@omnigraph/raml 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.
package/README.md CHANGED
@@ -1,8 +1,10 @@
1
1
  ## RAML (@omnigraph/raml)
2
2
 
3
- This package generates `GraphQLSchema` instance from **RAML API Document** (`.raml`) file located at a URL or FileSystem by resolving the JSON Schema dependencies. It uses `@omnigraph/json-schema` by generating the necessary configuration.
3
+ This package generates `GraphQLSchema` instance from **RAML API Document** (`.raml`) file located at
4
+ a URL or FileSystem by resolving the JSON Schema dependencies. It uses `@omnigraph/json-schema` by
5
+ generating the necessary configuration.
4
6
 
5
- ```yaml
7
+ ```yaml filename=".graphqlrc.yml"
6
8
  schema:
7
9
  myOmnigraph:
8
10
  loader: '@omnigraph/raml'
@@ -0,0 +1,229 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getJSONSchemaOptionsFromRAMLOptions = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const json_machete_1 = require("json-machete");
6
+ const to_json_schema_1 = tslib_1.__importDefault(require("to-json-schema"));
7
+ const raml_1_parser_1 = require("@ardatan/raml-1-parser");
8
+ const cross_helpers_1 = require("@graphql-mesh/cross-helpers");
9
+ const string_interpolation_1 = require("@graphql-mesh/string-interpolation");
10
+ const utils_1 = require("@graphql-mesh/utils");
11
+ const utils_2 = require("@graphql-tools/utils");
12
+ const fetch_1 = require("@whatwg-node/fetch");
13
+ const utils_js_1 = require("./utils.js");
14
+ function resolveTraitsByIs(base) {
15
+ const allTraits = [];
16
+ for (const traitRef of base.is()) {
17
+ const traitNode = traitRef.trait();
18
+ if (traitNode) {
19
+ allTraits.push(traitNode);
20
+ allTraits.push(...resolveTraitsByIs(traitNode));
21
+ }
22
+ }
23
+ return allTraits;
24
+ }
25
+ /**
26
+ * Generates the options for JSON Schema Loader
27
+ * from RAML Loader options by extracting the JSON Schema references
28
+ * from RAML API Document
29
+ */
30
+ async function getJSONSchemaOptionsFromRAMLOptions({ source, cwd: ramlFileCwd = cross_helpers_1.process.cwd(), operations: extraOperations, endpoint: forcedBaseUrl, fetch = fetch_1.fetch, schemaHeaders = {}, selectQueryOrMutationField = [], }) {
31
+ var _a, _b, _c, _d, _e, _f;
32
+ const fieldTypeMap = {};
33
+ for (const { fieldName, type } of selectQueryOrMutationField) {
34
+ fieldTypeMap[fieldName] = type;
35
+ }
36
+ const operations = extraOperations || [];
37
+ const ramlAbsolutePath = (0, json_machete_1.getAbsolutePath)(source, ramlFileCwd);
38
+ const schemaHeadersFactory = (0, string_interpolation_1.getInterpolatedHeadersFactory)(schemaHeaders);
39
+ const ramlAPI = (await (0, raml_1_parser_1.loadApi)(ramlAbsolutePath, [], {
40
+ httpResolver: {
41
+ getResourceAsync: async (url) => {
42
+ const fetchResponse = await fetch(url, {
43
+ headers: schemaHeadersFactory({ env: cross_helpers_1.process.env }),
44
+ });
45
+ const content = await fetchResponse.text();
46
+ if (fetchResponse.status !== 200) {
47
+ return {
48
+ errorMessage: content,
49
+ };
50
+ }
51
+ return {
52
+ content,
53
+ };
54
+ },
55
+ getResource: () => {
56
+ throw new Error(`Sync fetching not available for URLs`);
57
+ },
58
+ },
59
+ }));
60
+ let endpoint = forcedBaseUrl;
61
+ if (!endpoint) {
62
+ endpoint = ramlAPI.baseUri().value();
63
+ for (const endpointParamNode of ramlAPI.baseUriParameters()) {
64
+ const paramName = endpointParamNode.name();
65
+ endpoint = endpoint.split(`{${paramName}}`).join(`{context.${paramName}}`);
66
+ }
67
+ }
68
+ const pathTypeMap = new Map();
69
+ const typePathMap = new Map();
70
+ for (const typeNode of ramlAPI.types()) {
71
+ const typeNodeJson = typeNode.toJSON();
72
+ for (const typeName in typeNodeJson) {
73
+ const { schemaPath } = typeNodeJson[typeName];
74
+ if (schemaPath) {
75
+ pathTypeMap.set(schemaPath, typeName);
76
+ typePathMap.set(typeName, schemaPath);
77
+ }
78
+ }
79
+ }
80
+ const cwd = (0, json_machete_1.getCwd)(ramlAbsolutePath);
81
+ const apiQueryParameters = [];
82
+ const apiBodyNodes = [];
83
+ const apiResponses = [];
84
+ for (const traitNode of ramlAPI.traits()) {
85
+ apiQueryParameters.push(...traitNode.queryParameters());
86
+ apiBodyNodes.push(...traitNode.body());
87
+ apiResponses.push(...traitNode.responses());
88
+ const nestedTraits = resolveTraitsByIs(traitNode);
89
+ for (const nestedTrait of nestedTraits) {
90
+ apiQueryParameters.push(...nestedTrait.queryParameters());
91
+ apiBodyNodes.push(...nestedTrait.body());
92
+ apiResponses.push(...nestedTrait.responses());
93
+ }
94
+ }
95
+ for (const resourceNode of ramlAPI.allResources()) {
96
+ const resourceQueryParameters = [...apiQueryParameters];
97
+ const resourceBodyNodes = [...apiBodyNodes];
98
+ const resourceResponses = [...apiResponses];
99
+ const resourceTraits = resolveTraitsByIs(resourceNode);
100
+ for (const traitNode of resourceTraits) {
101
+ apiQueryParameters.push(...traitNode.queryParameters());
102
+ apiBodyNodes.push(...traitNode.body());
103
+ apiResponses.push(...traitNode.responses());
104
+ }
105
+ for (const methodNode of resourceNode.methods()) {
106
+ const queryParameters = [...resourceQueryParameters];
107
+ const bodyNodes = [...resourceBodyNodes];
108
+ const responses = [...resourceResponses];
109
+ const traits = resolveTraitsByIs(methodNode);
110
+ for (const traitNode of traits) {
111
+ queryParameters.push(...traitNode.queryParameters());
112
+ bodyNodes.push(...traitNode.body());
113
+ responses.push(...traitNode.responses());
114
+ }
115
+ queryParameters.push(...methodNode.queryParameters());
116
+ bodyNodes.push(...methodNode.body());
117
+ responses.push(...methodNode.responses());
118
+ let requestSchema;
119
+ let requestTypeName;
120
+ const responseByStatusCode = {};
121
+ const method = methodNode.method().toUpperCase();
122
+ let fieldName = (_a = methodNode.displayName()) === null || _a === void 0 ? void 0 : _a.replace('GET_', '');
123
+ const description = ((_b = methodNode.description()) === null || _b === void 0 ? void 0 : _b.value()) || ((_c = resourceNode.description()) === null || _c === void 0 ? void 0 : _c.value());
124
+ const originalFullRelativeUrl = resourceNode.completeRelativeUri();
125
+ let fullRelativeUrl = originalFullRelativeUrl;
126
+ const argTypeMap = {};
127
+ const queryParamArgMap = {};
128
+ for (const uriParameterNode of resourceNode.uriParameters()) {
129
+ const paramName = uriParameterNode.name();
130
+ const argName = (0, utils_1.sanitizeNameForGraphQL)(paramName);
131
+ fullRelativeUrl = fullRelativeUrl.replace(`{${paramName}}`, `{args.${argName}}`);
132
+ const uriParameterNodeJson = uriParameterNode.toJSON();
133
+ if (uriParameterNodeJson.displayName) {
134
+ uriParameterNodeJson.title = uriParameterNodeJson.displayName;
135
+ }
136
+ argTypeMap[argName] = uriParameterNodeJson;
137
+ }
138
+ for (const queryParameterNode of queryParameters) {
139
+ const parameterName = queryParameterNode.name();
140
+ const argName = (0, utils_1.sanitizeNameForGraphQL)(parameterName);
141
+ const queryParameterNodeJson = queryParameterNode.toJSON();
142
+ if (queryParameterNodeJson.displayName) {
143
+ queryParameterNodeJson.title = queryParameterNodeJson.displayName;
144
+ }
145
+ queryParamArgMap[parameterName] = argName;
146
+ argTypeMap[argName] = queryParameterNodeJson;
147
+ }
148
+ for (const bodyNode of bodyNodes) {
149
+ if (bodyNode.name().includes('application/json')) {
150
+ const bodyJson = bodyNode.toJSON();
151
+ if (bodyJson.schemaPath) {
152
+ const schemaPath = bodyJson.schemaPath;
153
+ requestSchema = schemaPath;
154
+ requestTypeName = pathTypeMap.get(schemaPath);
155
+ }
156
+ else if (bodyJson.type) {
157
+ const typeName = (0, utils_2.asArray)(bodyJson.type)[0];
158
+ requestTypeName = typeName;
159
+ const schemaPath = typePathMap.get(typeName);
160
+ requestSchema = schemaPath;
161
+ }
162
+ }
163
+ }
164
+ for (const responseNode of responses) {
165
+ const statusCode = responseNode.code().value();
166
+ const responseNodeDescription = (_d = responseNode.description()) === null || _d === void 0 ? void 0 : _d.value();
167
+ for (const bodyNode of responseNode.body()) {
168
+ if (bodyNode.name().includes('application/json')) {
169
+ const bodyJson = bodyNode.toJSON();
170
+ if (bodyJson.schemaPath) {
171
+ const schemaPath = bodyJson.schemaPath;
172
+ const typeName = pathTypeMap.get(schemaPath);
173
+ if (schemaPath) {
174
+ responseByStatusCode[statusCode] = {
175
+ responseSchema: schemaPath,
176
+ responseTypeName: typeName,
177
+ };
178
+ }
179
+ }
180
+ else if (bodyJson.type) {
181
+ const typeName = (0, utils_2.asArray)(bodyJson.type)[0];
182
+ const schemaPath = typePathMap.get(typeName);
183
+ if (schemaPath) {
184
+ responseByStatusCode[statusCode] = {
185
+ responseSchema: schemaPath,
186
+ responseTypeName: typeName,
187
+ };
188
+ }
189
+ }
190
+ if (!responseByStatusCode[statusCode] && bodyJson.example) {
191
+ const responseSchema = (0, to_json_schema_1.default)(bodyJson.example, {
192
+ required: false,
193
+ });
194
+ responseSchema.description = responseNodeDescription;
195
+ responseByStatusCode[statusCode] = {
196
+ responseSchema,
197
+ };
198
+ }
199
+ }
200
+ }
201
+ }
202
+ fieldName =
203
+ fieldName ||
204
+ (0, utils_js_1.getFieldNameFromPath)(originalFullRelativeUrl, method, (_e = responseByStatusCode['200']) === null || _e === void 0 ? void 0 : _e.responseTypeName);
205
+ if (fieldName) {
206
+ const graphQLFieldName = (0, utils_1.sanitizeNameForGraphQL)(fieldName);
207
+ const operationType = ((_f = fieldTypeMap[graphQLFieldName]) !== null && _f !== void 0 ? _f : method === 'GET') ? 'query' : 'mutation';
208
+ operations.push({
209
+ type: operationType,
210
+ field: graphQLFieldName,
211
+ description,
212
+ path: fullRelativeUrl,
213
+ method,
214
+ requestSchema,
215
+ requestTypeName,
216
+ responseByStatusCode,
217
+ argTypeMap,
218
+ });
219
+ }
220
+ }
221
+ }
222
+ return {
223
+ operations,
224
+ endpoint,
225
+ cwd,
226
+ fetch,
227
+ };
228
+ }
229
+ exports.getJSONSchemaOptionsFromRAMLOptions = getJSONSchemaOptionsFromRAMLOptions;
package/cjs/index.js ADDED
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getJSONSchemaOptionsFromRAMLOptions = exports.default = void 0;
4
+ const tslib_1 = require("tslib");
5
+ var loadGraphQLSchemaFromRAML_js_1 = require("./loadGraphQLSchemaFromRAML.js");
6
+ Object.defineProperty(exports, "default", { enumerable: true, get: function () { return loadGraphQLSchemaFromRAML_js_1.loadGraphQLSchemaFromRAML; } });
7
+ tslib_1.__exportStar(require("./loadGraphQLSchemaFromRAML.js"), exports);
8
+ var getJSONSchemaOptionsFromRAMLOptions_js_1 = require("./getJSONSchemaOptionsFromRAMLOptions.js");
9
+ Object.defineProperty(exports, "getJSONSchemaOptionsFromRAMLOptions", { enumerable: true, get: function () { return getJSONSchemaOptionsFromRAMLOptions_js_1.getJSONSchemaOptionsFromRAMLOptions; } });
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processDirectives = exports.loadNonExecutableGraphQLSchemaFromRAML = exports.loadGraphQLSchemaFromRAML = void 0;
4
+ const json_schema_1 = require("@omnigraph/json-schema");
5
+ const getJSONSchemaOptionsFromRAMLOptions_js_1 = require("./getJSONSchemaOptionsFromRAMLOptions.js");
6
+ /**
7
+ * Creates a local GraphQLSchema instance from a RAML API Document.
8
+ * Everytime this function is called, the RAML file and its dependencies will be resolved on runtime.
9
+ * If you want to avoid this, use `createBundle` function to create a bundle once and save it to a storage
10
+ * then load it with `loadGraphQLSchemaFromBundle`.
11
+ */
12
+ async function loadGraphQLSchemaFromRAML(name, options) {
13
+ const extraJSONSchemaOptions = await (0, getJSONSchemaOptionsFromRAMLOptions_js_1.getJSONSchemaOptionsFromRAMLOptions)(options);
14
+ return (0, json_schema_1.loadGraphQLSchemaFromJSONSchemas)(name, {
15
+ ...options,
16
+ ...extraJSONSchemaOptions,
17
+ });
18
+ }
19
+ exports.loadGraphQLSchemaFromRAML = loadGraphQLSchemaFromRAML;
20
+ async function loadNonExecutableGraphQLSchemaFromRAML(name, options) {
21
+ const extraJSONSchemaOptions = await (0, getJSONSchemaOptionsFromRAMLOptions_js_1.getJSONSchemaOptionsFromRAMLOptions)(options);
22
+ return (0, json_schema_1.loadNonExecutableGraphQLSchemaFromJSONSchemas)(name, {
23
+ ...options,
24
+ ...extraJSONSchemaOptions,
25
+ });
26
+ }
27
+ exports.loadNonExecutableGraphQLSchemaFromRAML = loadNonExecutableGraphQLSchemaFromRAML;
28
+ var json_schema_2 = require("@omnigraph/json-schema");
29
+ Object.defineProperty(exports, "processDirectives", { enumerable: true, get: function () { return json_schema_2.processDirectives; } });
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
package/cjs/types.js ADDED
File without changes
package/cjs/utils.js ADDED
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFieldNameFromPath = void 0;
4
+ const change_case_1 = require("change-case");
5
+ function getFieldNameFromPath(path, method, typeName) {
6
+ // Replace identifiers with "by"
7
+ path = path.split('{').join('by_').split('}').join('');
8
+ const [actualPartsStr, allQueryPartsStr] = path.split('?');
9
+ const actualParts = actualPartsStr.split('/').filter(Boolean);
10
+ let fieldNameWithoutMethod = actualParts.join('_');
11
+ // If path doesn't give any field name without identifiers, we can use the return type with HTTP Method name
12
+ if ((!fieldNameWithoutMethod || fieldNameWithoutMethod.startsWith('by')) && typeName) {
13
+ // lowercase looks better in the schema
14
+ const prefix = (0, change_case_1.camelCase)(typeName);
15
+ if (fieldNameWithoutMethod) {
16
+ fieldNameWithoutMethod = prefix + '_' + fieldNameWithoutMethod;
17
+ }
18
+ else {
19
+ fieldNameWithoutMethod = prefix;
20
+ }
21
+ }
22
+ if (allQueryPartsStr) {
23
+ const queryParts = allQueryPartsStr.split('&');
24
+ for (const queryPart of queryParts) {
25
+ const [queryName] = queryPart.split('=');
26
+ fieldNameWithoutMethod += '_' + 'by' + '_' + queryName;
27
+ }
28
+ }
29
+ // get_ doesn't look good in field names
30
+ const methodPrefix = method.toLowerCase();
31
+ if (methodPrefix === 'get') {
32
+ return fieldNameWithoutMethod;
33
+ }
34
+ return methodPrefix + '_' + fieldNameWithoutMethod;
35
+ }
36
+ exports.getFieldNameFromPath = getFieldNameFromPath;
@@ -1,48 +1,12 @@
1
- import { loadGraphQLSchemaFromJSONSchemas, createBundle as createBundle$1 } from '@omnigraph/json-schema';
2
- export { getGraphQLSchemaFromBundle } from '@omnigraph/json-schema';
3
- import { sanitizeNameForGraphQL } from '@graphql-mesh/utils';
4
1
  import { getAbsolutePath, getCwd } from 'json-machete';
5
- import { loadApi } from '@ardatan/raml-1-parser';
6
- import { fetch } from '@whatwg-node/fetch';
7
2
  import toJsonSchema from 'to-json-schema';
8
- import { asArray } from '@graphql-tools/utils';
9
- import { camelCase } from 'change-case';
10
- import { GraphQLEnumType } from 'graphql';
11
- import { getInterpolatedHeadersFactory } from '@graphql-mesh/string-interpolation';
3
+ import { loadApi } from '@ardatan/raml-1-parser';
12
4
  import { process } from '@graphql-mesh/cross-helpers';
13
-
14
- function getFieldNameFromPath(path, method, typeName) {
15
- // Replace identifiers with "by"
16
- path = path.split('{').join('by_').split('}').join('');
17
- const [actualPartsStr, allQueryPartsStr] = path.split('?');
18
- const actualParts = actualPartsStr.split('/').filter(Boolean);
19
- let fieldNameWithoutMethod = actualParts.join('_');
20
- // If path doesn't give any field name without identifiers, we can use the return type with HTTP Method name
21
- if ((!fieldNameWithoutMethod || fieldNameWithoutMethod.startsWith('by')) && typeName) {
22
- // lowercase looks better in the schema
23
- const prefix = camelCase(typeName);
24
- if (fieldNameWithoutMethod) {
25
- fieldNameWithoutMethod = prefix + '_' + fieldNameWithoutMethod;
26
- }
27
- else {
28
- fieldNameWithoutMethod = prefix;
29
- }
30
- }
31
- if (allQueryPartsStr) {
32
- const queryParts = allQueryPartsStr.split('&');
33
- for (const queryPart of queryParts) {
34
- const [queryName] = queryPart.split('=');
35
- fieldNameWithoutMethod += '_' + 'by' + '_' + queryName;
36
- }
37
- }
38
- // get_ doesn't look good in field names
39
- const methodPrefix = method.toLowerCase();
40
- if (methodPrefix === 'get') {
41
- return fieldNameWithoutMethod;
42
- }
43
- return methodPrefix + '_' + fieldNameWithoutMethod;
44
- }
45
-
5
+ import { getInterpolatedHeadersFactory } from '@graphql-mesh/string-interpolation';
6
+ import { sanitizeNameForGraphQL } from '@graphql-mesh/utils';
7
+ import { asArray } from '@graphql-tools/utils';
8
+ import { fetch as crossUndiciFetch } from '@whatwg-node/fetch';
9
+ import { getFieldNameFromPath } from './utils.js';
46
10
  function resolveTraitsByIs(base) {
47
11
  const allTraits = [];
48
12
  for (const traitRef of base.is()) {
@@ -59,19 +23,19 @@ function resolveTraitsByIs(base) {
59
23
  * from RAML Loader options by extracting the JSON Schema references
60
24
  * from RAML API Document
61
25
  */
62
- async function getJSONSchemaOptionsFromRAMLOptions({ ramlFilePath, cwd: ramlFileCwd = process.cwd(), operations: extraOperations, baseUrl: forcedBaseUrl, fetch: fetch$1 = fetch, schemaHeaders = {}, selectQueryOrMutationField = [], }) {
63
- var _a, _b, _c, _d, _e, _f, _g;
26
+ export async function getJSONSchemaOptionsFromRAMLOptions({ source, cwd: ramlFileCwd = process.cwd(), operations: extraOperations, endpoint: forcedBaseUrl, fetch = crossUndiciFetch, schemaHeaders = {}, selectQueryOrMutationField = [], }) {
27
+ var _a, _b, _c, _d, _e, _f;
64
28
  const fieldTypeMap = {};
65
29
  for (const { fieldName, type } of selectQueryOrMutationField) {
66
30
  fieldTypeMap[fieldName] = type;
67
31
  }
68
32
  const operations = extraOperations || [];
69
- const ramlAbsolutePath = getAbsolutePath(ramlFilePath, ramlFileCwd);
33
+ const ramlAbsolutePath = getAbsolutePath(source, ramlFileCwd);
70
34
  const schemaHeadersFactory = getInterpolatedHeadersFactory(schemaHeaders);
71
35
  const ramlAPI = (await loadApi(ramlAbsolutePath, [], {
72
36
  httpResolver: {
73
37
  getResourceAsync: async (url) => {
74
- const fetchResponse = await fetch$1(url, {
38
+ const fetchResponse = await fetch(url, {
75
39
  headers: schemaHeadersFactory({ env: process.env }),
76
40
  });
77
41
  const content = await fetchResponse.text();
@@ -89,12 +53,12 @@ async function getJSONSchemaOptionsFromRAMLOptions({ ramlFilePath, cwd: ramlFile
89
53
  },
90
54
  },
91
55
  }));
92
- let baseUrl = forcedBaseUrl;
93
- if (!baseUrl) {
94
- baseUrl = ramlAPI.baseUri().value();
95
- for (const baseUrlParamNode of ramlAPI.baseUriParameters()) {
96
- const paramName = baseUrlParamNode.name();
97
- baseUrl = baseUrl.split(`{${paramName}}`).join(`{context.${paramName}}`);
56
+ let endpoint = forcedBaseUrl;
57
+ if (!endpoint) {
58
+ endpoint = ramlAPI.baseUri().value();
59
+ for (const endpointParamNode of ramlAPI.baseUriParameters()) {
60
+ const paramName = endpointParamNode.name();
61
+ endpoint = endpoint.split(`{${paramName}}`).join(`{context.${paramName}}`);
98
62
  }
99
63
  }
100
64
  const pathTypeMap = new Map();
@@ -156,98 +120,26 @@ async function getJSONSchemaOptionsFromRAMLOptions({ ramlFilePath, cwd: ramlFile
156
120
  const originalFullRelativeUrl = resourceNode.completeRelativeUri();
157
121
  let fullRelativeUrl = originalFullRelativeUrl;
158
122
  const argTypeMap = {};
123
+ const queryParamArgMap = {};
159
124
  for (const uriParameterNode of resourceNode.uriParameters()) {
160
125
  const paramName = uriParameterNode.name();
161
- fullRelativeUrl = fullRelativeUrl.replace(`{${paramName}}`, `{args.${paramName}}`);
126
+ const argName = sanitizeNameForGraphQL(paramName);
127
+ fullRelativeUrl = fullRelativeUrl.replace(`{${paramName}}`, `{args.${argName}}`);
162
128
  const uriParameterNodeJson = uriParameterNode.toJSON();
163
- for (const typeName of asArray(uriParameterNodeJson.type)) {
164
- switch (typeName) {
165
- case 'number':
166
- argTypeMap[paramName] = 'Float';
167
- break;
168
- case 'boolean':
169
- argTypeMap[paramName] = 'Boolean';
170
- break;
171
- case 'integer':
172
- argTypeMap[paramName] = 'Int';
173
- break;
174
- default:
175
- argTypeMap[paramName] = 'String';
176
- break;
177
- }
178
- }
179
- /* raml pattern is different
180
- if (uriParameterNodeJson.pattern) {
181
- const typeName = sanitizeNameForGraphQL(uriParameterNodeJson.displayName || `${fieldName}_${paramName}`);
182
- argTypeMap[paramName] = new RegularExpression(typeName, new RegExp(uriParameterNodeJson.pattern), {
183
- description: uriParameterNodeJson.description,
184
- });
185
- }
186
- */
187
- if (uriParameterNodeJson.enum) {
188
- const typeName = sanitizeNameForGraphQL(uriParameterNodeJson.displayName || `${fieldName}_${paramName}`);
189
- const values = {};
190
- for (const value of asArray(uriParameterNodeJson.enum)) {
191
- let enumKey = sanitizeNameForGraphQL(value.toString());
192
- if (enumKey === 'false' || enumKey === 'true' || enumKey === 'null') {
193
- enumKey = enumKey.toUpperCase();
194
- }
195
- if (typeof enumKey === 'string' && enumKey.length === 0) {
196
- enumKey = '_';
197
- }
198
- values[enumKey] = {
199
- // Falsy values are ignored by GraphQL
200
- // eslint-disable-next-line no-unneeded-ternary
201
- value: value ? value : value === null || value === void 0 ? void 0 : value.toString(),
202
- };
203
- }
204
- argTypeMap[paramName] = new GraphQLEnumType({
205
- name: typeName,
206
- description: uriParameterNodeJson.description,
207
- values,
208
- });
209
- }
210
- if (uriParameterNodeJson.required) {
211
- argTypeMap[paramName] += '!';
129
+ if (uriParameterNodeJson.displayName) {
130
+ uriParameterNodeJson.title = uriParameterNodeJson.displayName;
212
131
  }
132
+ argTypeMap[argName] = uriParameterNodeJson;
213
133
  }
214
134
  for (const queryParameterNode of queryParameters) {
215
- requestSchema = requestSchema || {
216
- type: 'object',
217
- properties: {},
218
- required: [],
219
- };
220
135
  const parameterName = queryParameterNode.name();
136
+ const argName = sanitizeNameForGraphQL(parameterName);
221
137
  const queryParameterNodeJson = queryParameterNode.toJSON();
222
- if (queryParameterNodeJson.required) {
223
- requestSchema.required.push(parameterName);
224
- }
225
- if (queryParameterNodeJson.enum) {
226
- requestSchema.properties[parameterName] = {
227
- type: 'string',
228
- enum: queryParameterNodeJson.enum,
229
- };
230
- }
231
- if (queryParameterNodeJson.type) {
232
- requestSchema.properties[parameterName] = {
233
- type: asArray(queryParameterNodeJson.type)[0] || 'string',
234
- };
235
- }
236
- else {
237
- requestSchema.properties[parameterName] = toJsonSchema((_d = queryParameterNodeJson.example) !== null && _d !== void 0 ? _d : queryParameterNodeJson.default, {
238
- required: false,
239
- strings: {
240
- detectFormat: true,
241
- },
242
- });
243
- }
244
138
  if (queryParameterNodeJson.displayName) {
245
- requestSchema.properties[parameterName].title = queryParameterNodeJson.displayName;
246
- }
247
- if (queryParameterNode.description) {
248
- requestSchema.properties[parameterName].description =
249
- queryParameterNodeJson.description;
139
+ queryParameterNodeJson.title = queryParameterNodeJson.displayName;
250
140
  }
141
+ queryParamArgMap[parameterName] = argName;
142
+ argTypeMap[argName] = queryParameterNodeJson;
251
143
  }
252
144
  for (const bodyNode of bodyNodes) {
253
145
  if (bodyNode.name().includes('application/json')) {
@@ -267,7 +159,7 @@ async function getJSONSchemaOptionsFromRAMLOptions({ ramlFilePath, cwd: ramlFile
267
159
  }
268
160
  for (const responseNode of responses) {
269
161
  const statusCode = responseNode.code().value();
270
- const responseNodeDescription = (_e = responseNode.description()) === null || _e === void 0 ? void 0 : _e.value();
162
+ const responseNodeDescription = (_d = responseNode.description()) === null || _d === void 0 ? void 0 : _d.value();
271
163
  for (const bodyNode of responseNode.body()) {
272
164
  if (bodyNode.name().includes('application/json')) {
273
165
  const bodyJson = bodyNode.toJSON();
@@ -305,10 +197,10 @@ async function getJSONSchemaOptionsFromRAMLOptions({ ramlFilePath, cwd: ramlFile
305
197
  }
306
198
  fieldName =
307
199
  fieldName ||
308
- getFieldNameFromPath(originalFullRelativeUrl, method, (_f = responseByStatusCode['200']) === null || _f === void 0 ? void 0 : _f.responseTypeName);
200
+ getFieldNameFromPath(originalFullRelativeUrl, method, (_e = responseByStatusCode['200']) === null || _e === void 0 ? void 0 : _e.responseTypeName);
309
201
  if (fieldName) {
310
202
  const graphQLFieldName = sanitizeNameForGraphQL(fieldName);
311
- const operationType = ((_g = fieldTypeMap[graphQLFieldName]) !== null && _g !== void 0 ? _g : method === 'GET') ? 'query' : 'mutation';
203
+ const operationType = ((_f = fieldTypeMap[graphQLFieldName]) !== null && _f !== void 0 ? _f : method === 'GET') ? 'query' : 'mutation';
312
204
  operations.push({
313
205
  type: operationType,
314
206
  field: graphQLFieldName,
@@ -325,34 +217,8 @@ async function getJSONSchemaOptionsFromRAMLOptions({ ramlFilePath, cwd: ramlFile
325
217
  }
326
218
  return {
327
219
  operations,
328
- baseUrl,
220
+ endpoint,
329
221
  cwd,
330
- fetch: fetch$1,
222
+ fetch,
331
223
  };
332
224
  }
333
-
334
- /**
335
- * Creates a local GraphQLSchema instance from a RAML API Document.
336
- * Everytime this function is called, the RAML file and its dependencies will be resolved on runtime.
337
- * If you want to avoid this, use `createBundle` function to create a bundle once and save it to a storage
338
- * then load it with `loadGraphQLSchemaFromBundle`.
339
- */
340
- async function loadGraphQLSchemaFromRAML(name, options) {
341
- const extraJSONSchemaOptions = await getJSONSchemaOptionsFromRAMLOptions(options);
342
- return loadGraphQLSchemaFromJSONSchemas(name, {
343
- ...options,
344
- ...extraJSONSchemaOptions,
345
- });
346
- }
347
-
348
- /**
349
- * Creates a bundle by downloading and resolving the internal references once
350
- * to load the schema locally later
351
- */
352
- async function createBundle(name, ramlLoaderOptions) {
353
- const { operations, baseUrl, cwd, fetch } = await getJSONSchemaOptionsFromRAMLOptions(ramlLoaderOptions);
354
- return createBundle$1(name, { ...ramlLoaderOptions, baseUrl, operations, cwd, fetch });
355
- }
356
-
357
- export default loadGraphQLSchemaFromRAML;
358
- export { createBundle, getJSONSchemaOptionsFromRAMLOptions };
@@ -1,4 +1,3 @@
1
- export { loadGraphQLSchemaFromRAML as default } from './loadGraphQLSchemaFromRAML';
2
- export { getJSONSchemaOptionsFromRAMLOptions } from './getJSONSchemaOptionsFromRAMLOptions';
3
- export { RAMLLoaderOptions } from './types';
4
- export * from './bundle';
1
+ export { loadGraphQLSchemaFromRAML as default } from './loadGraphQLSchemaFromRAML.js';
2
+ export * from './loadGraphQLSchemaFromRAML.js';
3
+ export { getJSONSchemaOptionsFromRAMLOptions } from './getJSONSchemaOptionsFromRAMLOptions.js';
@@ -0,0 +1,23 @@
1
+ import { loadGraphQLSchemaFromJSONSchemas, loadNonExecutableGraphQLSchemaFromJSONSchemas, } from '@omnigraph/json-schema';
2
+ import { getJSONSchemaOptionsFromRAMLOptions } from './getJSONSchemaOptionsFromRAMLOptions.js';
3
+ /**
4
+ * Creates a local GraphQLSchema instance from a RAML API Document.
5
+ * Everytime this function is called, the RAML file and its dependencies will be resolved on runtime.
6
+ * If you want to avoid this, use `createBundle` function to create a bundle once and save it to a storage
7
+ * then load it with `loadGraphQLSchemaFromBundle`.
8
+ */
9
+ export async function loadGraphQLSchemaFromRAML(name, options) {
10
+ const extraJSONSchemaOptions = await getJSONSchemaOptionsFromRAMLOptions(options);
11
+ return loadGraphQLSchemaFromJSONSchemas(name, {
12
+ ...options,
13
+ ...extraJSONSchemaOptions,
14
+ });
15
+ }
16
+ export async function loadNonExecutableGraphQLSchemaFromRAML(name, options) {
17
+ const extraJSONSchemaOptions = await getJSONSchemaOptionsFromRAMLOptions(options);
18
+ return loadNonExecutableGraphQLSchemaFromJSONSchemas(name, {
19
+ ...options,
20
+ ...extraJSONSchemaOptions,
21
+ });
22
+ }
23
+ export { processDirectives } from '@omnigraph/json-schema';
package/esm/types.js ADDED
File without changes
package/esm/utils.js ADDED
@@ -0,0 +1,32 @@
1
+ import { camelCase } from 'change-case';
2
+ export function getFieldNameFromPath(path, method, typeName) {
3
+ // Replace identifiers with "by"
4
+ path = path.split('{').join('by_').split('}').join('');
5
+ const [actualPartsStr, allQueryPartsStr] = path.split('?');
6
+ const actualParts = actualPartsStr.split('/').filter(Boolean);
7
+ let fieldNameWithoutMethod = actualParts.join('_');
8
+ // If path doesn't give any field name without identifiers, we can use the return type with HTTP Method name
9
+ if ((!fieldNameWithoutMethod || fieldNameWithoutMethod.startsWith('by')) && typeName) {
10
+ // lowercase looks better in the schema
11
+ const prefix = camelCase(typeName);
12
+ if (fieldNameWithoutMethod) {
13
+ fieldNameWithoutMethod = prefix + '_' + fieldNameWithoutMethod;
14
+ }
15
+ else {
16
+ fieldNameWithoutMethod = prefix;
17
+ }
18
+ }
19
+ if (allQueryPartsStr) {
20
+ const queryParts = allQueryPartsStr.split('&');
21
+ for (const queryPart of queryParts) {
22
+ const [queryName] = queryPart.split('=');
23
+ fieldNameWithoutMethod += '_' + 'by' + '_' + queryName;
24
+ }
25
+ }
26
+ // get_ doesn't look good in field names
27
+ const methodPrefix = method.toLowerCase();
28
+ if (methodPrefix === 'get') {
29
+ return fieldNameWithoutMethod;
30
+ }
31
+ return methodPrefix + '_' + fieldNameWithoutMethod;
32
+ }
package/package.json CHANGED
@@ -1,22 +1,22 @@
1
1
  {
2
2
  "name": "@omnigraph/raml",
3
- "version": "1.0.0-alpha-3fc47d119.0",
3
+ "version": "1.0.0-alpha-20230420181317-a95037648",
4
4
  "sideEffects": false,
5
5
  "peerDependencies": {
6
- "@graphql-mesh/utils": "1.0.0-alpha-3fc47d119.0",
7
- "graphql": "*"
6
+ "@graphql-mesh/cross-helpers": "^0.3.4",
7
+ "@graphql-mesh/utils": "1.0.0-alpha-20230420181317-a95037648",
8
+ "@graphql-tools/utils": "^9.2.1",
9
+ "graphql": "*",
10
+ "tslib": "^2.4.0"
8
11
  },
9
12
  "dependencies": {
10
13
  "@ardatan/raml-1-parser": "1.1.69",
11
- "@graphql-mesh/cross-helpers": "0.2.0",
12
- "@graphql-mesh/string-interpolation": "0.3.0",
13
- "@graphql-tools/utils": "8.8.0",
14
- "@omnigraph/json-schema": "1.0.0-alpha-3fc47d119.0",
15
- "@whatwg-node/fetch": "^0.0.2",
14
+ "@graphql-mesh/string-interpolation": "0.4.4",
15
+ "@omnigraph/json-schema": "1.0.0-alpha-20230420181317-a95037648",
16
+ "@whatwg-node/fetch": "^0.8.0",
16
17
  "change-case": "4.1.2",
17
- "json-machete": "1.0.0-alpha-3fc47d119.0",
18
- "to-json-schema": "0.2.5",
19
- "tslib": "^2.4.0"
18
+ "json-machete": "1.0.0-alpha-20230420181317-a95037648",
19
+ "to-json-schema": "0.2.5"
20
20
  },
21
21
  "repository": {
22
22
  "type": "git",
@@ -24,21 +24,28 @@
24
24
  "directory": "packages/loaders/raml"
25
25
  },
26
26
  "license": "MIT",
27
- "main": "index.js",
28
- "module": "index.mjs",
29
- "typings": "index.d.ts",
27
+ "main": "cjs/index.js",
28
+ "module": "esm/index.js",
29
+ "typings": "typings/index.d.ts",
30
30
  "typescript": {
31
- "definition": "index.d.ts"
31
+ "definition": "typings/index.d.ts"
32
32
  },
33
+ "type": "module",
33
34
  "exports": {
34
35
  ".": {
35
- "require": "./index.js",
36
- "import": "./index.mjs"
37
- },
38
- "./*": {
39
- "require": "./*.js",
40
- "import": "./*.mjs"
36
+ "require": {
37
+ "types": "./typings/index.d.cts",
38
+ "default": "./cjs/index.js"
39
+ },
40
+ "import": {
41
+ "types": "./typings/index.d.ts",
42
+ "default": "./esm/index.js"
43
+ },
44
+ "default": {
45
+ "types": "./typings/index.d.ts",
46
+ "default": "./esm/index.js"
47
+ }
41
48
  },
42
49
  "./package.json": "./package.json"
43
50
  }
44
- }
51
+ }
@@ -0,0 +1,13 @@
1
+ import { JSONSchemaOperationConfig } from '@omnigraph/json-schema';
2
+ import { RAMLLoaderOptions } from './types.cjs';
3
+ /**
4
+ * Generates the options for JSON Schema Loader
5
+ * from RAML Loader options by extracting the JSON Schema references
6
+ * from RAML API Document
7
+ */
8
+ export declare function getJSONSchemaOptionsFromRAMLOptions({ source, cwd: ramlFileCwd, operations: extraOperations, endpoint: forcedBaseUrl, fetch, schemaHeaders, selectQueryOrMutationField, }: RAMLLoaderOptions): Promise<{
9
+ operations: JSONSchemaOperationConfig[];
10
+ cwd: string;
11
+ endpoint: string;
12
+ fetch?: WindowOrWorkerGlobalScope['fetch'];
13
+ }>;
@@ -1,13 +1,13 @@
1
1
  import { JSONSchemaOperationConfig } from '@omnigraph/json-schema';
2
- import { RAMLLoaderOptions } from './types';
2
+ import { RAMLLoaderOptions } from './types.js';
3
3
  /**
4
4
  * Generates the options for JSON Schema Loader
5
5
  * from RAML Loader options by extracting the JSON Schema references
6
6
  * from RAML API Document
7
7
  */
8
- export declare function getJSONSchemaOptionsFromRAMLOptions({ ramlFilePath, cwd: ramlFileCwd, operations: extraOperations, baseUrl: forcedBaseUrl, fetch, schemaHeaders, selectQueryOrMutationField, }: RAMLLoaderOptions): Promise<{
8
+ export declare function getJSONSchemaOptionsFromRAMLOptions({ source, cwd: ramlFileCwd, operations: extraOperations, endpoint: forcedBaseUrl, fetch, schemaHeaders, selectQueryOrMutationField, }: RAMLLoaderOptions): Promise<{
9
9
  operations: JSONSchemaOperationConfig[];
10
10
  cwd: string;
11
- baseUrl: string;
11
+ endpoint: string;
12
12
  fetch?: WindowOrWorkerGlobalScope['fetch'];
13
13
  }>;
@@ -0,0 +1,4 @@
1
+ export { loadGraphQLSchemaFromRAML as default } from './loadGraphQLSchemaFromRAML.cjs';
2
+ export * from './loadGraphQLSchemaFromRAML.cjs';
3
+ export { getJSONSchemaOptionsFromRAMLOptions } from './getJSONSchemaOptionsFromRAMLOptions.cjs';
4
+ export { RAMLLoaderOptions } from './types.cjs';
@@ -0,0 +1,4 @@
1
+ export { loadGraphQLSchemaFromRAML as default } from './loadGraphQLSchemaFromRAML.js';
2
+ export * from './loadGraphQLSchemaFromRAML.js';
3
+ export { getJSONSchemaOptionsFromRAMLOptions } from './getJSONSchemaOptionsFromRAMLOptions.js';
4
+ export { RAMLLoaderOptions } from './types.js';
@@ -0,0 +1,10 @@
1
+ import { RAMLLoaderOptions } from './types.cjs';
2
+ /**
3
+ * Creates a local GraphQLSchema instance from a RAML API Document.
4
+ * Everytime this function is called, the RAML 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 loadGraphQLSchemaFromRAML(name: string, options: RAMLLoaderOptions): Promise<import("graphql").GraphQLSchema>;
9
+ export declare function loadNonExecutableGraphQLSchemaFromRAML(name: string, options: RAMLLoaderOptions): Promise<import("graphql").GraphQLSchema>;
10
+ export { processDirectives } from '@omnigraph/json-schema';
@@ -1,4 +1,4 @@
1
- import { RAMLLoaderOptions } from './types';
1
+ import { RAMLLoaderOptions } from './types.js';
2
2
  /**
3
3
  * Creates a local GraphQLSchema instance from a RAML API Document.
4
4
  * Everytime this function is called, the RAML file and its dependencies will be resolved on runtime.
@@ -6,3 +6,5 @@ import { RAMLLoaderOptions } from './types';
6
6
  * then load it with `loadGraphQLSchemaFromBundle`.
7
7
  */
8
8
  export declare function loadGraphQLSchemaFromRAML(name: string, options: RAMLLoaderOptions): Promise<import("graphql").GraphQLSchema>;
9
+ export declare function loadNonExecutableGraphQLSchemaFromRAML(name: string, options: RAMLLoaderOptions): Promise<import("graphql").GraphQLSchema>;
10
+ export { processDirectives } from '@omnigraph/json-schema';
@@ -0,0 +1,9 @@
1
+ import { JSONSchemaLoaderOptions } from '@omnigraph/json-schema';
2
+ export interface RAMLLoaderOptions extends Partial<JSONSchemaLoaderOptions> {
3
+ source: string;
4
+ selectQueryOrMutationField?: RAMLLoaderSelectQueryOrMutationFieldConfig[];
5
+ }
6
+ export interface RAMLLoaderSelectQueryOrMutationFieldConfig {
7
+ type: 'query' | 'mutation' | 'Query' | 'Mutation';
8
+ fieldName: string;
9
+ }
@@ -1,9 +1,9 @@
1
1
  import { JSONSchemaLoaderOptions } from '@omnigraph/json-schema';
2
2
  export interface RAMLLoaderOptions extends Partial<JSONSchemaLoaderOptions> {
3
- ramlFilePath: string;
3
+ source: string;
4
4
  selectQueryOrMutationField?: RAMLLoaderSelectQueryOrMutationFieldConfig[];
5
5
  }
6
6
  export interface RAMLLoaderSelectQueryOrMutationFieldConfig {
7
- type: 'query' | 'mutation';
7
+ type: 'query' | 'mutation' | 'Query' | 'Mutation';
8
8
  fieldName: string;
9
9
  }
@@ -0,0 +1 @@
1
+ export declare function getFieldNameFromPath(path: string, method: string, typeName: string): string;
package/bundle.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import { getGraphQLSchemaFromBundle, JSONSchemaLoaderBundle as RAMLLoaderBundle } from '@omnigraph/json-schema';
2
- import { RAMLLoaderOptions } 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, ramlLoaderOptions: RAMLLoaderOptions): Promise<RAMLLoaderBundle>;
8
- export { getGraphQLSchemaFromBundle, RAMLLoaderBundle };
package/index.js DELETED
@@ -1,370 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- const jsonSchema = require('@omnigraph/json-schema');
8
- const utils = require('@graphql-mesh/utils');
9
- const jsonMachete = require('json-machete');
10
- const raml1Parser = require('@ardatan/raml-1-parser');
11
- const fetch = require('@whatwg-node/fetch');
12
- const toJsonSchema = _interopDefault(require('to-json-schema'));
13
- const utils$1 = require('@graphql-tools/utils');
14
- const changeCase = require('change-case');
15
- const graphql = require('graphql');
16
- const stringInterpolation = require('@graphql-mesh/string-interpolation');
17
- const crossHelpers = require('@graphql-mesh/cross-helpers');
18
-
19
- function getFieldNameFromPath(path, method, typeName) {
20
- // Replace identifiers with "by"
21
- path = path.split('{').join('by_').split('}').join('');
22
- const [actualPartsStr, allQueryPartsStr] = path.split('?');
23
- const actualParts = actualPartsStr.split('/').filter(Boolean);
24
- let fieldNameWithoutMethod = actualParts.join('_');
25
- // If path doesn't give any field name without identifiers, we can use the return type with HTTP Method name
26
- if ((!fieldNameWithoutMethod || fieldNameWithoutMethod.startsWith('by')) && typeName) {
27
- // lowercase looks better in the schema
28
- const prefix = changeCase.camelCase(typeName);
29
- if (fieldNameWithoutMethod) {
30
- fieldNameWithoutMethod = prefix + '_' + fieldNameWithoutMethod;
31
- }
32
- else {
33
- fieldNameWithoutMethod = prefix;
34
- }
35
- }
36
- if (allQueryPartsStr) {
37
- const queryParts = allQueryPartsStr.split('&');
38
- for (const queryPart of queryParts) {
39
- const [queryName] = queryPart.split('=');
40
- fieldNameWithoutMethod += '_' + 'by' + '_' + queryName;
41
- }
42
- }
43
- // get_ doesn't look good in field names
44
- const methodPrefix = method.toLowerCase();
45
- if (methodPrefix === 'get') {
46
- return fieldNameWithoutMethod;
47
- }
48
- return methodPrefix + '_' + fieldNameWithoutMethod;
49
- }
50
-
51
- function resolveTraitsByIs(base) {
52
- const allTraits = [];
53
- for (const traitRef of base.is()) {
54
- const traitNode = traitRef.trait();
55
- if (traitNode) {
56
- allTraits.push(traitNode);
57
- allTraits.push(...resolveTraitsByIs(traitNode));
58
- }
59
- }
60
- return allTraits;
61
- }
62
- /**
63
- * Generates the options for JSON Schema Loader
64
- * from RAML Loader options by extracting the JSON Schema references
65
- * from RAML API Document
66
- */
67
- async function getJSONSchemaOptionsFromRAMLOptions({ ramlFilePath, cwd: ramlFileCwd = crossHelpers.process.cwd(), operations: extraOperations, baseUrl: forcedBaseUrl, fetch: fetch$1 = fetch.fetch, schemaHeaders = {}, selectQueryOrMutationField = [], }) {
68
- var _a, _b, _c, _d, _e, _f, _g;
69
- const fieldTypeMap = {};
70
- for (const { fieldName, type } of selectQueryOrMutationField) {
71
- fieldTypeMap[fieldName] = type;
72
- }
73
- const operations = extraOperations || [];
74
- const ramlAbsolutePath = jsonMachete.getAbsolutePath(ramlFilePath, ramlFileCwd);
75
- const schemaHeadersFactory = stringInterpolation.getInterpolatedHeadersFactory(schemaHeaders);
76
- const ramlAPI = (await raml1Parser.loadApi(ramlAbsolutePath, [], {
77
- httpResolver: {
78
- getResourceAsync: async (url) => {
79
- const fetchResponse = await fetch$1(url, {
80
- headers: schemaHeadersFactory({ env: crossHelpers.process.env }),
81
- });
82
- const content = await fetchResponse.text();
83
- if (fetchResponse.status !== 200) {
84
- return {
85
- errorMessage: content,
86
- };
87
- }
88
- return {
89
- content,
90
- };
91
- },
92
- getResource: () => {
93
- throw new Error(`Sync fetching not available for URLs`);
94
- },
95
- },
96
- }));
97
- let baseUrl = forcedBaseUrl;
98
- if (!baseUrl) {
99
- baseUrl = ramlAPI.baseUri().value();
100
- for (const baseUrlParamNode of ramlAPI.baseUriParameters()) {
101
- const paramName = baseUrlParamNode.name();
102
- baseUrl = baseUrl.split(`{${paramName}}`).join(`{context.${paramName}}`);
103
- }
104
- }
105
- const pathTypeMap = new Map();
106
- const typePathMap = new Map();
107
- for (const typeNode of ramlAPI.types()) {
108
- const typeNodeJson = typeNode.toJSON();
109
- for (const typeName in typeNodeJson) {
110
- const { schemaPath } = typeNodeJson[typeName];
111
- if (schemaPath) {
112
- pathTypeMap.set(schemaPath, typeName);
113
- typePathMap.set(typeName, schemaPath);
114
- }
115
- }
116
- }
117
- const cwd = jsonMachete.getCwd(ramlAbsolutePath);
118
- const apiQueryParameters = [];
119
- const apiBodyNodes = [];
120
- const apiResponses = [];
121
- for (const traitNode of ramlAPI.traits()) {
122
- apiQueryParameters.push(...traitNode.queryParameters());
123
- apiBodyNodes.push(...traitNode.body());
124
- apiResponses.push(...traitNode.responses());
125
- const nestedTraits = resolveTraitsByIs(traitNode);
126
- for (const nestedTrait of nestedTraits) {
127
- apiQueryParameters.push(...nestedTrait.queryParameters());
128
- apiBodyNodes.push(...nestedTrait.body());
129
- apiResponses.push(...nestedTrait.responses());
130
- }
131
- }
132
- for (const resourceNode of ramlAPI.allResources()) {
133
- const resourceQueryParameters = [...apiQueryParameters];
134
- const resourceBodyNodes = [...apiBodyNodes];
135
- const resourceResponses = [...apiResponses];
136
- const resourceTraits = resolveTraitsByIs(resourceNode);
137
- for (const traitNode of resourceTraits) {
138
- apiQueryParameters.push(...traitNode.queryParameters());
139
- apiBodyNodes.push(...traitNode.body());
140
- apiResponses.push(...traitNode.responses());
141
- }
142
- for (const methodNode of resourceNode.methods()) {
143
- const queryParameters = [...resourceQueryParameters];
144
- const bodyNodes = [...resourceBodyNodes];
145
- const responses = [...resourceResponses];
146
- const traits = resolveTraitsByIs(methodNode);
147
- for (const traitNode of traits) {
148
- queryParameters.push(...traitNode.queryParameters());
149
- bodyNodes.push(...traitNode.body());
150
- responses.push(...traitNode.responses());
151
- }
152
- queryParameters.push(...methodNode.queryParameters());
153
- bodyNodes.push(...methodNode.body());
154
- responses.push(...methodNode.responses());
155
- let requestSchema;
156
- let requestTypeName;
157
- const responseByStatusCode = {};
158
- const method = methodNode.method().toUpperCase();
159
- let fieldName = (_a = methodNode.displayName()) === null || _a === void 0 ? void 0 : _a.replace('GET_', '');
160
- const description = ((_b = methodNode.description()) === null || _b === void 0 ? void 0 : _b.value()) || ((_c = resourceNode.description()) === null || _c === void 0 ? void 0 : _c.value());
161
- const originalFullRelativeUrl = resourceNode.completeRelativeUri();
162
- let fullRelativeUrl = originalFullRelativeUrl;
163
- const argTypeMap = {};
164
- for (const uriParameterNode of resourceNode.uriParameters()) {
165
- const paramName = uriParameterNode.name();
166
- fullRelativeUrl = fullRelativeUrl.replace(`{${paramName}}`, `{args.${paramName}}`);
167
- const uriParameterNodeJson = uriParameterNode.toJSON();
168
- for (const typeName of utils$1.asArray(uriParameterNodeJson.type)) {
169
- switch (typeName) {
170
- case 'number':
171
- argTypeMap[paramName] = 'Float';
172
- break;
173
- case 'boolean':
174
- argTypeMap[paramName] = 'Boolean';
175
- break;
176
- case 'integer':
177
- argTypeMap[paramName] = 'Int';
178
- break;
179
- default:
180
- argTypeMap[paramName] = 'String';
181
- break;
182
- }
183
- }
184
- /* raml pattern is different
185
- if (uriParameterNodeJson.pattern) {
186
- const typeName = sanitizeNameForGraphQL(uriParameterNodeJson.displayName || `${fieldName}_${paramName}`);
187
- argTypeMap[paramName] = new RegularExpression(typeName, new RegExp(uriParameterNodeJson.pattern), {
188
- description: uriParameterNodeJson.description,
189
- });
190
- }
191
- */
192
- if (uriParameterNodeJson.enum) {
193
- const typeName = utils.sanitizeNameForGraphQL(uriParameterNodeJson.displayName || `${fieldName}_${paramName}`);
194
- const values = {};
195
- for (const value of utils$1.asArray(uriParameterNodeJson.enum)) {
196
- let enumKey = utils.sanitizeNameForGraphQL(value.toString());
197
- if (enumKey === 'false' || enumKey === 'true' || enumKey === 'null') {
198
- enumKey = enumKey.toUpperCase();
199
- }
200
- if (typeof enumKey === 'string' && enumKey.length === 0) {
201
- enumKey = '_';
202
- }
203
- values[enumKey] = {
204
- // Falsy values are ignored by GraphQL
205
- // eslint-disable-next-line no-unneeded-ternary
206
- value: value ? value : value === null || value === void 0 ? void 0 : value.toString(),
207
- };
208
- }
209
- argTypeMap[paramName] = new graphql.GraphQLEnumType({
210
- name: typeName,
211
- description: uriParameterNodeJson.description,
212
- values,
213
- });
214
- }
215
- if (uriParameterNodeJson.required) {
216
- argTypeMap[paramName] += '!';
217
- }
218
- }
219
- for (const queryParameterNode of queryParameters) {
220
- requestSchema = requestSchema || {
221
- type: 'object',
222
- properties: {},
223
- required: [],
224
- };
225
- const parameterName = queryParameterNode.name();
226
- const queryParameterNodeJson = queryParameterNode.toJSON();
227
- if (queryParameterNodeJson.required) {
228
- requestSchema.required.push(parameterName);
229
- }
230
- if (queryParameterNodeJson.enum) {
231
- requestSchema.properties[parameterName] = {
232
- type: 'string',
233
- enum: queryParameterNodeJson.enum,
234
- };
235
- }
236
- if (queryParameterNodeJson.type) {
237
- requestSchema.properties[parameterName] = {
238
- type: utils$1.asArray(queryParameterNodeJson.type)[0] || 'string',
239
- };
240
- }
241
- else {
242
- requestSchema.properties[parameterName] = toJsonSchema((_d = queryParameterNodeJson.example) !== null && _d !== void 0 ? _d : queryParameterNodeJson.default, {
243
- required: false,
244
- strings: {
245
- detectFormat: true,
246
- },
247
- });
248
- }
249
- if (queryParameterNodeJson.displayName) {
250
- requestSchema.properties[parameterName].title = queryParameterNodeJson.displayName;
251
- }
252
- if (queryParameterNode.description) {
253
- requestSchema.properties[parameterName].description =
254
- queryParameterNodeJson.description;
255
- }
256
- }
257
- for (const bodyNode of bodyNodes) {
258
- if (bodyNode.name().includes('application/json')) {
259
- const bodyJson = bodyNode.toJSON();
260
- if (bodyJson.schemaPath) {
261
- const schemaPath = bodyJson.schemaPath;
262
- requestSchema = schemaPath;
263
- requestTypeName = pathTypeMap.get(schemaPath);
264
- }
265
- else if (bodyJson.type) {
266
- const typeName = utils$1.asArray(bodyJson.type)[0];
267
- requestTypeName = typeName;
268
- const schemaPath = typePathMap.get(typeName);
269
- requestSchema = schemaPath;
270
- }
271
- }
272
- }
273
- for (const responseNode of responses) {
274
- const statusCode = responseNode.code().value();
275
- const responseNodeDescription = (_e = responseNode.description()) === null || _e === void 0 ? void 0 : _e.value();
276
- for (const bodyNode of responseNode.body()) {
277
- if (bodyNode.name().includes('application/json')) {
278
- const bodyJson = bodyNode.toJSON();
279
- if (bodyJson.schemaPath) {
280
- const schemaPath = bodyJson.schemaPath;
281
- const typeName = pathTypeMap.get(schemaPath);
282
- if (schemaPath) {
283
- responseByStatusCode[statusCode] = {
284
- responseSchema: schemaPath,
285
- responseTypeName: typeName,
286
- };
287
- }
288
- }
289
- else if (bodyJson.type) {
290
- const typeName = utils$1.asArray(bodyJson.type)[0];
291
- const schemaPath = typePathMap.get(typeName);
292
- if (schemaPath) {
293
- responseByStatusCode[statusCode] = {
294
- responseSchema: schemaPath,
295
- responseTypeName: typeName,
296
- };
297
- }
298
- }
299
- if (!responseByStatusCode[statusCode] && bodyJson.example) {
300
- const responseSchema = toJsonSchema(bodyJson.example, {
301
- required: false,
302
- });
303
- responseSchema.description = responseNodeDescription;
304
- responseByStatusCode[statusCode] = {
305
- responseSchema,
306
- };
307
- }
308
- }
309
- }
310
- }
311
- fieldName =
312
- fieldName ||
313
- getFieldNameFromPath(originalFullRelativeUrl, method, (_f = responseByStatusCode['200']) === null || _f === void 0 ? void 0 : _f.responseTypeName);
314
- if (fieldName) {
315
- const graphQLFieldName = utils.sanitizeNameForGraphQL(fieldName);
316
- const operationType = ((_g = fieldTypeMap[graphQLFieldName]) !== null && _g !== void 0 ? _g : method === 'GET') ? 'query' : 'mutation';
317
- operations.push({
318
- type: operationType,
319
- field: graphQLFieldName,
320
- description,
321
- path: fullRelativeUrl,
322
- method,
323
- requestSchema,
324
- requestTypeName,
325
- responseByStatusCode,
326
- argTypeMap,
327
- });
328
- }
329
- }
330
- }
331
- return {
332
- operations,
333
- baseUrl,
334
- cwd,
335
- fetch: fetch$1,
336
- };
337
- }
338
-
339
- /**
340
- * Creates a local GraphQLSchema instance from a RAML API Document.
341
- * Everytime this function is called, the RAML file and its dependencies will be resolved on runtime.
342
- * If you want to avoid this, use `createBundle` function to create a bundle once and save it to a storage
343
- * then load it with `loadGraphQLSchemaFromBundle`.
344
- */
345
- async function loadGraphQLSchemaFromRAML(name, options) {
346
- const extraJSONSchemaOptions = await getJSONSchemaOptionsFromRAMLOptions(options);
347
- return jsonSchema.loadGraphQLSchemaFromJSONSchemas(name, {
348
- ...options,
349
- ...extraJSONSchemaOptions,
350
- });
351
- }
352
-
353
- /**
354
- * Creates a bundle by downloading and resolving the internal references once
355
- * to load the schema locally later
356
- */
357
- async function createBundle(name, ramlLoaderOptions) {
358
- const { operations, baseUrl, cwd, fetch } = await getJSONSchemaOptionsFromRAMLOptions(ramlLoaderOptions);
359
- return jsonSchema.createBundle(name, { ...ramlLoaderOptions, baseUrl, operations, cwd, fetch });
360
- }
361
-
362
- Object.defineProperty(exports, 'getGraphQLSchemaFromBundle', {
363
- enumerable: true,
364
- get: function () {
365
- return jsonSchema.getGraphQLSchemaFromBundle;
366
- }
367
- });
368
- exports.createBundle = createBundle;
369
- exports.default = loadGraphQLSchemaFromRAML;
370
- exports.getJSONSchemaOptionsFromRAMLOptions = getJSONSchemaOptionsFromRAMLOptions;
File without changes