@graphql-codegen/plugin-helpers 2.5.0-alpha-252a8d50d.0 → 2.5.0-alpha-2fbcdb6d3.0

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,588 +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 module$1 = require('module');
8
- const process$1 = require('process');
9
- const changeCaseAll = require('change-case-all');
10
- const graphql = require('graphql');
11
- const merge = _interopDefault(require('lodash/merge.js'));
12
- const utils = require('@graphql-tools/utils');
13
-
14
- function resolveExternalModuleAndFn(pointer) {
15
- if (typeof pointer === 'function') {
16
- return pointer;
17
- }
18
- // eslint-disable-next-line prefer-const
19
- let [moduleName, functionName] = pointer.split('#');
20
- // Temp workaround until v2
21
- if (moduleName === 'change-case') {
22
- moduleName = 'change-case-all';
23
- }
24
- let loadedModule;
25
- if (moduleName === 'change-case-all') {
26
- loadedModule = changeCaseAll;
27
- }
28
- else {
29
- // we have to use a path to a filename here (it does not need to exist.)
30
- // https://github.com/dotansimha/graphql-code-generator/issues/6553
31
- const cwdRequire = module$1.createRequire(process$1.cwd() + '/index.js');
32
- loadedModule = cwdRequire(moduleName);
33
- if (!(functionName in loadedModule) && typeof loadedModule !== 'function') {
34
- throw new Error(`${functionName} couldn't be found in module ${moduleName}!`);
35
- }
36
- }
37
- return loadedModule[functionName] || loadedModule;
38
- }
39
-
40
- function isComplexPluginOutput(obj) {
41
- return typeof obj === 'object' && obj.hasOwnProperty('content');
42
- }
43
-
44
- function mergeOutputs(content) {
45
- const result = { content: '', prepend: [], append: [] };
46
- if (Array.isArray(content)) {
47
- content.forEach(item => {
48
- if (typeof item === 'string') {
49
- result.content += item;
50
- }
51
- else {
52
- result.content += item.content;
53
- result.prepend.push(...(item.prepend || []));
54
- result.append.push(...(item.append || []));
55
- }
56
- });
57
- }
58
- return [...result.prepend, result.content, ...result.append].join('\n');
59
- }
60
- function isWrapperType(t) {
61
- return graphql.isListType(t) || graphql.isNonNullType(t);
62
- }
63
- function getBaseType(type) {
64
- if (isWrapperType(type)) {
65
- return getBaseType(type.ofType);
66
- }
67
- else {
68
- return type;
69
- }
70
- }
71
- function removeNonNullWrapper(type) {
72
- return graphql.isNonNullType(type) ? type.ofType : type;
73
- }
74
-
75
- function isOutputConfigArray(type) {
76
- return Array.isArray(type);
77
- }
78
- function isConfiguredOutput(type) {
79
- return (typeof type === 'object' && type.plugins) || type.preset;
80
- }
81
- function normalizeOutputParam(config) {
82
- // In case of direct array with a list of plugins
83
- if (isOutputConfigArray(config)) {
84
- return {
85
- documents: [],
86
- schema: [],
87
- plugins: isConfiguredOutput(config) ? config.plugins : config,
88
- };
89
- }
90
- else if (isConfiguredOutput(config)) {
91
- return config;
92
- }
93
- else {
94
- throw new Error(`Invalid "generates" config!`);
95
- }
96
- }
97
- function normalizeInstanceOrArray(type) {
98
- if (Array.isArray(type)) {
99
- return type;
100
- }
101
- else if (!type) {
102
- return [];
103
- }
104
- return [type];
105
- }
106
- function normalizeConfig(config) {
107
- if (typeof config === 'string') {
108
- return [{ [config]: {} }];
109
- }
110
- else if (Array.isArray(config)) {
111
- return config.map(plugin => (typeof plugin === 'string' ? { [plugin]: {} } : plugin));
112
- }
113
- else if (typeof config === 'object') {
114
- return Object.keys(config).reduce((prev, pluginName) => [...prev, { [pluginName]: config[pluginName] }], []);
115
- }
116
- else {
117
- return [];
118
- }
119
- }
120
- function hasNullableTypeRecursively(type) {
121
- if (!graphql.isNonNullType(type)) {
122
- return true;
123
- }
124
- if (graphql.isListType(type) || graphql.isNonNullType(type)) {
125
- return hasNullableTypeRecursively(type.ofType);
126
- }
127
- return false;
128
- }
129
- function isUsingTypes(document, externalFragments, schema) {
130
- let foundFields = 0;
131
- const typesStack = [];
132
- graphql.visit(document, {
133
- SelectionSet: {
134
- enter(node, key, parent, anscestors) {
135
- const insideIgnoredFragment = anscestors.find((f) => f.kind && f.kind === 'FragmentDefinition' && externalFragments.includes(f.name.value));
136
- if (insideIgnoredFragment) {
137
- return;
138
- }
139
- const selections = node.selections || [];
140
- if (schema && selections.length > 0) {
141
- const nextTypeName = (() => {
142
- if (parent.kind === graphql.Kind.FRAGMENT_DEFINITION) {
143
- return parent.typeCondition.name.value;
144
- }
145
- else if (parent.kind === graphql.Kind.FIELD) {
146
- const lastType = typesStack[typesStack.length - 1];
147
- if (!lastType) {
148
- throw new Error(`Unable to find parent type! Please make sure you operation passes validation`);
149
- }
150
- const field = lastType.getFields()[parent.name.value];
151
- if (!field) {
152
- throw new Error(`Unable to find field "${parent.name.value}" on type "${lastType}"!`);
153
- }
154
- return getBaseType(field.type).name;
155
- }
156
- else if (parent.kind === graphql.Kind.OPERATION_DEFINITION) {
157
- if (parent.operation === 'query') {
158
- return schema.getQueryType().name;
159
- }
160
- else if (parent.operation === 'mutation') {
161
- return schema.getMutationType().name;
162
- }
163
- else if (parent.operation === 'subscription') {
164
- return schema.getSubscriptionType().name;
165
- }
166
- }
167
- else if (parent.kind === graphql.Kind.INLINE_FRAGMENT) {
168
- if (parent.typeCondition) {
169
- return parent.typeCondition.name.value;
170
- }
171
- else {
172
- return typesStack[typesStack.length - 1].name;
173
- }
174
- }
175
- return null;
176
- })();
177
- typesStack.push(schema.getType(nextTypeName));
178
- }
179
- },
180
- leave(node) {
181
- const selections = node.selections || [];
182
- if (schema && selections.length > 0) {
183
- typesStack.pop();
184
- }
185
- },
186
- },
187
- Field: {
188
- enter: (node, key, parent, path, anscestors) => {
189
- if (node.name.value.startsWith('__')) {
190
- return;
191
- }
192
- const insideIgnoredFragment = anscestors.find((f) => f.kind && f.kind === 'FragmentDefinition' && externalFragments.includes(f.name.value));
193
- if (insideIgnoredFragment) {
194
- return;
195
- }
196
- const selections = node.selectionSet ? node.selectionSet.selections || [] : [];
197
- const relevantFragmentSpreads = selections.filter(s => s.kind === graphql.Kind.FRAGMENT_SPREAD && !externalFragments.includes(s.name.value));
198
- if (selections.length === 0 || relevantFragmentSpreads.length > 0) {
199
- foundFields++;
200
- }
201
- if (schema) {
202
- const lastType = typesStack[typesStack.length - 1];
203
- if (lastType) {
204
- if (graphql.isObjectType(lastType)) {
205
- const field = lastType.getFields()[node.name.value];
206
- if (!field) {
207
- throw new Error(`Unable to find field "${node.name.value}" on type "${lastType}"!`);
208
- }
209
- const currentType = field.type;
210
- // To handle `Maybe` usage
211
- if (hasNullableTypeRecursively(currentType)) {
212
- foundFields++;
213
- }
214
- }
215
- }
216
- }
217
- },
218
- },
219
- VariableDefinition: {
220
- enter: (node, key, parent, path, anscestors) => {
221
- const insideIgnoredFragment = anscestors.find((f) => f.kind && f.kind === 'FragmentDefinition' && externalFragments.includes(f.name.value));
222
- if (insideIgnoredFragment) {
223
- return;
224
- }
225
- foundFields++;
226
- },
227
- },
228
- InputValueDefinition: {
229
- enter: (node, key, parent, path, anscestors) => {
230
- const insideIgnoredFragment = anscestors.find((f) => f.kind && f.kind === 'FragmentDefinition' && externalFragments.includes(f.name.value));
231
- if (insideIgnoredFragment) {
232
- return;
233
- }
234
- foundFields++;
235
- },
236
- },
237
- });
238
- return foundFields > 0;
239
- }
240
-
241
- /**
242
- * Federation Spec
243
- */
244
- const federationSpec = graphql.parse(/* GraphQL */ `
245
- scalar _FieldSet
246
-
247
- directive @external on FIELD_DEFINITION
248
- directive @requires(fields: _FieldSet!) on FIELD_DEFINITION
249
- directive @provides(fields: _FieldSet!) on FIELD_DEFINITION
250
- directive @key(fields: _FieldSet!) on OBJECT | INTERFACE
251
- `);
252
- /**
253
- * Adds `__resolveReference` in each ObjectType involved in Federation.
254
- * @param schema
255
- */
256
- function addFederationReferencesToSchema(schema) {
257
- return utils.mapSchema(schema, {
258
- [utils.MapperKind.OBJECT_TYPE]: type => {
259
- if (isFederationObjectType(type, schema)) {
260
- const typeConfig = type.toConfig();
261
- typeConfig.fields = {
262
- [resolveReferenceFieldName]: {
263
- type,
264
- },
265
- ...typeConfig.fields,
266
- };
267
- return new graphql.GraphQLObjectType(typeConfig);
268
- }
269
- return type;
270
- },
271
- });
272
- }
273
- /**
274
- * Removes Federation Spec from GraphQL Schema
275
- * @param schema
276
- * @param config
277
- */
278
- function removeFederation(schema) {
279
- return utils.mapSchema(schema, {
280
- [utils.MapperKind.QUERY]: queryType => {
281
- const queryTypeConfig = queryType.toConfig();
282
- delete queryTypeConfig.fields._entities;
283
- delete queryTypeConfig.fields._service;
284
- return new graphql.GraphQLObjectType(queryTypeConfig);
285
- },
286
- [utils.MapperKind.UNION_TYPE]: unionType => {
287
- const unionTypeName = unionType.name;
288
- if (unionTypeName === '_Entity' || unionTypeName === '_Any') {
289
- return null;
290
- }
291
- return unionType;
292
- },
293
- [utils.MapperKind.OBJECT_TYPE]: objectType => {
294
- if (objectType.name === '_Service') {
295
- return null;
296
- }
297
- return objectType;
298
- },
299
- });
300
- }
301
- const resolveReferenceFieldName = '__resolveReference';
302
- class ApolloFederation {
303
- constructor({ enabled, schema }) {
304
- this.enabled = false;
305
- this.enabled = enabled;
306
- this.schema = schema;
307
- this.providesMap = this.createMapOfProvides();
308
- }
309
- /**
310
- * Excludes types definde by Federation
311
- * @param typeNames List of type names
312
- */
313
- filterTypeNames(typeNames) {
314
- return this.enabled ? typeNames.filter(t => t !== '_FieldSet') : typeNames;
315
- }
316
- /**
317
- * Excludes `__resolveReference` fields
318
- * @param fieldNames List of field names
319
- */
320
- filterFieldNames(fieldNames) {
321
- return this.enabled ? fieldNames.filter(t => t !== resolveReferenceFieldName) : fieldNames;
322
- }
323
- /**
324
- * Decides if directive should not be generated
325
- * @param name directive's name
326
- */
327
- skipDirective(name) {
328
- return this.enabled && ['external', 'requires', 'provides', 'key'].includes(name);
329
- }
330
- /**
331
- * Decides if scalar should not be generated
332
- * @param name directive's name
333
- */
334
- skipScalar(name) {
335
- return this.enabled && name === '_FieldSet';
336
- }
337
- /**
338
- * Decides if field should not be generated
339
- * @param data
340
- */
341
- skipField({ fieldNode, parentType }) {
342
- if (!this.enabled || !graphql.isObjectType(parentType) || !isFederationObjectType(parentType, this.schema)) {
343
- return false;
344
- }
345
- return this.isExternalAndNotProvided(fieldNode, parentType);
346
- }
347
- isResolveReferenceField(fieldNode) {
348
- const name = typeof fieldNode.name === 'string' ? fieldNode.name : fieldNode.name.value;
349
- return this.enabled && name === resolveReferenceFieldName;
350
- }
351
- /**
352
- * Transforms ParentType signature in ObjectTypes involved in Federation
353
- * @param data
354
- */
355
- transformParentType({ fieldNode, parentType, parentTypeSignature, }) {
356
- if (this.enabled &&
357
- graphql.isObjectType(parentType) &&
358
- isFederationObjectType(parentType, this.schema) &&
359
- (isTypeExtension(parentType, this.schema) || fieldNode.name.value === resolveReferenceFieldName)) {
360
- const keys = getDirectivesByName('key', parentType);
361
- if (keys.length) {
362
- const outputs = [`{ __typename: '${parentType.name}' } &`];
363
- // Look for @requires and see what the service needs and gets
364
- const requires = getDirectivesByName('requires', fieldNode).map(this.extractKeyOrRequiresFieldSet);
365
- const requiredFields = this.translateFieldSet(merge({}, ...requires), parentTypeSignature);
366
- // @key() @key() - "primary keys" in Federation
367
- const primaryKeys = keys.map(def => {
368
- const fields = this.extractKeyOrRequiresFieldSet(def);
369
- return this.translateFieldSet(fields, parentTypeSignature);
370
- });
371
- const [open, close] = primaryKeys.length > 1 ? ['(', ')'] : ['', ''];
372
- outputs.push([open, primaryKeys.join(' | '), close].join(''));
373
- // include required fields
374
- if (requires.length) {
375
- outputs.push(`& ${requiredFields}`);
376
- }
377
- return outputs.join(' ');
378
- }
379
- }
380
- return parentTypeSignature;
381
- }
382
- isExternalAndNotProvided(fieldNode, objectType) {
383
- return this.isExternal(fieldNode) && !this.hasProvides(objectType, fieldNode);
384
- }
385
- isExternal(node) {
386
- return getDirectivesByName('external', node).length > 0;
387
- }
388
- hasProvides(objectType, node) {
389
- const fields = this.providesMap[graphql.isObjectType(objectType) ? objectType.name : objectType.name.value];
390
- if (fields && fields.length) {
391
- return fields.includes(node.name.value);
392
- }
393
- return false;
394
- }
395
- translateFieldSet(fields, parentTypeRef) {
396
- return `GraphQLRecursivePick<${parentTypeRef}, ${JSON.stringify(fields)}>`;
397
- }
398
- extractKeyOrRequiresFieldSet(directive) {
399
- const arg = directive.arguments.find(arg => arg.name.value === 'fields');
400
- const value = arg.value.value;
401
- return oldVisit(graphql.parse(`{${value}}`), {
402
- leave: {
403
- SelectionSet(node) {
404
- return node.selections.reduce((accum, field) => {
405
- accum[field.name] = field.selection;
406
- return accum;
407
- }, {});
408
- },
409
- Field(node) {
410
- return {
411
- name: node.name.value,
412
- selection: node.selectionSet ? node.selectionSet : true,
413
- };
414
- },
415
- Document(node) {
416
- return node.definitions.find((def) => def.kind === 'OperationDefinition' && def.operation === 'query').selectionSet;
417
- },
418
- },
419
- });
420
- }
421
- extractProvidesFieldSet(directive) {
422
- const arg = directive.arguments.find(arg => arg.name.value === 'fields');
423
- const value = arg.value.value;
424
- if (/[{}]/gi.test(value)) {
425
- throw new Error('Nested fields in _FieldSet is not supported in the @provides directive');
426
- }
427
- return value.split(/\s+/g);
428
- }
429
- createMapOfProvides() {
430
- const providesMap = {};
431
- Object.keys(this.schema.getTypeMap()).forEach(typename => {
432
- const objectType = this.schema.getType(typename);
433
- if (graphql.isObjectType(objectType)) {
434
- Object.values(objectType.getFields()).forEach(field => {
435
- const provides = getDirectivesByName('provides', field.astNode)
436
- .map(this.extractProvidesFieldSet)
437
- .reduce((prev, curr) => [...prev, ...curr], []);
438
- const ofType = getBaseType(field.type);
439
- if (!providesMap[ofType.name]) {
440
- providesMap[ofType.name] = [];
441
- }
442
- providesMap[ofType.name].push(...provides);
443
- });
444
- }
445
- });
446
- return providesMap;
447
- }
448
- }
449
- /**
450
- * Checks if Object Type is involved in Federation. Based on `@key` directive
451
- * @param node Type
452
- */
453
- function isFederationObjectType(node, schema) {
454
- const { name: { value: name }, directives, } = graphql.isObjectType(node) ? utils.astFromObjectType(node, schema) : node;
455
- const rootTypeNames = utils.getRootTypeNames(schema);
456
- const isNotRoot = !rootTypeNames.has(name);
457
- const isNotIntrospection = !name.startsWith('__');
458
- const hasKeyDirective = directives.some(d => d.name.value === 'key');
459
- return isNotRoot && isNotIntrospection && hasKeyDirective;
460
- }
461
- /**
462
- * Extracts directives from a node based on directive's name
463
- * @param name directive name
464
- * @param node ObjectType or Field
465
- */
466
- function getDirectivesByName(name, node) {
467
- var _a;
468
- let astNode;
469
- if (graphql.isObjectType(node)) {
470
- astNode = node.astNode;
471
- }
472
- else {
473
- astNode = node;
474
- }
475
- return ((_a = astNode === null || astNode === void 0 ? void 0 : astNode.directives) === null || _a === void 0 ? void 0 : _a.filter(d => d.name.value === name)) || [];
476
- }
477
- /**
478
- * Checks if the Object Type extends a federated type from a remote schema.
479
- * Based on if any of its fields contain the `@external` directive
480
- * @param node Type
481
- */
482
- function isTypeExtension(node, schema) {
483
- var _a;
484
- const definition = graphql.isObjectType(node) ? node.astNode || utils.astFromObjectType(node, schema) : node;
485
- return (_a = definition.fields) === null || _a === void 0 ? void 0 : _a.some(field => getDirectivesByName('external', field).length);
486
- }
487
-
488
- class DetailedError extends Error {
489
- constructor(message, details, source) {
490
- super(message);
491
- this.message = message;
492
- this.details = details;
493
- this.source = source;
494
- Object.setPrototypeOf(this, DetailedError.prototype);
495
- Error.captureStackTrace(this, DetailedError);
496
- }
497
- }
498
- function isDetailedError(error) {
499
- return error.details;
500
- }
501
-
502
- const getCachedDocumentNodeFromSchema = utils.memoize1(utils.getDocumentNodeFromSchema);
503
-
504
- function oldVisit(root, { enter: enterVisitors, leave: leaveVisitors, ...newVisitor }) {
505
- if (typeof enterVisitors === 'object') {
506
- for (const key in enterVisitors) {
507
- newVisitor[key] = newVisitor[key] || {};
508
- newVisitor[key].enter = enterVisitors[key];
509
- }
510
- }
511
- if (typeof leaveVisitors === 'object') {
512
- for (const key in leaveVisitors) {
513
- newVisitor[key] = newVisitor[key] || {};
514
- newVisitor[key].leave = leaveVisitors[key];
515
- }
516
- }
517
- return graphql.visit(root, newVisitor);
518
- }
519
-
520
- function createNoopProfiler() {
521
- return {
522
- run(fn) {
523
- return Promise.resolve().then(() => fn());
524
- },
525
- collect() {
526
- return [];
527
- },
528
- };
529
- }
530
- function createProfiler() {
531
- const events = [];
532
- return {
533
- collect() {
534
- return events;
535
- },
536
- run(fn, name, cat) {
537
- let startTime;
538
- return Promise.resolve()
539
- .then(() => {
540
- startTime = process.hrtime();
541
- })
542
- .then(() => fn())
543
- .then(value => {
544
- const duration = process.hrtime(startTime);
545
- // Trace Event Format documentation:
546
- // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
547
- const event = {
548
- name,
549
- cat,
550
- ph: 'X',
551
- ts: hrtimeToMicroseconds(startTime),
552
- pid: 1,
553
- tid: 0,
554
- dur: hrtimeToMicroseconds(duration),
555
- };
556
- events.push(event);
557
- return value;
558
- });
559
- },
560
- };
561
- }
562
- function hrtimeToMicroseconds(hrtime) {
563
- return (hrtime[0] * 1e9 + hrtime[1]) / 1000;
564
- }
565
-
566
- exports.ApolloFederation = ApolloFederation;
567
- exports.DetailedError = DetailedError;
568
- exports.addFederationReferencesToSchema = addFederationReferencesToSchema;
569
- exports.createNoopProfiler = createNoopProfiler;
570
- exports.createProfiler = createProfiler;
571
- exports.federationSpec = federationSpec;
572
- exports.getBaseType = getBaseType;
573
- exports.getCachedDocumentNodeFromSchema = getCachedDocumentNodeFromSchema;
574
- exports.hasNullableTypeRecursively = hasNullableTypeRecursively;
575
- exports.isComplexPluginOutput = isComplexPluginOutput;
576
- exports.isConfiguredOutput = isConfiguredOutput;
577
- exports.isDetailedError = isDetailedError;
578
- exports.isOutputConfigArray = isOutputConfigArray;
579
- exports.isUsingTypes = isUsingTypes;
580
- exports.isWrapperType = isWrapperType;
581
- exports.mergeOutputs = mergeOutputs;
582
- exports.normalizeConfig = normalizeConfig;
583
- exports.normalizeInstanceOrArray = normalizeInstanceOrArray;
584
- exports.normalizeOutputParam = normalizeOutputParam;
585
- exports.oldVisit = oldVisit;
586
- exports.removeFederation = removeFederation;
587
- exports.removeNonNullWrapper = removeNonNullWrapper;
588
- exports.resolveExternalModuleAndFn = resolveExternalModuleAndFn;