-
Notifications
You must be signed in to change notification settings - Fork 343
Expand file tree
/
Copy pathApiSpecResolver.ts
More file actions
174 lines (158 loc) · 6.72 KB
/
Copy pathApiSpecResolver.ts
File metadata and controls
174 lines (158 loc) · 6.72 KB
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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import { AbsoluteFilePath, doesPathExist, resolve } from "@fern-api/fs-utils";
import { CliError } from "@fern-api/task-context";
import { mkdtemp, readFile, writeFile } from "fs/promises";
import { tmpdir } from "os";
import path from "path";
import { Readable } from "stream";
import { FETCH_API_SPEC_REQUEST_TIMEOUT_MS } from "../../constants.js";
import type { Context } from "../../context/Context.js";
import { FernCliErrors } from "../../errors/wellKnown/CliErrors.js";
import { isStdioMarker, readInput, STDIO_MARKER } from "../../io/stdio.js";
import type { ApiSpec, ApiSpecType } from "../config/ApiSpec.js";
import { ApiSpecDetector } from "./ApiSpecDetector.js";
export namespace ApiSpecResolver {
export interface Args {
reference: string;
/** Optional stdin stream (defaults to process.stdin). Used for testing. */
stdin?: Readable;
}
export interface Result {
/* The absolute file path to the file (i.e. downloaded from a URL or local file). */
absoluteFilePath: AbsoluteFilePath;
/* The original user-provided reference (path or URL), used in error messages. */
reference: string;
/* The API specification. */
spec: ApiSpec;
}
}
export class ApiSpecResolver {
private readonly context: Context;
private readonly detector: ApiSpecDetector;
constructor({ context }: { context: Context }) {
this.context = context;
this.detector = new ApiSpecDetector();
}
/**
* Resolves a string reference (local path, URL, or `-` for stdin) to a
* fully-constructed ApiSpec.
*/
public async resolve(args: ApiSpecResolver.Args): Promise<ApiSpecResolver.Result> {
if (isStdioMarker(args.reference)) {
return this.resolveStdin({ stdin: args.stdin });
}
if (this.isUrl(args.reference)) {
return this.resolveUrl(args);
}
return this.resolveLocal(args);
}
private async resolveStdin({ stdin }: { stdin?: Readable }): Promise<ApiSpecResolver.Result> {
const content = await readInput(STDIO_MARKER, { stdin });
if (content.trim().length === 0) {
throw FernCliErrors.EmptyStdin();
}
const extension = this.inferExtensionFromContent(content);
const tempDir = await mkdtemp(path.join(tmpdir(), "fern-"));
const absoluteFilePath = AbsoluteFilePath.of(path.join(tempDir, `spec${extension}`));
await writeFile(absoluteFilePath, content, "utf-8");
const specType = await this.detector.detect({ absoluteFilePath, content, reference: "stdin" });
return {
absoluteFilePath,
reference: "stdin",
spec: this.buildApiSpec({ absoluteFilePath, specType, origin: "stdin" })
};
}
private inferExtensionFromContent(content: string): string {
const trimmed = content.trimStart();
const first = trimmed[0];
return first === "{" || first === "[" ? ".json" : ".yaml";
}
private async resolveUrl({ reference }: { reference: string }): Promise<ApiSpecResolver.Result> {
const { content, contentType } = await this.fetchContent({ url: reference });
const extension = this.inferExtension({ url: reference, contentType });
const tempDir = await mkdtemp(path.join(tmpdir(), "fern-"));
const absoluteFilePath = AbsoluteFilePath.of(path.join(tempDir, `spec${extension}`));
await writeFile(absoluteFilePath, content, "utf-8");
const specType = await this.detector.detect({ absoluteFilePath, content, reference });
return {
absoluteFilePath,
reference,
spec: this.buildApiSpec({ absoluteFilePath, specType, origin: reference })
};
}
private async resolveLocal({ reference }: { reference: string }): Promise<ApiSpecResolver.Result> {
const absoluteFilePath = resolve(this.context.cwd, reference);
if (!(await doesPathExist(absoluteFilePath))) {
throw FernCliErrors.FileNotFound({ path: reference });
}
const content = await readFile(absoluteFilePath, "utf-8");
const specType = await this.detector.detect({ absoluteFilePath, content, reference });
return {
absoluteFilePath,
reference,
spec: this.buildApiSpec({ absoluteFilePath, specType })
};
}
private async fetchContent({ url }: { url: string }): Promise<{ content: string; contentType: string }> {
const response = await fetch(url, { signal: AbortSignal.timeout(FETCH_API_SPEC_REQUEST_TIMEOUT_MS) });
if (!response.ok) {
throw FernCliErrors.HttpFetchFailed({
url,
status: response.status,
statusText: response.statusText
});
}
const contentType = response.headers.get("content-type") ?? "";
if (contentType.includes("text/html")) {
throw new CliError({
message:
`The URL "${url}" returned HTML content. ` +
`Ensure you're pointing to a raw spec URL, not a documentation page.`,
code: CliError.Code.ConfigError
});
}
const content = await response.text();
return { content, contentType };
}
private inferExtension({ url, contentType }: { url: string; contentType: string }): string {
const urlPath = new URL(url).pathname.toLowerCase();
if (urlPath.endsWith(".graphql") || urlPath.endsWith(".graphqls") || urlPath.endsWith(".gql")) {
return ".graphql";
}
if (urlPath.endsWith(".json")) {
return ".json";
}
if (urlPath.endsWith(".yaml") || urlPath.endsWith(".yml")) {
return ".yaml";
}
if (contentType.includes("json")) {
return ".json";
}
return ".yaml";
}
private buildApiSpec({
absoluteFilePath,
specType,
origin
}: {
absoluteFilePath: AbsoluteFilePath;
specType: ApiSpecType;
origin?: string;
}): ApiSpec {
switch (specType) {
case "openapi":
return { openapi: absoluteFilePath, origin };
case "asyncapi":
return { asyncapi: absoluteFilePath, origin };
case "graphql":
return { graphql: absoluteFilePath, origin };
default:
throw new CliError({
message: `Unsupported spec type for flags mode: "${specType}". Supported: openapi, asyncapi, graphql`,
code: CliError.Code.ConfigError
});
}
}
private isUrl(reference: string): boolean {
return reference.startsWith("https://") || reference.startsWith("http://");
}
}