Skip to content

feat(cli): add 'fern export' command #7586

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jun 23, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions packages/cli/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
"@fern-api/openapi-ir-parser": "workspace:*",
"@fern-api/openapi-ir-to-fern": "workspace:*",
"@fern-api/oss-validator": "workspace:*",
"@fern-api/path-utils": "workspace:*",
"@fern-api/posthog-manager": "workspace:*",
"@fern-api/project-loader": "workspace:*",
"@fern-api/register": "workspace:*",
Expand All @@ -92,6 +93,7 @@
"@types/lodash-es": "^4.17.12",
"@types/semver": "^7.5.8",
"@types/tar": "^6.1.11",
"@types/url-join": "4.0.1",
"@types/validate-npm-package-name": "^4.0.0",
"@types/yargs": "^17.0.28",
"ansi-escapes": "^5.0.0",
Expand All @@ -106,11 +108,13 @@
"latest-version": "^9.0.0",
"lodash-es": "^4.17.21",
"ora": "^7.0.1",
"openapi-types": "^12.1.3",
"semver": "^7.6.2",
"tar": "^6.2.1",
"tmp-promise": "^3.0.3",
"tsup": "^8.3.5",
"undici": "^6.21.1",
"url-join": "^5.0.0",
"validate-npm-package-name": "^5.0.1",
"yaml": "^2.4.5",
"yargs": "^17.4.1",
Expand Down
37 changes: 37 additions & 0 deletions packages/cli/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { addGeneratorCommands, addGetOrganizationCommand } from "./cliV2";
import { addGeneratorToWorkspaces } from "./commands/add-generator/addGeneratorToWorkspaces";
import { diff } from "./commands/diff/diff";
import { previewDocsWorkspace } from "./commands/docs-dev/devDocsWorkspace";
import { generateOpenAPIForWorkspaces } from "./commands/export/generateOpenAPIForWorkspaces";
import { formatWorkspaces } from "./commands/format/formatWorkspaces";
import { generateDynamicIrForWorkspaces } from "./commands/generate-dynamic-ir/generateDynamicIrForWorkspaces";
import { generateFdrApiDefinitionForWorkspaces } from "./commands/generate-fdr/generateFdrApiDefinitionForWorkspaces";
Expand Down Expand Up @@ -182,6 +183,7 @@ async function tryRunCli(cliContext: CliContext) {
});
addGenerateJsonschemaCommand(cli, cliContext);
addWriteDocsDefinitionCommand(cli, cliContext);
addExportCommand(cli, cliContext);

// CLI V2 Sanctioned Commands
addGetOrganizationCommand(cli, cliContext);
Expand Down Expand Up @@ -1340,3 +1342,38 @@ function addWriteDocsDefinitionCommand(cli: Argv<GlobalCliOptions>, cliContext:
}
);
}

function addExportCommand(cli: Argv<GlobalCliOptions>, cliContext: CliContext) {
cli.command(
"export <output-path>",
"Export your API to an OpenAPI spec",
(yargs) =>
yargs
.positional("output-path", {
type: "string",
description: "Path to write the OpenAPI spec",
demandOption: true
})
.option("api", {
string: true,
description: "Only run the command on the provided API"
}),
async (argv) => {
await cliContext.instrumentPostHogEvent({
command: "fern export",
properties: {
outputPath: argv.outputPath
}
});

await generateOpenAPIForWorkspaces({
project: await loadProjectAndRegisterWorkspacesWithContext(cliContext, {
commandLineApiWorkspace: argv.api,
defaultToAllApiWorkspaces: false
}),
cliContext,
outputPath: resolve(cwd(), argv.outputPath)
});
}
);
}
103 changes: 103 additions & 0 deletions packages/cli/cli/src/commands/export/convertIrToOpenApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { OpenAPIV3 } from "openapi-types";

import {
DeclaredErrorName,
DeclaredTypeName,
ErrorDeclaration,
IntermediateRepresentation,
TypeDeclaration
} from "@fern-api/ir-sdk";

import { convertServices } from "./converters/servicesConverter";
import { convertType } from "./converters/typeConverter";
import { constructEndpointSecurity, constructSecuritySchemes } from "./security";

export type Mode = "stoplight" | "openapi";

export function convertIrToOpenApi({
apiName,
ir,
mode
}: {
apiName: string;
ir: IntermediateRepresentation;
mode: Mode;
}): OpenAPIV3.Document | undefined {
const schemas: Record<string, OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject> = {};

const typesByName: Record<string, TypeDeclaration> = {};
Object.values(ir.types).forEach((typeDeclaration) => {
// convert type to open api schema
const convertedType = convertType(typeDeclaration, ir);
schemas[convertedType.schemaName] = {
title: convertedType.schemaName,
...convertedType.openApiSchema
};
// populates typesByName map
typesByName[getDeclaredTypeNameKey(typeDeclaration.name)] = typeDeclaration;
});

const errorsByName: Record<string, ErrorDeclaration> = {};
Object.values(ir.errors).forEach((errorDeclaration) => {
errorsByName[getErrorTypeNameKey(errorDeclaration.name)] = errorDeclaration;
});

const security = constructEndpointSecurity(ir.auth);

const paths = convertServices({
ir,
httpServices: Object.values(ir.services),
typesByName,
errorsByName,
errorDiscriminationStrategy: ir.errorDiscriminationStrategy,
security,
environments: ir.environments ?? undefined,
mode
});

const info: OpenAPIV3.InfoObject = {
title: ir.apiDisplayName ?? apiName,
version: ""
};
if (ir.apiDocs != null) {
info.description = ir.apiDocs;
}

const openAPISpec: OpenAPIV3.Document = {
openapi: "3.0.1",
info,
paths,
components: {
schemas,
securitySchemes: constructSecuritySchemes(ir.auth)
}
};

if (ir.environments != null && ir.environments.environments.type === "singleBaseUrl") {
openAPISpec.servers = ir.environments.environments.environments.map((environment) => {
return {
url: environment.url,
description:
environment.docs != null
? `${environment.name.originalName} (${environment.docs})`
: environment.name.originalName
};
});
}

return openAPISpec;
}

export function getDeclaredTypeNameKey(declaredTypeName: DeclaredTypeName): string {
return [
...declaredTypeName.fernFilepath.allParts.map((part) => part.originalName),
declaredTypeName.name.originalName
].join("-");
}

export function getErrorTypeNameKey(declaredErrorName: DeclaredErrorName): string {
return [
...declaredErrorName.fernFilepath.allParts.map((part) => part.originalName),
declaredErrorName.name.originalName
].join("-");
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { OpenAPIV3 } from "openapi-types";

import {
DeclaredTypeName,
ExampleInlinedRequestBodyProperty,
ExampleObjectProperty,
NameAndWireValue,
TypeReference
} from "@fern-api/ir-sdk";

import { OpenApiComponentSchema, convertTypeReference, getReferenceFromDeclaredTypeName } from "./typeConverter";

export interface ObjectProperty {
docs: string | undefined;
name: NameAndWireValue;
valueType: TypeReference;
example?: ExampleObjectProperty | ExampleInlinedRequestBodyProperty;
}

export function convertObject({
docs,
properties,
extensions
}: {
docs: string | undefined;
properties: ObjectProperty[];
extensions: DeclaredTypeName[];
}): OpenAPIV3.SchemaObject {
const convertedProperties: Record<string, OpenApiComponentSchema> = {};
const required: string[] = [];
properties.forEach((objectProperty) => {
const convertedObjectProperty = convertTypeReference(objectProperty.valueType);

let example: unknown = undefined;
if (objectProperty.example != null && objectProperty.valueType.type === "primitive") {
example = objectProperty.example.value.jsonExample;
} else if (
objectProperty.example != null &&
objectProperty.valueType.type === "container" &&
objectProperty.valueType.container.type === "list" &&
objectProperty.valueType.container.list.type === "primitive"
) {
example = objectProperty.example.value.jsonExample;
}

convertedProperties[objectProperty.name.wireValue] = {
...convertedObjectProperty,
description: objectProperty.docs ?? undefined,
example
};
const isOptionalProperty =
objectProperty.valueType.type === "container" && objectProperty.valueType.container.type === "optional";
if (!isOptionalProperty) {
required.push(objectProperty.name.wireValue);
}
});
const convertedSchemaObject: OpenAPIV3.SchemaObject = {
type: "object",
description: docs,
properties: convertedProperties
};
if (required.length > 0) {
convertedSchemaObject.required = required;
}
if (extensions.length > 0) {
convertedSchemaObject.allOf = extensions.map((declaredTypeName) => {
return {
$ref: getReferenceFromDeclaredTypeName(declaredTypeName)
};
});
}
return convertedSchemaObject;
}
Loading
Loading