History

Refactor plugin SDK and HTTP client boundaries

Rhys Sullivan committed 7 months ago

Commit 6f6f1b11 parent f25b091114 files · +2703 −9255Browse files

Showing the changes to plugins/openapi/shared (3 of 114 files). Show all

Unified · Split

3 files
  1. plugins/openapi/shared/index.ts +177 −0
  2. plugins/openapi/shared/package.json +24 −0
  3. plugins/openapi/shared/tsconfig.json +15 −0
plugins/openapi/shared/index.ts+177−0
@@ -0,0 +1,177 @@
1+import * as Effect from "effect/Effect";
2+import * as Schema from "effect/Schema";
3+import YAML from "yaml";
4+
5+import {
6+ StringMapSchema,
7+} from "@executor/source-core";
8+
9+export const OpenApiConnectionAuthSchema = Schema.Union(
10+ Schema.Struct({
11+ kind: Schema.Literal("none"),
12+ }),
13+ Schema.Struct({
14+ kind: Schema.Literal("bearer"),
15+ tokenSecretRef: Schema.String,
16+ }),
17+);
18+
19+export const OpenApiConnectInputSchema = Schema.Struct({
20+ name: Schema.String,
21+ specUrl: Schema.String,
22+ baseUrl: Schema.NullOr(Schema.String),
23+ auth: OpenApiConnectionAuthSchema,
24+});
25+
26+export const OpenApiSourceConfigSchema = Schema.Struct({
27+ specUrl: Schema.String,
28+ baseUrl: Schema.NullOr(Schema.String),
29+ authStrategy: Schema.Literal("none", "bearer"),
30+ documentHash: Schema.String,
31+});
32+
33+export const OpenApiStoredSourceDataSchema = Schema.Struct({
34+ specUrl: Schema.String,
35+ baseUrl: Schema.NullOr(Schema.String),
36+ auth: OpenApiConnectionAuthSchema,
37+ defaultHeaders: Schema.NullOr(StringMapSchema),
38+ etag: Schema.NullOr(Schema.String),
39+ lastSyncAt: Schema.NullOr(Schema.Number),
40+});
41+
42+export const OpenApiPreviewRequestSchema = Schema.Struct({
43+ specUrl: Schema.String,
44+});
45+
46+export const OpenApiPreviewResponseSchema = Schema.Struct({
47+ title: Schema.NullOr(Schema.String),
48+ version: Schema.NullOr(Schema.String),
49+ baseUrl: Schema.NullOr(Schema.String),
50+ operationCount: Schema.Number,
51+ warnings: Schema.Array(Schema.String),
52+});
53+
54+export type OpenApiConnectionAuth = typeof OpenApiConnectionAuthSchema.Type;
55+export type OpenApiConnectInput = typeof OpenApiConnectInputSchema.Type;
56+export type OpenApiSourceConfig = typeof OpenApiSourceConfigSchema.Type;
57+export type OpenApiStoredSourceData = typeof OpenApiStoredSourceDataSchema.Type;
58+export type OpenApiPreviewRequest = typeof OpenApiPreviewRequestSchema.Type;
59+export type OpenApiPreviewResponse = typeof OpenApiPreviewResponseSchema.Type;
60+
61+type JsonRecord = Record<string, unknown>;
62+
63+const asRecord = (value: unknown): JsonRecord | null =>
64+ value !== null && typeof value === "object" && !Array.isArray(value)
65+ ? value as JsonRecord
66+ : null;
67+
68+const asString = (value: unknown): string | null =>
69+ typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
70+
71+const parseDocument = (text: string): unknown => {
72+ const trimmed = text.trim();
73+ if (!trimmed) {
74+ throw new Error("The OpenAPI document is empty.");
75+ }
76+
77+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
78+ return JSON.parse(trimmed);
79+ }
80+
81+ return YAML.parse(trimmed);
82+};
83+
84+const deriveBaseUrl = (document: JsonRecord, specUrl: string): string | null => {
85+ const servers = Array.isArray(document.servers) ? document.servers : [];
86+ const firstServer = asRecord(servers[0]);
87+ const rawUrl = asString(firstServer?.url);
88+ if (rawUrl === null) {
89+ return null;
90+ }
91+
92+ try {
93+ return new URL(rawUrl, specUrl).toString();
94+ } catch {
95+ return rawUrl;
96+ }
97+};
98+
99+const countOperations = (document: JsonRecord): number => {
100+ const paths = asRecord(document.paths);
101+ if (paths === null) {
102+ return 0;
103+ }
104+
105+ const methodNames = new Set([
106+ "get",
107+ "post",
108+ "put",
109+ "patch",
110+ "delete",
111+ "head",
112+ "options",
113+ "trace",
114+ ]);
115+
116+ let count = 0;
117+ for (const pathItem of Object.values(paths)) {
118+ const pathRecord = asRecord(pathItem);
119+ if (pathRecord === null) {
120+ continue;
121+ }
122+
123+ for (const key of Object.keys(pathRecord)) {
124+ if (methodNames.has(key.toLowerCase())) {
125+ count += 1;
126+ }
127+ }
128+ }
129+
130+ return count;
131+};
132+
133+export const previewOpenApiDocument = async (
134+ input: OpenApiPreviewRequest,
135+): Promise<OpenApiPreviewResponse> => {
136+ const response = await fetch(input.specUrl);
137+ if (!response.ok) {
138+ throw new Error(`Failed fetching spec: ${response.status} ${response.statusText}`);
139+ }
140+
141+ const text = await response.text();
142+ const parsed = parseDocument(text);
143+ const document = asRecord(parsed);
144+ if (document === null) {
145+ throw new Error("The fetched document is not a valid OpenAPI object.");
146+ }
147+
148+ const info = asRecord(document.info);
149+ const warnings: string[] = [];
150+
151+ const openapiVersion = asString(document.openapi) ?? asString(document.swagger);
152+ if (openapiVersion === null) {
153+ warnings.push("The document does not declare an OpenAPI/Swagger version.");
154+ }
155+
156+ const baseUrl = deriveBaseUrl(document, input.specUrl);
157+ if (baseUrl === null) {
158+ warnings.push("No server URL was found in the document.");
159+ }
160+
161+ return {
162+ title: asString(info?.title),
163+ version: asString(info?.version),
164+ baseUrl,
165+ operationCount: countOperations(document),
166+ warnings,
167+ };
168+};
169+
170+export const decodeOpenApiStoredSourceData = (
171+ value: unknown,
172+): Effect.Effect<OpenApiStoredSourceData, Error, never> =>
173+ Effect.try({
174+ try: () => Schema.decodeUnknownSync(OpenApiStoredSourceDataSchema)(value),
175+ catch: (cause) =>
176+ cause instanceof Error ? cause : new Error(String(cause)),
177+ });
plugins/openapi/shared/package.json+24−0
@@ -0,0 +1,24 @@
1+{
2+ "name": "@executor/plugin-openapi-shared",
3+ "private": true,
4+ "type": "module",
5+ "exports": {
6+ ".": "./index.ts"
7+ },
8+ "files": [
9+ "index.ts"
10+ ],
11+ "scripts": {
12+ "typecheck": "bunx tsc --noEmit -p tsconfig.json"
13+ },
14+ "dependencies": {
15+ "@executor/source-core": "workspace:*",
16+ "effect": "catalog:",
17+ "yaml": "^2.8.1"
18+ },
19+ "devDependencies": {
20+ "@types/node": "catalog:",
21+ "bun-types": "catalog:"
22+ },
23+ "version": "0.0.0"
24+}
plugins/openapi/shared/tsconfig.json+15−0
@@ -0,0 +1,15 @@
1+{
2+ "compilerOptions": {
3+ "target": "ES2022",
4+ "module": "ESNext",
5+ "moduleResolution": "Bundler",
6+ "strict": true,
7+ "skipLibCheck": true,
8+ "noEmit": true,
9+ "lib": ["ES2022", "DOM"],
10+ "types": ["bun-types", "node"]
11+ },
12+ "include": [
13+ "index.ts"
14+ ]
15+}

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t