@omnigraph/openapi 1.0.0-alpha-3fc47d119.0 → 1.0.0-alpha-20230420181317-a95037648

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4 @@
1
+ export { loadGraphQLSchemaFromOpenAPI as default } from './loadGraphQLSchemaFromOpenAPI.cjs';
2
+ export * from './loadGraphQLSchemaFromOpenAPI.cjs';
3
+ export { getJSONSchemaOptionsFromOpenAPIOptions } from './getJSONSchemaOptionsFromOpenAPIOptions.cjs';
4
+ export { OpenAPILoaderOptions } from './types.cjs';
@@ -0,0 +1,4 @@
1
+ export { loadGraphQLSchemaFromOpenAPI as default } from './loadGraphQLSchemaFromOpenAPI.js';
2
+ export * from './loadGraphQLSchemaFromOpenAPI.js';
3
+ export { getJSONSchemaOptionsFromOpenAPIOptions } from './getJSONSchemaOptionsFromOpenAPIOptions.js';
4
+ export { OpenAPILoaderOptions } from './types.js';
@@ -0,0 +1,10 @@
1
+ import { OpenAPILoaderOptions } from './types.cjs';
2
+ /**
3
+ * Creates a local GraphQLSchema instance from a OpenAPI Document.
4
+ * Everytime this function is called, the OpenAPI file and its dependencies will be resolved on runtime.
5
+ * If you want to avoid this, use `createBundle` function to create a bundle once and save it to a storage
6
+ * then load it with `loadGraphQLSchemaFromBundle`.
7
+ */
8
+ export declare function loadGraphQLSchemaFromOpenAPI(name: string, options: OpenAPILoaderOptions): Promise<import("graphql").GraphQLSchema>;
9
+ export declare function loadNonExecutableGraphQLSchemaFromOpenAPI(name: string, options: OpenAPILoaderOptions): Promise<import("graphql").GraphQLSchema>;
10
+ export { processDirectives } from '@omnigraph/json-schema';
@@ -1,4 +1,4 @@
1
- import { OpenAPILoaderOptions } from '.';
1
+ import { OpenAPILoaderOptions } from './types.js';
2
2
  /**
3
3
  * Creates a local GraphQLSchema instance from a OpenAPI Document.
4
4
  * Everytime this function is called, the OpenAPI file and its dependencies will be resolved on runtime.
@@ -6,3 +6,5 @@ import { OpenAPILoaderOptions } from '.';
6
6
  * then load it with `loadGraphQLSchemaFromBundle`.
7
7
  */
8
8
  export declare function loadGraphQLSchemaFromOpenAPI(name: string, options: OpenAPILoaderOptions): Promise<import("graphql").GraphQLSchema>;
9
+ export declare function loadNonExecutableGraphQLSchemaFromOpenAPI(name: string, options: OpenAPILoaderOptions): Promise<import("graphql").GraphQLSchema>;
10
+ export { processDirectives } from '@omnigraph/json-schema';
@@ -0,0 +1,10 @@
1
+ import { JSONSchemaLoaderOptions } from '@omnigraph/json-schema';
2
+ export interface OpenAPILoaderOptions extends Partial<JSONSchemaLoaderOptions> {
3
+ source: string;
4
+ selectQueryOrMutationField?: OpenAPILoaderSelectQueryOrMutationFieldConfig[];
5
+ fallbackFormat?: 'json' | 'yaml' | 'js' | 'ts';
6
+ }
7
+ export interface OpenAPILoaderSelectQueryOrMutationFieldConfig {
8
+ type: 'query' | 'mutation' | 'Query' | 'Mutation';
9
+ fieldName: string;
10
+ }
@@ -1,10 +1,10 @@
1
1
  import { JSONSchemaLoaderOptions } from '@omnigraph/json-schema';
2
2
  export interface OpenAPILoaderOptions extends Partial<JSONSchemaLoaderOptions> {
3
- oasFilePath: string;
3
+ source: string;
4
4
  selectQueryOrMutationField?: OpenAPILoaderSelectQueryOrMutationFieldConfig[];
5
5
  fallbackFormat?: 'json' | 'yaml' | 'js' | 'ts';
6
6
  }
7
7
  export interface OpenAPILoaderSelectQueryOrMutationFieldConfig {
8
- type: 'query' | 'mutation';
8
+ type: 'query' | 'mutation' | 'Query' | 'Mutation';
9
9
  fieldName: string;
10
10
  }
@@ -0,0 +1 @@
1
+ export declare function getFieldNameFromPath(path: string, method: string, responseTypeSchemaRef: string): string;
package/bundle.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import { getGraphQLSchemaFromBundle, JSONSchemaLoaderBundle as OpenAPILoaderBundle } from '@omnigraph/json-schema';
2
- import { OpenAPILoaderOptions } from './types';
3
- /**
4
- * Creates a bundle by downloading and resolving the internal references once
5
- * to load the schema locally later
6
- */
7
- export declare function createBundle(name: string, openApiLoaderOptions: OpenAPILoaderOptions): Promise<OpenAPILoaderBundle>;
8
- export { getGraphQLSchemaFromBundle, OpenAPILoaderBundle };
@@ -1,24 +0,0 @@
1
- import { OpenAPIV3, OpenAPIV2 } from 'openapi-types';
2
- import { JSONSchemaOperationConfig } from '@omnigraph/json-schema';
3
- import { OpenAPILoaderSelectQueryOrMutationFieldConfig } from './types';
4
- import { Logger } from '@graphql-mesh/types';
5
- interface GetJSONSchemaOptionsFromOpenAPIOptionsParams {
6
- oasFilePath: OpenAPIV3.Document | OpenAPIV2.Document | string;
7
- fallbackFormat?: 'json' | 'yaml' | 'js' | 'ts';
8
- cwd?: string;
9
- fetch?: WindowOrWorkerGlobalScope['fetch'];
10
- baseUrl?: string;
11
- schemaHeaders?: Record<string, string>;
12
- operationHeaders?: Record<string, string>;
13
- selectQueryOrMutationField?: OpenAPILoaderSelectQueryOrMutationFieldConfig[];
14
- logger?: Logger;
15
- }
16
- export declare function getJSONSchemaOptionsFromOpenAPIOptions({ oasFilePath, fallbackFormat, cwd, fetch: fetchFn, baseUrl, schemaHeaders, operationHeaders, selectQueryOrMutationField, logger, }: GetJSONSchemaOptionsFromOpenAPIOptionsParams): Promise<{
17
- operations: JSONSchemaOperationConfig[];
18
- baseUrl: string;
19
- cwd: string;
20
- fetch: (input: URL | RequestInfo, init?: RequestInit) => Promise<Response>;
21
- schemaHeaders: Record<string, string>;
22
- operationHeaders: Record<string, string>;
23
- }>;
24
- export {};
package/index.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export { loadGraphQLSchemaFromOpenAPI as default } from './loadGraphQLSchemaFromOpenAPI';
2
- export { getJSONSchemaOptionsFromOpenAPIOptions } from './getJSONSchemaOptionsFromOpenAPIOptions';
3
- export { OpenAPILoaderOptions } from './types';
4
- export * from './bundle';
package/index.js DELETED
@@ -1,355 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const jsonSchema = require('@omnigraph/json-schema');
6
- const utils = require('@graphql-mesh/utils');
7
- const jsonMachete = require('json-machete');
8
- const changeCase = require('change-case');
9
- const stringInterpolation = require('@graphql-mesh/string-interpolation');
10
- const crossHelpers = require('@graphql-mesh/cross-helpers');
11
-
12
- function getFieldNameFromPath(path, method, responseTypeSchemaRef) {
13
- // Replace identifiers with "by"
14
- path = path.split('{').join('by_').split('}').join('');
15
- const [actualPartsStr, allQueryPartsStr] = path.split('?');
16
- const actualParts = actualPartsStr.split('/').filter(Boolean);
17
- let fieldNameWithoutMethod = actualParts.join('_');
18
- // If path doesn't give any field name without identifiers, we can use the return type with HTTP Method name
19
- if ((!fieldNameWithoutMethod || fieldNameWithoutMethod.startsWith('by')) && responseTypeSchemaRef) {
20
- const refArr = responseTypeSchemaRef.split('/');
21
- // lowercase looks better in the schema
22
- const prefix = changeCase.camelCase(refArr[refArr.length - 1]);
23
- if (fieldNameWithoutMethod) {
24
- fieldNameWithoutMethod = prefix + '_' + fieldNameWithoutMethod;
25
- }
26
- else {
27
- fieldNameWithoutMethod = prefix;
28
- }
29
- }
30
- if (allQueryPartsStr) {
31
- const queryParts = allQueryPartsStr.split('&');
32
- for (const queryPart of queryParts) {
33
- const [queryName] = queryPart.split('=');
34
- fieldNameWithoutMethod += '_' + 'by' + '_' + queryName;
35
- }
36
- }
37
- // get_ doesn't look good in field names
38
- const methodPrefix = method.toLowerCase();
39
- if (methodPrefix === 'get') {
40
- return fieldNameWithoutMethod;
41
- }
42
- if (fieldNameWithoutMethod) {
43
- return methodPrefix + '_' + fieldNameWithoutMethod;
44
- }
45
- return methodPrefix;
46
- }
47
-
48
- async function getJSONSchemaOptionsFromOpenAPIOptions({ oasFilePath, fallbackFormat, cwd, fetch: fetchFn, baseUrl, schemaHeaders, operationHeaders, selectQueryOrMutationField = [], logger = new utils.DefaultLogger('getJSONSchemaOptionsFromOpenAPIOptions'), }) {
49
- var _a, _b, _c, _d, _e;
50
- const fieldTypeMap = {};
51
- for (const { fieldName, type } of selectQueryOrMutationField) {
52
- fieldTypeMap[fieldName] = type;
53
- }
54
- const schemaHeadersFactory = stringInterpolation.getInterpolatedHeadersFactory(schemaHeaders);
55
- logger === null || logger === void 0 ? void 0 : logger.debug(`Fetching OpenAPI Document from ${oasFilePath}`);
56
- const oasOrSwagger = typeof oasFilePath === 'string'
57
- ? await utils.readFileOrUrl(oasFilePath, {
58
- cwd,
59
- fallbackFormat,
60
- headers: schemaHeadersFactory({ env: crossHelpers.process.env }),
61
- fetch: fetchFn,
62
- importFn: utils.defaultImportFn,
63
- logger,
64
- })
65
- : oasFilePath;
66
- const operations = [];
67
- if ('servers' in oasOrSwagger) {
68
- baseUrl = baseUrl || oasOrSwagger.servers[0].url;
69
- }
70
- for (const relativePath in oasOrSwagger.paths) {
71
- const pathObj = oasOrSwagger.paths[relativePath];
72
- for (const method in pathObj) {
73
- const methodObj = pathObj[method];
74
- const operationConfig = {
75
- method: method.toUpperCase(),
76
- path: relativePath,
77
- type: method.toUpperCase() === 'GET' ? 'query' : 'mutation',
78
- field: methodObj.operationId && utils.sanitizeNameForGraphQL(methodObj.operationId),
79
- description: methodObj.description || methodObj.summary,
80
- schemaHeaders,
81
- operationHeaders,
82
- responseByStatusCode: {},
83
- };
84
- operations.push(operationConfig);
85
- for (const paramObjIndex in methodObj.parameters) {
86
- const paramObj = methodObj.parameters[paramObjIndex];
87
- const argName = utils.sanitizeNameForGraphQL(paramObj.name);
88
- switch (paramObj.in) {
89
- case 'query':
90
- if (method.toUpperCase() === 'GET') {
91
- const requestSchema = (operationConfig.requestSchema = operationConfig.requestSchema || {
92
- type: 'object',
93
- properties: {},
94
- });
95
- requestSchema.properties[paramObj.name] =
96
- paramObj.schema || ((_b = (_a = paramObj.content) === null || _a === void 0 ? void 0 : _a['application/json']) === null || _b === void 0 ? void 0 : _b.schema) || paramObj;
97
- if (!requestSchema.properties[paramObj.name].title) {
98
- requestSchema.properties[paramObj.name].name = paramObj.name;
99
- }
100
- if (!requestSchema.properties[paramObj.name].description) {
101
- requestSchema.properties[paramObj.name].description = paramObj.description;
102
- }
103
- if (requestSchema.properties.__typename) {
104
- delete requestSchema.properties.__typename;
105
- }
106
- if (paramObj.required) {
107
- requestSchema.required = requestSchema.required || [];
108
- requestSchema.required.push(paramObj.name);
109
- }
110
- }
111
- else {
112
- if (!operationConfig.path.includes('?')) {
113
- operationConfig.path += '?';
114
- }
115
- operationConfig.path += `${paramObj.name}={args.${argName}}`;
116
- }
117
- break;
118
- case 'path': {
119
- // If it is in the path, let JSON Schema handler put it
120
- operationConfig.path = operationConfig.path.replace(`{${paramObj.name}}`, `{args.${argName}}`);
121
- break;
122
- }
123
- case 'header': {
124
- operationConfig.headers = operationConfig.headers || {};
125
- operationConfig.headers[paramObj.name] = `{args.${argName}}`;
126
- break;
127
- }
128
- case 'cookie': {
129
- operationConfig.headers = operationConfig.headers || {};
130
- operationConfig.headers.cookie = operationConfig.headers.cookie || '';
131
- const cookieParams = operationConfig.headers.cookie.split('; ');
132
- cookieParams.push(`${paramObj.name}={args.${argName}}`);
133
- operationConfig.headers.cookie = cookieParams.join('; ');
134
- break;
135
- }
136
- case 'body':
137
- if (paramObj.schema && Object.keys(paramObj.schema).length > 0) {
138
- operationConfig.requestSchema = `${oasFilePath}#/paths/${relativePath
139
- .split('/')
140
- .join('~1')}/${method}/parameters/${paramObjIndex}/schema`;
141
- }
142
- if (paramObj.example) {
143
- operationConfig.requestSample = paramObj.example;
144
- }
145
- if (paramObj.examples) {
146
- operationConfig.requestSample = Object.values(paramObj.examples)[0];
147
- }
148
- break;
149
- }
150
- switch (((_c = paramObj.schema) === null || _c === void 0 ? void 0 : _c.type) || paramObj.type) {
151
- case 'string':
152
- operationConfig.argTypeMap = operationConfig.argTypeMap || {};
153
- operationConfig.argTypeMap[argName] = 'String';
154
- break;
155
- case 'integer':
156
- operationConfig.argTypeMap = operationConfig.argTypeMap || {};
157
- operationConfig.argTypeMap[argName] = 'Int';
158
- break;
159
- case 'number':
160
- operationConfig.argTypeMap = operationConfig.argTypeMap || {};
161
- operationConfig.argTypeMap[argName] = 'Float';
162
- break;
163
- case 'boolean':
164
- operationConfig.argTypeMap = operationConfig.argTypeMap || {};
165
- operationConfig.argTypeMap[argName] = 'Boolean';
166
- break;
167
- }
168
- if (paramObj.required) {
169
- operationConfig.argTypeMap = operationConfig.argTypeMap || {};
170
- operationConfig.argTypeMap[argName] = operationConfig.argTypeMap[argName] || 'ID';
171
- operationConfig.argTypeMap[argName] += '!';
172
- }
173
- }
174
- if ('requestBody' in methodObj) {
175
- const requestBodyObj = methodObj.requestBody;
176
- if ('content' in requestBodyObj) {
177
- const contentKey = Object.keys(requestBodyObj.content)[0];
178
- const contentSchema = (_d = requestBodyObj.content[contentKey]) === null || _d === void 0 ? void 0 : _d.schema;
179
- if (contentSchema && Object.keys(contentSchema).length > 0) {
180
- operationConfig.requestSchema = `${oasFilePath}#/paths/${relativePath
181
- .split('/')
182
- .join('~1')}/${method}/requestBody/content/${contentKey === null || contentKey === void 0 ? void 0 : contentKey.toString().split('/').join('~1')}/schema`;
183
- }
184
- const examplesObj = (_e = requestBodyObj.content[contentKey]) === null || _e === void 0 ? void 0 : _e.examples;
185
- if (examplesObj) {
186
- operationConfig.requestSample = Object.values(examplesObj)[0];
187
- }
188
- }
189
- }
190
- const responseByStatusCode = operationConfig.responseByStatusCode;
191
- // Handling multiple response types
192
- for (const responseKey in methodObj.responses) {
193
- const responseObj = methodObj.responses[responseKey];
194
- let schemaObj;
195
- if ('content' in responseObj) {
196
- const contentKey = Object.keys(responseObj.content)[0];
197
- schemaObj = responseObj.content[contentKey].schema;
198
- if (schemaObj && Object.keys(schemaObj).length > 0) {
199
- responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
200
- responseByStatusCode[responseKey].responseSchema = `${oasFilePath}#/paths/${relativePath
201
- .split('/')
202
- .join('~1')}/${method}/responses/${responseKey}/content/${contentKey === null || contentKey === void 0 ? void 0 : contentKey.toString().split('/').join('~1')}/schema`;
203
- }
204
- const examplesObj = responseObj.content[contentKey].examples;
205
- if (examplesObj) {
206
- responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
207
- responseByStatusCode[responseKey].responseSample = Object.values(examplesObj)[0];
208
- }
209
- const example = responseObj.content[contentKey].example;
210
- if (example) {
211
- responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
212
- responseByStatusCode[responseKey].responseSample = example;
213
- }
214
- }
215
- else if ('schema' in responseObj) {
216
- schemaObj = responseObj.schema;
217
- if (schemaObj && Object.keys(schemaObj).length > 0) {
218
- responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
219
- responseByStatusCode[responseKey].responseSchema = `${oasFilePath}#/paths/${relativePath
220
- .split('/')
221
- .join('~1')}/${method}/responses/${responseKey}/schema`;
222
- }
223
- }
224
- else if ('examples' in responseObj) {
225
- const examples = Object.values(responseObj.examples);
226
- responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
227
- responseByStatusCode[responseKey].responseSample = examples[0];
228
- }
229
- else if (responseKey.toString() === '204') {
230
- responseByStatusCode[responseKey] = responseByStatusCode[responseKey] || {};
231
- responseByStatusCode[responseKey].responseSchema = {
232
- type: 'null',
233
- description: responseObj.description,
234
- };
235
- }
236
- if ('links' in responseObj) {
237
- const dereferencedLinkObj = await jsonMachete.dereferenceObject({
238
- links: responseObj.links,
239
- }, {
240
- cwd,
241
- root: oasOrSwagger,
242
- fetchFn,
243
- logger,
244
- headers: schemaHeaders,
245
- });
246
- responseByStatusCode[responseKey].links = responseByStatusCode[responseKey].links || {};
247
- for (const linkName in dereferencedLinkObj.links) {
248
- const linkObj = responseObj.links[linkName];
249
- if ('$ref' in linkObj) {
250
- throw new Error('Unexpected $ref in dereferenced link object');
251
- }
252
- const args = {};
253
- for (const parameterName in linkObj.parameters || {}) {
254
- const parameterExp = linkObj.parameters[parameterName].split('-').join('_');
255
- args[utils.sanitizeNameForGraphQL(parameterName)] = parameterExp.startsWith('$')
256
- ? `{root.${parameterExp}}`
257
- : parameterExp.split('$').join('root.$');
258
- }
259
- if ('operationRef' in linkObj) {
260
- const [externalPath, ref] = linkObj.operationRef.split('#');
261
- if (externalPath) {
262
- if (crossHelpers.process.env.DEBUG) {
263
- console.warn(`Skipping external operation reference ${linkObj.operationRef}\n Use additionalTypeDefs and additionalResolvers instead.`);
264
- }
265
- }
266
- else {
267
- const actualOperation = jsonMachete.resolvePath(ref, oasOrSwagger);
268
- if (actualOperation.operationId) {
269
- const fieldName = utils.sanitizeNameForGraphQL(actualOperation.operationId);
270
- responseByStatusCode[responseKey].links[linkName] = {
271
- fieldName,
272
- args,
273
- description: linkObj.description,
274
- };
275
- }
276
- else {
277
- console.warn('Missing operationId skipping...');
278
- }
279
- }
280
- }
281
- else if ('operationId' in linkObj) {
282
- responseByStatusCode[responseKey].links[linkName] = {
283
- fieldName: utils.sanitizeNameForGraphQL(linkObj.operationId),
284
- args,
285
- description: linkObj.description,
286
- };
287
- }
288
- }
289
- }
290
- if (!operationConfig.field) {
291
- methodObj.operationId = getFieldNameFromPath(relativePath, method, schemaObj === null || schemaObj === void 0 ? void 0 : schemaObj.$ref);
292
- // Operation ID might not be avaiable so let's generate field name from path and response type schema
293
- operationConfig.field = utils.sanitizeNameForGraphQL(methodObj.operationId);
294
- }
295
- // Give a better name to the request input object
296
- if (typeof operationConfig.requestSchema === 'object' && !operationConfig.requestSchema.title) {
297
- operationConfig.requestSchema.title = operationConfig.field + '_request';
298
- }
299
- }
300
- if (fieldTypeMap[operationConfig.field]) {
301
- operationConfig.type = fieldTypeMap[operationConfig.field];
302
- }
303
- }
304
- }
305
- return {
306
- operations,
307
- baseUrl,
308
- cwd,
309
- fetch: fetchFn,
310
- schemaHeaders,
311
- operationHeaders,
312
- };
313
- }
314
-
315
- /**
316
- * Creates a local GraphQLSchema instance from a OpenAPI Document.
317
- * Everytime this function is called, the OpenAPI file and its dependencies will be resolved on runtime.
318
- * If you want to avoid this, use `createBundle` function to create a bundle once and save it to a storage
319
- * then load it with `loadGraphQLSchemaFromBundle`.
320
- */
321
- async function loadGraphQLSchemaFromOpenAPI(name, options) {
322
- const extraJSONSchemaOptions = await getJSONSchemaOptionsFromOpenAPIOptions(options);
323
- return jsonSchema.loadGraphQLSchemaFromJSONSchemas(name, {
324
- ...options,
325
- ...extraJSONSchemaOptions,
326
- });
327
- }
328
-
329
- /**
330
- * Creates a bundle by downloading and resolving the internal references once
331
- * to load the schema locally later
332
- */
333
- async function createBundle(name, openApiLoaderOptions) {
334
- const { operations, baseUrl, cwd, fetch, schemaHeaders, operationHeaders } = await getJSONSchemaOptionsFromOpenAPIOptions(openApiLoaderOptions);
335
- return jsonSchema.createBundle(name, {
336
- operations,
337
- baseUrl,
338
- cwd,
339
- fetch,
340
- schemaHeaders,
341
- operationHeaders,
342
- ignoreErrorResponses: openApiLoaderOptions.ignoreErrorResponses,
343
- logger: openApiLoaderOptions.logger,
344
- });
345
- }
346
-
347
- Object.defineProperty(exports, 'getGraphQLSchemaFromBundle', {
348
- enumerable: true,
349
- get: function () {
350
- return jsonSchema.getGraphQLSchemaFromBundle;
351
- }
352
- });
353
- exports.createBundle = createBundle;
354
- exports.default = loadGraphQLSchemaFromOpenAPI;
355
- exports.getJSONSchemaOptionsFromOpenAPIOptions = getJSONSchemaOptionsFromOpenAPIOptions;