### Install Project Dependencies Source: https://github.com/graphql-hive/federation-composition/blob/main/README.md Use this command to install all necessary project dependencies before running other commands. ```bash pnpm install ``` -------------------------------- ### Install Federation Composition Source: https://github.com/graphql-hive/federation-composition/blob/main/README.md Install the @theguild/federation-composition package using NPM, PNPM, or Yarn. ```bash # NPM npm install @theguild/federation-composition # PNPM pnpm add @theguild/federation-composition # Yarn yarn add @theguild/federation-composition ``` -------------------------------- ### Example Subgraph Configuration for Federation Composition Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/configuration.md Demonstrates how to configure multiple subgraphs with their respective type definitions and URLs for use with `composeServices`. ```typescript import { parse } from "graphql"; import { composeServices } from "@theguild/federation-composition"; const services = [ { name: "users", url: "https://users-api.example.com/graphql", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key"]) type User @key(fields: "id") { id: ID! email: String! name: String! } type Query { user(id: ID!): User } `), }, { name: "posts", url: "https://posts-api.example.com/graphql", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key", "@external"]) extend type User @key(fields: "id") { id: ID! @external posts: [Post!]! } type Post @key(fields: "id") { id: ID! title: String! author: User! } type Query { post(id: ID!): Post } `), }, ]; const result = composeServices(services); ``` -------------------------------- ### Handle Composition Success Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/types.md Example demonstrating how to check for composition success using compositionHasErrors() and access the supergraphSdl and publicSdl. ```typescript const result = composeServices(services); if (!compositionHasErrors(result)) { console.log("Supergraph:", result.supergraphSdl); console.log("Public API:", result.publicSdl); } ``` -------------------------------- ### Import Core Federation Composition APIs Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/README.md Import the main functions for service composition and validation from the federation-composition package. Ensure you have the package installed as a dependency. ```typescript import { composeServices, validate, validateSubgraph, compositionHasErrors, // ... etc } from "@theguild/federation-composition"; ``` -------------------------------- ### Compose Services and Write Outputs Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/configuration.md Compose services and conditionally write the supergraph SDL for gateway consumption and the public SDL for clients. This example also shows publishing to a schema registry. ```typescript const result = composeServices(services); if (!compositionHasErrors(result)) { // Write supergraph for gateway fs.writeFileSync("supergraph.graphql", result.supergraphSdl); // Write public schema for documentation/clients fs.writeFileSync("schema.graphql", result.publicSdl); // Publish to schema registry publishSupergraph(result.supergraphSdl); } ``` -------------------------------- ### Handle Composition Failure Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/types.md Example showing how to detect composition errors and iterate through the errors array to log each error's code and message. ```typescript const result = composeServices(services); if (compositionHasErrors(result)) { result.errors.forEach(error => { console.error(`${error.extensions.code}: ${error.message}`); }); } ``` -------------------------------- ### Extract Link Implementations Example Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/types.md Demonstrates how to use `extractLinkImplementations` to check for support of specific federation versions. This function helps determine if a given schema supports a particular version or range. ```typescript import { extractLinkImplementations, FEDERATION_V1 } from "@theguild/federation-composition"; const { matchesImplementation } = extractLinkImplementations(typeDefs); if (matchesImplementation("https://specs.apollo.dev/federation", "v2.3")) { console.log("Supports v2.3"); } if (matchesImplementation("https://specs.apollo.dev/federation", { major: 2, minor: 3 })) { console.log("Supports v2.3"); } if (matchesImplementation("https://specs.apollo.dev/federation", FEDERATION_V1)) { console.log("Is Federation v1"); } ``` -------------------------------- ### Compose Services from Files Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/examples.md This example demonstrates how to compose multiple GraphQL services by reading their schema definitions from local files. It handles reading, parsing, composing, and writing the resulting supergraph and public schemas. ```typescript import { readFileSync } from "fs"; import { parse } from "graphql"; import { composeServices, compositionHasErrors } from "@theguild/federation-composition"; const services = [ { name: "users", url: "http://localhost:4001", typeDefs: parse(readFileSync("./schemas/users.graphql", "utf-8")), }, { name: "posts", url: "http://localhost:4002", typeDefs: parse(readFileSync("./schemas/posts.graphql", "utf-8")), }, { name: "comments", url: "http://localhost:4003", typeDefs: parse(readFileSync("./schemas/comments.graphql", "utf-8")), }, ]; const result = composeServices(services); if (!compositionHasErrors(result)) { // Write outputs fs.writeFileSync("supergraph.graphql", result.supergraphSdl); fs.writeFileSync("public-schema.graphql", result.publicSdl); console.log("✓ Composition written to supergraph.graphql"); } else { console.error("Composition failed"); process.exit(1); } ``` -------------------------------- ### Configure @link Directive Imports Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/configuration.md Use the @link directive to control which federation features are available in your schema. This example imports several standard federation directives and demonstrates aliasing. ```graphql extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: [ "@key", "@external", "@requires", "@provides", "@shareable", "@inaccessible", "@override", { name: "@tag", as: "@myTag" } ]) ``` ```graphql @link(url: "https://specs.apollo.dev/federation/v2.3", import: [ { name: "@tag", as: "@myTag" }, { name: "@inaccessible", as: "@hidden" } ]) ``` -------------------------------- ### NO_QUERIES Error Example Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/errors.md This error occurs when no Query root type is defined in any subgraph. Ensure at least one subgraph defines a Query type with fields. ```text No Query root type defined in any subgraph ``` -------------------------------- ### Compose Supergraph with Webpack/esbuild Plugin Pattern Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/examples.md Discover and compose all schema files using glob patterns. This example is suitable for integration into build pipelines. ```typescript import { composeServices, compositionHasErrors } from "@theguild/federation-composition"; import { readFileSync } from "fs"; import { glob } from "glob"; import { parse } from "graphql"; async function composeSupergraph() { // Discover all schema files const schemaFiles = await glob("./subgraphs/*/schema.graphql"); const services = schemaFiles.map((file) => { const match = file.match(/subgraphs\/([^/]+)\/schema\.graphql/); const name = match?.[1] || "unknown"; const sdl = readFileSync(file, "utf-8"); return { name, typeDefs: parse(sdl), }; }); const result = composeServices(services); if (compositionHasErrors(result)) { throw new Error( `Composition failed:\n${result.errors.map((e) => e.message).join("\n")}` ); } return result; } // Export for use in build pipeline export default composeSupergraph(); ``` -------------------------------- ### Inspecting Federation Link Directives Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/examples.md This example demonstrates how to use `extractLinkImplementations` to parse link directives from schema definitions. It shows how to list linked features, resolve imported directive names, and check for support of specific federation versions. ```typescript import { extractLinkImplementations } from "@theguild/federation-composition"; import { parse } from "graphql"; const typeDefs = parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key", "@external"]) @link(url: "https://specs.apollo.dev/authenticated/v0.1", import: ["@authenticated"]) `); const { links, resolveImportName, matchesImplementation } = extractLinkImplementations(typeDefs); console.log("Linked features:"); links.forEach((link) => { console.log(` - ${link.identity} (${link.url})`); }); // Resolve actual name of @key directive const keyName = resolveImportName( "https://specs.apollo.dev/federation", "@key" ); console.log(`@key imported as: @${keyName}`); // Check version support if (matchesImplementation("https://specs.apollo.dev/federation", "v2.3")) { console.log("Supports Federation v2.3"); } ``` -------------------------------- ### Federation Version Auto-Detection Example Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/types.md Illustrates how the composition library automatically detects the highest federation version from schema `@link` directives. The `validate` function returns the maximum detected version. ```typescript const result = validate([ { name: "a", typeDefs: parse(`extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", ...)`) }, { name: "b", typeDefs: parse(`extend schema @link(url: "https://specs.apollo.dev/federation/v2.5", ...)`) }, ]); if (result.success) { console.log(result.federationVersion); // "v2.5" (the higher version) } ``` -------------------------------- ### ServiceDefinition Interface Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/types.md Represents a single federated subgraph service within a GraphQL Federation setup. It includes the type definitions, a unique name, and an optional URL for routing. ```APIDOC ## ServiceDefinition (Interface) ```typescript export interface ServiceDefinition { typeDefs: DocumentNode; name: string; url?: string; } ``` Represents one federated subgraph service in a federation. ### Fields | Field | Type | Required | Description | |-------|------|----------|-------------| | typeDefs | `DocumentNode` | Yes | GraphQL schema as a parsed DocumentNode. Must be obtained via `parse()` from the graphql package, not a string. Must declare `extend schema @link(...)` with a federation version. | | name | `string` | Yes | Unique subgraph identifier. Used in `@join__Graph` and composition error messages. Case-sensitive. Must not start with a digit. Recommended: lowercase alphanumeric (e.g., `"users"`, `"posts"`, `"accounts_service"`). | | url | `string` | No | Optional HTTP URL where the subgraph is deployed. Used by gateways for request routing. Not validated by composition; purely informational. | ### Example ```typescript const userService: ServiceDefinition = { name: "users", url: "https://users-api.example.com/graphql", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key"]) type User @key(fields: "id") { id: ID! email: String! } type Query { user(id: ID!): User } `) }; ``` ``` -------------------------------- ### Auto-Detect Maximum Federation Version Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/configuration.md When subgraphs declare different federation versions, the composition uses the maximum detected version. This example shows how to validate multiple type definitions and access the determined federation version. ```typescript const result = validate([ { name: "old-service", typeDefs: parse(`extend schema @link(url: "https://specs.apollo.dev/federation/v2.1", ...)`) }, { name: "new-service", typeDefs: parse(`extend schema @link(url: "https://specs.apollo.dev/federation/v2.5", ...)`) }, ]); if (result.success) { console.log(result.federationVersion); // "v2.5" } ``` -------------------------------- ### Compose GraphQL Subgraphs Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/INDEX.md Use `composeServices` to combine multiple GraphQL subgraphs into a single supergraph schema. This example demonstrates composing 'users' and 'posts' services, including error checking. ```typescript import { parse } from "graphql"; import { composeServices, compositionHasErrors } from "@theguild/federation-composition"; const result = composeServices([ { name: "users", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key"]) type User @key(fields: "id") { id: ID! name: String! } type Query { user(id: ID!): User } `), }, { name: "posts", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key", "@external"]) extend type User @key(fields: "id") { id: ID! @external posts: [Post!]! } type Post @key(fields: "id") { id: ID! title: String! } type Query { post(id: ID!): Post } `), }, ]); if (compositionHasErrors(result)) { console.error("Errors:", result.errors); } else { console.log("Supergraph:", result.supergraphSdl); console.log("Public API:", result.publicSdl); } ``` -------------------------------- ### Unknown Directive Error Example Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/errors.md This error is triggered when a directive is used in a schema but is not defined anywhere. Ensure all directives are defined before use, check for typos, or import external directives using `@link`. ```text Unknown directive "@unknownDir" ``` -------------------------------- ### INVALID_SUBGRAPH_NAME Error Example Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/errors.md This error is triggered by invalid subgraph names, such as those starting with a digit or containing invalid characters. Subgraph names must start with a letter and contain only alphanumeric characters and underscores. ```text Subgraph name "123-service" is invalid: must not start with a number and contain only alphanumeric characters and underscores ``` -------------------------------- ### Main Entry Point Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Import all necessary functions and types from the main entry point of the federation-composition library. ```APIDOC ## Main Entry Point ```typescript import { composeServices, validate, validateSubgraph, compositionHasErrors, assertCompositionSuccess, assertCompositionFailure, transformSupergraphToPublicSchema, containsSupergraphSpec, sortSDL, composeSchemaContract, addInaccessibleToUnreachableTypes, applyTagFilterOnSubgraphs, extractLinkImplementations, FEDERATION_V1, type CompositionResult, type CompositionSuccess, type CompositionFailure, type ServiceDefinition, type SchemaContractFilter, type FederationVersion, type LinkVersion, } from "@theguild/federation-composition" ``` ``` -------------------------------- ### Shareable Directive Usage Error Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/errors.md Indicates incorrect usage of the @shareable directive, such as on @external fields or root fields without proper federation setup. Remove @shareable from @external fields and ensure correct setup. ```graphql @shareable cannot be used on @external fields ``` -------------------------------- ### Import All Utilities from Main Entry Point Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/utilities.md Imports all available utility functions from the main entry point of the federation-composition library. ```typescript import { composeServices, transformSupergraphToPublicSchema, sortSDL, containsSupergraphSpec, extractLinkImplementations, composeSchemaContract, applyTagFilterOnSubgraphs, addInaccessibleToUnreachableTypes, } from "@theguild/federation-composition"; ``` -------------------------------- ### Run Project Tests Source: https://github.com/graphql-hive/federation-composition/blob/main/README.md Execute this command to run the project's test suite and verify the current state of the code. ```bash pnpm test ``` -------------------------------- ### OVERRIDE_FROM_SELF_ERROR Example Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/errors.md This error occurs when the @override directive references the same subgraph it is defined in. Ensure the 'from' argument points to a different subgraph. ```text @override(from: "users") cannot override from the same subgraph ``` -------------------------------- ### Import Main Federation Composition Exports Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Import all core functionalities from the main entry point of the federation-composition library. This includes functions for composing services, validation, error checking, schema transformation, and type definitions. ```typescript import { composeServices, validate, validateSubgraph, compositionHasErrors, assertCompositionSuccess, assertCompositionFailure, transformSupergraphToPublicSchema, containsSupergraphSpec, sortSDL, composeSchemaContract, addInaccessibleToUnreachableTypes, applyTagFilterOnSubgraphs, extractLinkImplementations, FEDERATION_V1, type CompositionResult, type CompositionSuccess, type CompositionFailure, type ServiceDefinition, type SchemaContractFilter, type FederationVersion, type LinkVersion, } from "@theguild/federation-composition" ``` -------------------------------- ### Import GraphQL Sort Utilities Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Import the sortSDL utility for sorting GraphQL schema definition language (SDL). ```typescript // Sort utilities import { sortSDL } from "@theguild/federation-composition/graphql/sort-sdl" ``` -------------------------------- ### Import GraphQL Printer Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Import the GraphQL printer utility for formatting schema definitions. ```typescript // GraphQL printer import { print } from "@theguild/federation-composition/graphql/printer" ``` -------------------------------- ### Resolve Imported Name with Alias Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/utilities.md Use this method to get the actual imported name of a feature, which is useful when an alias has been specified in the @link directive's import clause. ```typescript // Schema: @link(..., import: [{ name: "@tag", as: "@myTag" }]) const actualName = link.resolveImportName("@tag"); // "myTag" ``` -------------------------------- ### print Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Prints a GraphQL DocumentNode to a string (SDL). ```APIDOC ## print ### Description Prints a GraphQL DocumentNode to a string (SDL). ### Signature ```typescript function print(ast: DocumentNode): string ``` ### Parameters - `ast` (DocumentNode) - The GraphQL Abstract Syntax Tree to print. ### Returns - `string` - The SDL representation of the DocumentNode. ``` -------------------------------- ### OVERRIDE_SOURCE_HAS_OVERRIDE Error Example Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/errors.md This error indicates a field marked with @override is itself being overridden, often due to multiple @override directives in a chain. Limit @override usage to a single chain. ```text Field User.email is marked with @override in subgraph "accounts" but is also being overridden by subgraph "backup" ``` -------------------------------- ### Import Link Utilities from Federation Composition Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Import specific utilities for handling Link specifications, including implementation extraction and federation version constants. ```typescript // Link utilities import { extractLinkImplementations, FEDERATION_V1, type LinkVersion } from "@theguild/federation-composition/utils/link" ``` -------------------------------- ### Get Reachable Types from Schema Document Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/utilities.md Analyzes a schema document and returns the set of all types reachable from the root Query type. Used to identify types that should be marked with `@inaccessible`. ```typescript import { parse } from "graphql"; import { getReachableTypes } from "@theguild/federation-composition/contracts/reachable-type-filter"; const schema = parse(` type Query { user: User } type User { posts: [Post!]! } type Post { title: String! } type Archive { data: String! } `); const reachable = getReachableTypes(schema); console.log(reachable); // Set(["Query", "User", "Post"]) // "Archive" is not included as it's unreachable ``` -------------------------------- ### Federation Composition Module Structure Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/INDEX.md This tree displays the directory and file structure of the federation-composition library, highlighting key modules like composition, validation, and utilities. ```tree federation-composition/ ├── src/ │ ├── compose.ts # Main composeServices() │ ├── validate.ts # Validation functions │ ├── types.ts # Type definitions │ ├── index.ts # Public exports │ ├── graphql/ # GraphQL utilities │ │ ├── transform-supergraph-to-public-schema.ts │ │ ├── sort-sdl.ts │ │ ├── contains-supergraph-spec.ts │ │ └── printer.ts │ ├── utils/ # Utility functions │ │ └── link/ # Link directive utilities │ ├── contracts/ # Schema contract support │ │ ├── schema-contract.ts │ │ ├── tag-extraction.ts │ │ └── add-inaccessible-to-unreachable-types.ts │ ├── subgraph/ # Subgraph validation │ ├── supergraph/ # Supergraph composition │ └── specifications/ # Federation specs ├── package.json └── README.md ``` -------------------------------- ### print Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/utilities.md Prints a GraphQL DocumentNode back to SDL string format. This custom printer preserves formatting preferences for federation schemas. ```APIDOC ## print ### Description Prints a GraphQL DocumentNode back to SDL string format. Custom printer that preserves formatting preferences for federation schemas. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method - Not applicable (function signature) ### Endpoint - Not applicable (function signature) ### Request Example ```typescript import { parse, print } from "graphql"; import { sortSDL } from "@theguild/federation-composition"; const sdl = `...`; // Your SDL string const doc = parse(sdl); const sorted = sortSDL(doc); const output = print(sorted); ``` ### Response #### Success Response - **Type**: `string` - **Description**: GraphQL SDL representation of the document #### Response Example ```typescript // Example output string const output = "type Query {\n field: String\n}"; ``` ``` -------------------------------- ### Compose Services with @key and @requires Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/examples.md Demonstrates composing multiple services using federation directives. The `Account` type is extended in the `orders` service, and its `orders` field requires the `email` field from `Account`. ```typescript const result = composeServices([ { name: "accounts", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key"]) type Account @key(fields: "id") { id: ID! email: String! createdAt: String! } type Query { account(id: ID!): Account } `), }, { name: "orders", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key", "@external", "@requires"]) extend type Account @key(fields: "id") { id: ID! @external email: String! @external orders: [Order!]! @requires(fields: "email") } type Order @key(fields: "id") { id: ID! total: Float! } type Query { order(id: ID!): Order } `), }, ]); ``` -------------------------------- ### Directive Composition Error Example Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/errors.md This error occurs when directives cannot be composed due to inconsistencies across subgraphs. Ensure directives are defined identically, including `repeatable` settings, argument types, and locations. ```text Directive @customTag cannot be composed: repeatable mismatch between subgraph "a" and "b" ``` -------------------------------- ### Invalid Directive Definition Error Example Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/errors.md This error indicates an issue with the syntax or semantics of a directive definition. Verify that directive locations are valid according to the GraphQL specification, arguments are unique, and names are compliant. ```text @myDirective has invalid location FIELD_DEFINITION_ARGUMENT ``` -------------------------------- ### Compose Multiple Schema Contracts Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/examples.md Demonstrates composing multiple schema contracts from the same set of services, using different 'include' and 'exclude' tag sets. This allows for versioning or creating specialized API views. ```typescript const v1Contract = composeSchemaContract( services, { include: new Set(["v1", "public"]), exclude: new Set(["v2only"]), }, ); const v2Contract = composeSchemaContract( services, { include: new Set(["v2", "public"]), exclude: new Set(["deprecated"]), }, ); const betaContract = composeSchemaContract( services, { include: new Set(["beta"]), exclude: new Set(), }, ); ``` -------------------------------- ### Enable Debug Logging for Composition Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/configuration.md Use the `DEBUG` environment variable to enable verbose logging for the composition library. You can enable all logs or specific modules like `validate` or `compose`. ```bash # Enable all composition debug logs DEBUG=composition:* node app.js ``` ```bash # Enable specific module logs DEBUG=composition:validate node app.js DEBUG=composition:compose node app.js ``` ```bash # Color output DEBUG_COLORS=0 DEBUG=composition:* node app.js ``` -------------------------------- ### Compare GraphQL Schemas After Normalization Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/utilities.md Compares two GraphQL schemas for equality after normalizing and sorting them. Demonstrates that different declaration orders result in identical sorted SDL. ```typescript import { parse, print } from "graphql"; import { sortSDL } from "@theguild/federation-composition"; const sdl1 = ` type Query { z: String a: String } `; const sdl2 = ` type Query { a: String z: String } `; const sorted1 = print(sortSDL(parse(sdl1))); const sorted2 = print(sortSDL(parse(sdl2))); console.log(sorted1 === sorted2); // true ``` -------------------------------- ### Link Utilities Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Utilities for working with Link directives and implementations. ```APIDOC ## extractLinkImplementations ### Description Extracts Link implementations from type definitions. ``` -------------------------------- ### Link Utilities Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/README.md Utilities for working with the `@link` directive in Federation. ```APIDOC ## extractLinkImplementations() ### Description Extracts and resolves `@link` directives from subgraph schemas, matching them by version. ### Method `function extractLinkImplementations(services: ServiceDefinition[], options?: ExtractLinkImplementationsOptions): LinkImplementationsResult` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { extractLinkImplementations } from '@theguild/federation-composition'; const services = [...]; // Service definitions const result = extractLinkImplementations(services); if (result.errors) { console.error('Failed to extract link implementations:', result.errors); } else { console.log('Link implementations:', result.implementations); } ``` ### Response #### Success Response (LinkImplementationsResult) - **implementations** (Array) - An array of resolved link implementations. - **errors** (Array) - An array of errors encountered during extraction (empty if successful). #### Response Example ```json { "implementations": [ { "url": "...", "version": "1.0.0", "typeDefs": "..." } ], "errors": [] } ``` ``` -------------------------------- ### Link Utilities Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Utilities for handling link versions and extracting link implementations from type definitions. ```APIDOC ## Link Utilities (src/utils/link/index.ts) ### `extractLinkImplementations` Function This function extracts link implementations from GraphQL type definitions. #### Parameters - `typeDefs` (DocumentNode) - The GraphQL type definitions to process. #### Returns An object containing: - `links` (FederatedLink[]) - A list of extracted federated links. - `resolveImportName` (function) - A function to resolve import names. - `matchesImplementation` (function) - A function to check if an identity matches a link version. ``` -------------------------------- ### buildSchemaCoordinateTagRegister Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/INDEX.md Builds a registration map for schema coordinates and their associated tags, useful for schema management and analysis. ```APIDOC ## buildSchemaCoordinateTagRegister() ### Description Build tag index. ### Returns `Map>` ``` -------------------------------- ### Normalize SDL for Comparison Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/INDEX.md Use `sortSDL` from `@theguild/federation-composition` along with `parse` and `print` from `graphql` to normalize a schema definition string. This ensures consistent formatting for comparisons. ```typescript import { sortSDL } from "@theguild/federation-composition"; import { parse, print } from "graphql"; const normalized = print(sortSDL(parse(sdl))); ``` -------------------------------- ### Schema Contracts Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/README.md Utilities for working with schema contracts in Federation. ```APIDOC ## composeSchemaContract() ### Description Composes a schema contract from a set of subgraph definitions. ### Method `function composeSchemaContract(services: ServiceDefinition[], options?: ComposeSchemaContractOptions): CompositionResult` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { composeSchemaContract } from '@theguild/federation-composition'; const services = [...]; // Service definitions const result = composeSchemaContract(services); if (result.errors) { console.error('Schema contract composition failed:', result.errors); } else { console.log('Schema contract SDL:', result.publicSdl); } ``` ### Response #### Success Response (CompositionSuccess) - **publicSdl** (string) - The composed schema contract in SDL format. - **errors** (Array) - An array of errors encountered during composition (empty if successful). #### Response Example ```json { "publicSdl": "...", "errors": [] } ``` ## applyTagFilterOnSubgraphs() ### Description Applies a tag filter to subgraph schemas, returning only the types and fields matching the specified tags. ### Method `function applyTagFilterOnSubgraphs(services: ServiceDefinition[], tagFilter: string[], options?: ApplyTagFilterOptions): CompositionResult` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { applyTagFilterOnSubgraphs } from '@theguild/federation-composition'; const services = [...]; // Service definitions const tagFilter = ['v1']; const result = applyTagFilterOnSubgraphs(services, tagFilter); if (result.errors) { console.error('Tag filtering failed:', result.errors); } else { console.log('Filtered schema SDL:', result.publicSdl); } ``` ### Response #### Success Response (CompositionSuccess) - **publicSdl** (string) - The filtered schema in SDL format. - **errors** (Array) - An array of errors encountered during filtering (empty if successful). #### Response Example ```json { "publicSdl": "...", "errors": [] } ``` ``` -------------------------------- ### Compose Two Services with Federation Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/examples.md Composes two GraphQL services, 'users' and 'posts', into a single supergraph. Handles potential composition errors and logs the resulting supergraph SDL and public API schema. ```typescript import { parse } from "graphql"; import { composeServices, compositionHasErrors } from "@theguild/federation-composition"; const result = composeServices([ { name: "users", url: "http://users-service:4001/graphql", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key"]) type User @key(fields: "id") { id: ID! name: String! email: String! } type Query { me: User user(id: ID!): User } `), }, { name: "posts", url: "http://posts-service:4002/graphql", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key", "@external"]) extend type User @key(fields: "id") { id: ID! @external posts: [Post!]! } type Post @key(fields: "id") { id: ID! title: String! content: String! authorId: ID! } type Query { post(id: ID!): Post posts: [Post!]! } `), }, ]); if (compositionHasErrors(result)) { console.error("Composition failed:"); result.errors.forEach((error) => { console.error(` - [${error.extensions?.code}] ${error.message}`); }); process.exit(1); } else { console.log("✓ Composition succeeded"); console.log("\nSupergraph SDL:"); console.log(result.supergraphSdl); console.log("\nPublic API Schema:"); console.log(result.publicSdl); } ``` -------------------------------- ### Print GraphQL DocumentNode to SDL Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/utilities.md Prints a GraphQL DocumentNode back to SDL string format. This custom printer preserves formatting preferences for federation schemas. ```typescript import { print } from "@theguild/federation-composition/graphql/printer" export function print(ast: DocumentNode): string ``` -------------------------------- ### Create Multi-Version Schema Contracts Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/configuration.md Generate different API versions (e.g., v1 and v2) by calling `composeSchemaContract` with distinct `include` and `exclude` tag sets for each version. This allows for phased rollouts and backward compatibility. ```typescript // v1 API const v1 = composeSchemaContract(services, { include: new Set(["v1", "public"]), exclude: new Set(["v2only", "experimental"]), }); // v2 API const v2 = composeSchemaContract(services, { include: new Set(["v2", "public"]), exclude: new Set(["deprecated", "experimental"]), }); ``` -------------------------------- ### FederationVersion Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/api-reference.md Defines the supported Apollo Federation versions. ```APIDOC ## FederationVersion ### Description Supported Apollo Federation versions. The composition library supports all listed versions and will auto-detect which version to use based on schema declarations. ### Possible Values - `"v1.0"` - `"v2.0"` - `"v2.1"` - `"v2.2"` - `"v2.3"` - `"v2.4"` - `"v2.5"` - `"v2.6"` - `"v2.7"` - `"v2.8"` - `"v2.9"` ``` -------------------------------- ### Federation Versioning Functions Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Functions for managing and detecting Federation versions. ```APIDOC ## isFederationVersion ### Description Checks if a given string is a valid Federation version. ### Signature ```typescript function isFederationVersion(version: string): version is FederationVersion ``` ## detectFederationVersion ### Description Detects the Federation version from provided type definitions. ### Signature ```typescript function detectFederationVersion(typeDefs: DocumentNode): { version: FederationVersion; } ``` ``` -------------------------------- ### Import Specific Utilities from Submodules Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/utilities.md Imports specific utility functions from their respective submodules within the federation-composition library. ```typescript import { sortSDL } from "@theguild/federation-composition/graphql/sort-sdl"; ``` ```typescript import { FederatedLink } from "@theguild/federation-composition/utils/link"; ``` -------------------------------- ### Check Link Version Support (String) Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/utilities.md Use this method to check if a FederatedLink supports a given version string (e.g., "2.3"). Pass null to check if any version is supported. ```typescript const link = FederatedLink.fromTypedefs(typeDefs)[0]; if (link.supports("2.3")) { console.log("Supports v2.3"); } if (link.supports(null)) { console.log("Supports any version"); } ``` -------------------------------- ### Parse GraphQL Document Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/types.md Demonstrates how to parse a GraphQL SDL string into a DocumentNode using the parse function from the graphql package. This is a fundamental step before validating or composing schemas. ```typescript import { parse } from "graphql"; const doc: DocumentNode = parse(` type Query { hello: String } `); ``` -------------------------------- ### Federation Specification Creation Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Function for creating Federation specification schemas. ```APIDOC ## createSpecSchema ### Description Creates a specification schema for a given Federation version. ### Parameters - `version` (FederationVersion & string) - The Federation version to create the schema for. - `imports` (readonly LinkImport[]) - Optional. Link imports to include in the schema. ### Signature ```typescript function createSpecSchema(version: T, imports?: readonly LinkImport[]) ``` ``` -------------------------------- ### Federation Version Types and Functions Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/EXPORTS.md Defines types for Federation versions and imports, and provides functions to check and detect Federation versions. Use `isFederationVersion` to narrow down types and `detectFederationVersion` to infer the version from schema type definitions. ```typescript export type FederationVersion = keyof typeof federationSpecFactory export type FederationImports = readonly LinkImport[] export function isFederationVersion(version: string): version is FederationVersion export function createSpecSchema( version: T, imports?: readonly LinkImport[], ) export function detectFederationVersion(typeDefs: DocumentNode): { version: FederationVersion; } ``` -------------------------------- ### Core Functions Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/README.md This section details the core functions available in the federation-composition library for composing and validating GraphQL schemas. ```APIDOC ## composeServices() ### Description Composes multiple subgraph schemas into a single supergraph schema. ### Method `function composeServices(services: ServiceDefinition[], options?: CompositionOptions): CompositionResult` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { composeServices } from '@theguild/federation-composition'; const services = [ { name: 'users', url: 'http://localhost:4001/graphql' }, { name: 'products', url: 'http://localhost:4002/graphql' }, ]; const result = composeServices(services); if (result.errors) { console.error('Composition failed:', result.errors); } else { console.log('Supergraph schema:', result.supergraphSdl); } ``` ### Response #### Success Response (CompositionSuccess) - **supergraphSdl** (string) - The composed supergraph schema in SDL format. - **publicSdl** (string) - The composed public schema in SDL format (if applicable). - **errors** (Array) - An array of errors encountered during composition (empty if successful). #### Response Example ```json { "supergraphSdl": "type Query { ... }", "publicSdl": "type Query { ... }", "errors": [] } ``` ## validate() ### Description Validates a set of subgraph schemas without composing them into a supergraph. ### Method `function validate(services: ServiceDefinition[], options?: ValidationOptions): CompositionResult` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { validate } from '@theguild/federation-composition'; const services = [ { name: 'users', url: 'http://localhost:4001/graphql' }, ]; const result = validate(services); if (result.errors) { console.error('Validation failed:', result.errors); } ``` ### Response #### Success Response (CompositionSuccess) - **errors** (Array) - An array of errors encountered during validation (empty if successful). #### Response Example ```json { "errors": [] } ``` ## validateSubgraph() ### Description Validates a single subgraph schema against the Federation specification. ### Method `function validateSubgraph(service: ServiceDefinition, options?: SubgraphValidationOptions): CompositionResult` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { validateSubgraph } from '@theguild/federation-composition'; const service = { name: 'users', url: 'http://localhost:4001/graphql' }; const result = validateSubgraph(service); if (result.errors) { console.error('Subgraph validation failed:', result.errors); } ``` ### Response #### Success Response (CompositionSuccess) - **errors** (Array) - An array of errors encountered during subgraph validation (empty if successful). #### Response Example ```json { "errors": [] } ``` ``` -------------------------------- ### Type Definitions Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/COMPLETION_REPORT.txt Key type definitions used within the federation composition API. ```APIDOC ## Type Definitions ### CompositionResult Represents the result of a composition operation. - **supergraphSchema** (string) - The composed supergraph schema. - **errors** (ValidationError[]) - An array of validation errors. ### CompositionSuccess Represents a successful composition result. - **supergraphSchema** (string) - The composed supergraph schema. ### CompositionFailure Represents a failed composition result. - **errors** (ValidationError[]) - An array of validation errors. ### ServiceDefinition Defines a single GraphQL service (subgraph). - **name** (string) - The name of the service. - **url** (string) - The URL of the service. - **typeDefs** (string) - The schema definition language (SDL) for the service. - **config** (object) - Optional configuration for the service. ### SchemaContractFilter Defines criteria for filtering schema contracts. - **tag** (string) - The tag to filter by. ### FederationVersion Represents a version of the GraphQL Federation specification. - **major** (number) - The major version number. - **minor** (number) - The minor version number. ### LinkVersion Represents a version of the Link specification. - **major** (number) - The major version number. - **minor** (number) - The minor version number. ### FEDERATION_V1 (symbol) A symbol representing Federation version 1. ``` -------------------------------- ### composeServices Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/api-reference.md Composes a set of federated GraphQL subgraphs into a supergraph. It validates each subgraph and then performs supergraph-level validation before generating the final supergraph SDL. ```APIDOC ## composeServices ### Description Composes a set of federated GraphQL subgraphs into a supergraph. Validates each subgraph and then performs supergraph-level validation before generating the final supergraph SDL. ### Method ```typescript export function composeServices( services: ServiceDefinition[], __internal?: { disableValidationRules?: string[]; }, ): CompositionResult ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **services** (ServiceDefinition[]) - Required - Array of subgraph definitions to compose - **__internal** (object) - Optional - Internal options for development/benchmarking - **__internal.disableValidationRules** (string[]) - Optional - Rule names to skip during validation (benchmark only) ### Request Example ```typescript import { parse } from "graphql"; import { composeServices, compositionHasErrors } from "@theguild/federation-composition"; const result = composeServices([ { name: "users", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key"]) type User @key(fields: "id") { id: ID! name: String! } type Query { users: [User] } `), }, { name: "posts", typeDefs: parse(` extend schema @link(url: "https://specs.apollo.dev/federation/v2.3", import: ["@key", "@external"]) extend type User @key(fields: "id") { id: ID! @external posts: [Post] } type Post { id: ID! title: String! } `), }, ]); if (compositionHasErrors(result)) { console.error("Composition failed:", result.errors); } else { console.log("Supergraph SDL:", result.supergraphSdl); console.log("Public SDL:", result.publicSdl); } ``` ### Response #### Success Response (200) `CompositionResult` — Either `CompositionSuccess` with supergraphSdl and publicSdl, or `CompositionFailure` with errors array. Use `compositionHasErrors()` to discriminate. #### Response Example None provided. ``` -------------------------------- ### CompositionSuccess (Interface) Source: https://github.com/graphql-hive/federation-composition/blob/main/_autodocs/types.md Represents a successful federation composition. It contains the supergraph SDL and the public API schema. ```APIDOC ## CompositionSuccess (Interface) ### Description Result type when federation composition succeeds without validation errors. ### Fields - **supergraphSdl** (`string`) - Required - Complete supergraph in GraphQL SDL format. Includes all federation directives (`@join`, `@link`, etc.) and internal implementation details. Can be used with Apollo Router or any gateway that understands Supergraph SDL. - **publicSdl** (`string`) - Required - Public API schema derived from supergraph. Strips federation directives (`@join`, `@link`, `@inaccessible`, etc.) and internal types. This is what clients see. Computed lazily on first access. - **errors** (`undefined`) - Not Applicable - Always undefined for success case ### Example ```typescript const result = composeServices(services); if (!compositionHasErrors(result)) { console.log("Supergraph:", result.supergraphSdl); console.log("Public API:", result.publicSdl); } ``` ```