@graphql-mesh/runtime 1.0.0-alpha-20220804093904-8e2e41f7f → 1.0.0-alpha-20230420220344-25b6b92bf

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/index.js DELETED
@@ -1,434 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- const graphql = require('graphql');
6
- const utils = require('@graphql-mesh/utils');
7
- const utils$1 = require('@graphql-tools/utils');
8
- const core = require('@envelop/core');
9
- const extendedValidation = require('@envelop/extended-validation');
10
- const batchDelegate = require('@graphql-tools/batch-delegate');
11
- const delegate = require('@graphql-tools/delegate');
12
- const wrap = require('@graphql-tools/wrap');
13
-
14
- const MESH_CONTEXT_SYMBOL = Symbol('isMeshContext');
15
- const MESH_API_CONTEXT_SYMBOL = Symbol('isMeshAPIContext');
16
-
17
- async function getInContextSDK(unifiedSchema, rawSources, logger) {
18
- const inContextSDK = {};
19
- const sourceMap = unifiedSchema.extensions.sourceMap;
20
- for (const rawSource of rawSources) {
21
- const rawSourceLogger = logger.child(`${rawSource.name}`);
22
- const rawSourceContext = {
23
- rawSource,
24
- [MESH_API_CONTEXT_SYMBOL]: true,
25
- };
26
- // TODO: Somehow rawSource reference got lost in somewhere
27
- let rawSourceSubSchemaConfig;
28
- const stitchingInfo = unifiedSchema.extensions.stitchingInfo;
29
- if (stitchingInfo) {
30
- for (const [subschemaConfig, subschema] of stitchingInfo.subschemaMap) {
31
- if (subschemaConfig.name === rawSource.name) {
32
- rawSourceSubSchemaConfig = subschema;
33
- break;
34
- }
35
- }
36
- }
37
- else {
38
- rawSourceSubSchemaConfig = rawSource;
39
- }
40
- // If there is a single source, there is no unifiedSchema
41
- const transformedSchema = sourceMap.get(rawSource);
42
- const rootTypes = {
43
- query: transformedSchema.getQueryType(),
44
- mutation: transformedSchema.getMutationType(),
45
- subscription: transformedSchema.getSubscriptionType(),
46
- };
47
- rawSourceLogger.debug(`Generating In Context SDK`);
48
- for (const operationType in rootTypes) {
49
- const rootType = rootTypes[operationType];
50
- if (rootType) {
51
- rawSourceContext[rootType.name] = {};
52
- const rootTypeFieldMap = rootType.getFields();
53
- for (const fieldName in rootTypeFieldMap) {
54
- const rootTypeField = rootTypeFieldMap[fieldName];
55
- const inContextSdkLogger = rawSourceLogger.child(`InContextSDK.${rootType.name}.${fieldName}`);
56
- const namedReturnType = graphql.getNamedType(rootTypeField.type);
57
- const shouldHaveSelectionSet = !graphql.isLeafType(namedReturnType);
58
- rawSourceContext[rootType.name][fieldName] = ({ root, args, context, info = {
59
- fieldName,
60
- fieldNodes: [],
61
- returnType: namedReturnType,
62
- parentType: rootType,
63
- path: {
64
- typename: rootType.name,
65
- key: fieldName,
66
- prev: undefined,
67
- },
68
- schema: transformedSchema,
69
- fragments: {},
70
- rootValue: root,
71
- operation: {
72
- kind: graphql.Kind.OPERATION_DEFINITION,
73
- operation: operationType,
74
- selectionSet: {
75
- kind: graphql.Kind.SELECTION_SET,
76
- selections: [],
77
- },
78
- },
79
- variableValues: {},
80
- cacheControl: {
81
- setCacheHint: () => { },
82
- cacheHint: {},
83
- },
84
- }, selectionSet, key, argsFromKeys, valuesFromResults, }) => {
85
- inContextSdkLogger.debug(`Called with`, {
86
- args,
87
- key,
88
- });
89
- const commonDelegateOptions = {
90
- schema: rawSourceSubSchemaConfig,
91
- rootValue: root,
92
- operation: operationType,
93
- fieldName,
94
- context,
95
- transformedSchema,
96
- info,
97
- };
98
- // If there isn't an extraction of a value
99
- if (typeof selectionSet !== 'function') {
100
- commonDelegateOptions.returnType = rootTypeField.type;
101
- }
102
- if (shouldHaveSelectionSet) {
103
- let selectionCount = 0;
104
- for (const fieldNode of info.fieldNodes) {
105
- if (fieldNode.selectionSet != null) {
106
- selectionCount += fieldNode.selectionSet.selections.length;
107
- }
108
- }
109
- if (selectionCount === 0) {
110
- if (!selectionSet) {
111
- throw new Error(`You have to provide 'selectionSet' for context.${rawSource.name}.${rootType.name}.${fieldName}`);
112
- }
113
- commonDelegateOptions.info = {
114
- ...info,
115
- fieldNodes: [
116
- {
117
- ...info.fieldNodes[0],
118
- selectionSet: {
119
- kind: graphql.Kind.SELECTION_SET,
120
- selections: [
121
- {
122
- kind: graphql.Kind.FIELD,
123
- name: {
124
- kind: graphql.Kind.NAME,
125
- value: '__typename',
126
- },
127
- },
128
- ],
129
- },
130
- },
131
- ...info.fieldNodes.slice(1),
132
- ],
133
- };
134
- }
135
- }
136
- if (key && argsFromKeys) {
137
- const batchDelegationOptions = {
138
- ...commonDelegateOptions,
139
- key,
140
- argsFromKeys,
141
- valuesFromResults,
142
- };
143
- if (selectionSet) {
144
- const selectionSetFactory = normalizeSelectionSetParamOrFactory(selectionSet);
145
- const path = [fieldName];
146
- const wrapQueryTransform = new wrap.WrapQuery(path, selectionSetFactory, identical);
147
- batchDelegationOptions.transforms = [wrapQueryTransform];
148
- }
149
- return batchDelegate.batchDelegateToSchema(batchDelegationOptions);
150
- }
151
- else {
152
- const regularDelegateOptions = {
153
- ...commonDelegateOptions,
154
- args,
155
- };
156
- if (selectionSet) {
157
- const selectionSetFactory = normalizeSelectionSetParamOrFactory(selectionSet);
158
- const path = [fieldName];
159
- const wrapQueryTransform = new wrap.WrapQuery(path, selectionSetFactory, valuesFromResults || identical);
160
- regularDelegateOptions.transforms = [wrapQueryTransform];
161
- }
162
- return delegate.delegateToSchema(regularDelegateOptions);
163
- }
164
- };
165
- }
166
- }
167
- }
168
- inContextSDK[rawSource.name] = rawSourceContext;
169
- }
170
- return inContextSDK;
171
- }
172
- function normalizeSelectionSetParam(selectionSetParam) {
173
- if (typeof selectionSetParam === 'string') {
174
- return utils$1.parseSelectionSet(selectionSetParam);
175
- }
176
- if (utils$1.isDocumentNode(selectionSetParam)) {
177
- return utils$1.parseSelectionSet(utils.printWithCache(selectionSetParam));
178
- }
179
- return selectionSetParam;
180
- }
181
- function normalizeSelectionSetParamOrFactory(selectionSetParamOrFactory) {
182
- return function getSelectionSet(subtree) {
183
- if (typeof selectionSetParamOrFactory === 'function') {
184
- const selectionSetParam = selectionSetParamOrFactory(subtree);
185
- return normalizeSelectionSetParam(selectionSetParam);
186
- }
187
- else {
188
- return normalizeSelectionSetParam(selectionSetParamOrFactory);
189
- }
190
- };
191
- }
192
- function identical(val) {
193
- return val;
194
- }
195
-
196
- function getExecuteFnByArgs(args, subschema) {
197
- var _a, _b;
198
- const transformationContext = {};
199
- const originalRequest = {
200
- document: args.document,
201
- variables: args.variableValues,
202
- operationName: (_a = args.operationName) !== null && _a !== void 0 ? _a : undefined,
203
- rootValue: args.rootValue,
204
- context: args.contextValue,
205
- };
206
- const operationAST = utils$1.getOperationASTFromRequest(originalRequest);
207
- const delegationContext = {
208
- subschema,
209
- subschemaConfig: subschema,
210
- targetSchema: args.schema,
211
- operation: operationAST.operation,
212
- fieldName: '',
213
- context: args.contextValue,
214
- rootValue: args.rootValue,
215
- transforms: subschema.transforms,
216
- transformedSchema: args.schema,
217
- skipTypeMerging: true,
218
- returnType: {}, // Might not work
219
- };
220
- const executor = (_b = subschema.executor) !== null && _b !== void 0 ? _b : delegate.createDefaultExecutor(subschema.schema);
221
- return async function subschemaExecute() {
222
- const transformedRequest = utils.applyRequestTransforms(originalRequest, delegationContext, transformationContext, subschema.transforms);
223
- const originalResult = await executor(transformedRequest);
224
- if (utils$1.isAsyncIterable(originalResult)) {
225
- return core.mapAsyncIterator(originalResult, singleResult => utils.applyResultTransforms(singleResult, delegationContext, transformationContext, subschema.transforms));
226
- }
227
- const transformedResult = utils.applyResultTransforms(originalResult, delegationContext, transformationContext, subschema.transforms);
228
- return transformedResult;
229
- };
230
- }
231
- // Creates an envelop plugin to execute a subschema inside Envelop
232
- function useSubschema(subschema) {
233
- const transformedSchema = utils.applySchemaTransforms(subschema.schema, subschema, subschema.schema, subschema.transforms);
234
- const plugin = {
235
- onPluginInit({ setSchema }) {
236
- setSchema(transformedSchema);
237
- },
238
- onExecute({ args, setExecuteFn, setResultAndStopExecution }) {
239
- // TODO: This is a hack to make introspection work properly
240
- if (args.operationName === 'IntrospectionQuery') {
241
- setResultAndStopExecution({
242
- data: graphql.introspectionFromSchema(args.schema),
243
- });
244
- }
245
- setExecuteFn(getExecuteFnByArgs(args, subschema));
246
- },
247
- onSubscribe({ args, setSubscribeFn }) {
248
- setSubscribeFn(getExecuteFnByArgs(args, subschema));
249
- },
250
- };
251
- return {
252
- transformedSchema,
253
- plugin,
254
- };
255
- }
256
-
257
- const memoizedGetOperationType = utils$1.memoize1((document) => {
258
- const operationAST = graphql.getOperationAST(document, undefined);
259
- if (!operationAST) {
260
- throw new Error('Must provide document with a valid operation');
261
- }
262
- return operationAST.operation;
263
- });
264
- const memoizedGetEnvelopedFactory = utils$1.memoize1(function getEnvelopedFactory(plugins) {
265
- const getEnveloped = core.envelop({ plugins });
266
- return utils$1.memoize1(function getEnvelopedByContext(initialContext) {
267
- return getEnveloped(initialContext);
268
- });
269
- });
270
- async function getMesh(options) {
271
- const rawSources = [];
272
- const { pubsub = new utils.PubSub(), cache, logger = new utils.DefaultLogger('🕸️ Mesh'), additionalEnvelopPlugins = [], sources, merger, additionalResolvers = [], additionalTypeDefs = [], transforms = [], } = options;
273
- const getMeshLogger = logger.child('GetMesh');
274
- getMeshLogger.debug(`Getting subschemas from source handlers`);
275
- let failed = false;
276
- await Promise.allSettled(sources.map(async (apiSource) => {
277
- const apiName = apiSource.name;
278
- const sourceLogger = logger.child(apiName);
279
- sourceLogger.debug(`Generating the schema`);
280
- try {
281
- const source = await apiSource.handler.getMeshSource();
282
- sourceLogger.debug(`The schema has been generated successfully`);
283
- let apiSchema = source.schema;
284
- sourceLogger.debug(`Analyzing transforms`);
285
- let transforms;
286
- const { wrapTransforms, noWrapTransforms } = utils.groupTransforms(apiSource.transforms);
287
- if (!(wrapTransforms === null || wrapTransforms === void 0 ? void 0 : wrapTransforms.length) && (noWrapTransforms === null || noWrapTransforms === void 0 ? void 0 : noWrapTransforms.length)) {
288
- sourceLogger.debug(`${noWrapTransforms.length} bare transforms found and applying`);
289
- apiSchema = utils.applySchemaTransforms(apiSchema, source, null, noWrapTransforms);
290
- }
291
- else {
292
- transforms = apiSource.transforms;
293
- }
294
- rawSources.push({
295
- name: apiName,
296
- schema: apiSchema,
297
- executor: source.executor,
298
- transforms,
299
- contextVariables: source.contextVariables || {},
300
- handler: apiSource.handler,
301
- batch: 'batch' in source ? source.batch : true,
302
- merge: apiSource.merge,
303
- });
304
- }
305
- catch (e) {
306
- sourceLogger.error(`Failed to generate the schema`, e);
307
- failed = true;
308
- }
309
- }));
310
- if (failed) {
311
- throw new Error(`Schemas couldn't be generated successfully. Check for the logs by running Mesh with DEBUG=1 environmental variable to get more verbose output.`);
312
- }
313
- getMeshLogger.debug(`Schemas have been generated by the source handlers`);
314
- getMeshLogger.debug(`Merging schemas using the defined merging strategy.`);
315
- const unifiedSubschema = await merger.getUnifiedSchema({
316
- rawSources,
317
- typeDefs: additionalTypeDefs,
318
- resolvers: additionalResolvers,
319
- });
320
- unifiedSubschema.transforms = unifiedSubschema.transforms || [];
321
- unifiedSubschema.transforms.push(...transforms);
322
- let inContextSDK$;
323
- const { plugin: subschemaPlugin, transformedSchema: finalSchema } = useSubschema(unifiedSubschema);
324
- finalSchema.extensions = unifiedSubschema.schema.extensions;
325
- const plugins = [
326
- subschemaPlugin,
327
- // TODO: Not a good practise to expect users to be a Yoga user
328
- core.useExtendContext(({ request, req }) => {
329
- // Maybe Node-like environment
330
- if (req === null || req === void 0 ? void 0 : req.headers) {
331
- return {
332
- headers: req.headers,
333
- };
334
- }
335
- // Fetch environment
336
- if (request === null || request === void 0 ? void 0 : request.headers) {
337
- return {
338
- headers: utils.getHeadersObj(request.headers),
339
- };
340
- }
341
- return {};
342
- }),
343
- core.useExtendContext(() => ({
344
- pubsub,
345
- cache,
346
- logger,
347
- [MESH_CONTEXT_SYMBOL]: true,
348
- })),
349
- core.useExtendContext(() => {
350
- if (!inContextSDK$) {
351
- inContextSDK$ = getInContextSDK(finalSchema, rawSources, logger);
352
- }
353
- return inContextSDK$;
354
- }),
355
- core.enableIf(!!finalSchema.getDirective('oneOf'), () => extendedValidation.useExtendedValidation({
356
- rules: [extendedValidation.OneOfInputObjectsRule],
357
- })),
358
- {
359
- onParse({ setParseFn }) {
360
- setParseFn(utils.parseWithCache);
361
- },
362
- },
363
- ...additionalEnvelopPlugins,
364
- ];
365
- const EMPTY_ROOT_VALUE = {};
366
- const EMPTY_CONTEXT_VALUE = {};
367
- const EMPTY_VARIABLES_VALUE = {};
368
- async function meshExecute(documentOrSDL, variableValues = EMPTY_VARIABLES_VALUE, contextValue = EMPTY_CONTEXT_VALUE, rootValue = EMPTY_ROOT_VALUE, operationName) {
369
- const getEnveloped = memoizedGetEnvelopedFactory(plugins);
370
- const { execute, contextFactory, parse } = getEnveloped(contextValue);
371
- return execute({
372
- document: typeof documentOrSDL === 'string' ? parse(documentOrSDL) : documentOrSDL,
373
- contextValue: await contextFactory(),
374
- rootValue,
375
- variableValues: variableValues,
376
- schema: unifiedSubschema.schema,
377
- operationName,
378
- });
379
- }
380
- async function meshSubscribe(documentOrSDL, variableValues = EMPTY_VARIABLES_VALUE, contextValue = EMPTY_CONTEXT_VALUE, rootValue = EMPTY_ROOT_VALUE, operationName) {
381
- const getEnveloped = memoizedGetEnvelopedFactory(plugins);
382
- const { subscribe, contextFactory, parse } = getEnveloped(contextValue);
383
- return subscribe({
384
- document: typeof documentOrSDL === 'string' ? parse(documentOrSDL) : documentOrSDL,
385
- contextValue: await contextFactory(),
386
- rootValue,
387
- variableValues: variableValues,
388
- schema: unifiedSubschema.schema,
389
- operationName,
390
- });
391
- }
392
- function sdkRequesterFactory(globalContext) {
393
- return async function meshSdkRequester(document, variables, contextValue) {
394
- const executeFn = memoizedGetOperationType(document) === 'subscription' ? meshSubscribe : meshExecute;
395
- const result = await executeFn(document, variables, {
396
- ...globalContext,
397
- ...contextValue,
398
- });
399
- if (utils$1.isAsyncIterable(result)) {
400
- return utils$1.mapAsyncIterator(result, extractDataOrThrowErrors);
401
- }
402
- return extractDataOrThrowErrors(result);
403
- };
404
- }
405
- return {
406
- execute: meshExecute,
407
- subscribe: meshSubscribe,
408
- schema: finalSchema,
409
- rawSources,
410
- cache,
411
- pubsub,
412
- destroy() {
413
- return pubsub.publish('destroy', undefined);
414
- },
415
- logger,
416
- plugins,
417
- get getEnveloped() {
418
- return memoizedGetEnvelopedFactory(plugins);
419
- },
420
- sdkRequesterFactory,
421
- };
422
- }
423
- function extractDataOrThrowErrors(result) {
424
- if (result.errors) {
425
- if (result.errors.length === 1) {
426
- throw result.errors[0];
427
- }
428
- throw new utils$1.AggregateError(result.errors);
429
- }
430
- return result.data;
431
- }
432
-
433
- exports.getMesh = getMesh;
434
- exports.useSubschema = useSubschema;