@omnigraph/mongo 0.0.0-stage → 0.1.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.
@@ -0,0 +1,759 @@
1
+ import { GraphQLFloat, GraphQLID, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLString, } from 'graphql';
2
+ import { SchemaComposer } from 'graphql-compose';
3
+ import { GraphQLDateTime, GraphQLJSON, GraphQLObjectID } from 'graphql-scalars';
4
+ import { process as meshProcess } from '@graphql-mesh/cross-helpers';
5
+ import { defaultImportFn, loadFromModuleExportExpression } from '@graphql-mesh/utils';
6
+ import { MongoDirective, MongoKindEnum, TransportDirective } from './directives.js';
7
+ import { createDefaultNaming } from './naming.js';
8
+ import { mapMongoPathToGraphQL } from './type-map.js';
9
+ const FEDERATION_LINK_URL = 'https://specs.apollo.dev/federation/v2.6';
10
+ export async function loadGraphQLSchemaFromMongo(subgraphName, opts) {
11
+ const naming = { ...createDefaultNaming(), ...opts.naming };
12
+ const cwd = opts.cwd || meshProcess.cwd();
13
+ const importFn = opts.importFn || defaultImportFn;
14
+ const schemaComposer = new SchemaComposer();
15
+ schemaComposer.add(GraphQLObjectID);
16
+ schemaComposer.add(GraphQLDateTime);
17
+ schemaComposer.add(GraphQLJSON);
18
+ schemaComposer.addDirective(TransportDirective);
19
+ schemaComposer.addDirective(MongoDirective);
20
+ schemaComposer.add(MongoKindEnum);
21
+ ensureSharedFilterInputs(schemaComposer);
22
+ ensurePageInfo(schemaComposer);
23
+ const modelMeta = [];
24
+ for (const modelConfig of opts.models) {
25
+ const model = await resolveModel(modelConfig, cwd, importFn);
26
+ const collection = modelConfig.collection ||
27
+ model.collection?.collectionName ||
28
+ model.schema?.get('collection') ||
29
+ pluralizeFallback(modelConfig.name);
30
+ const typeName = naming.typeName(modelConfig.name);
31
+ const paths = introspectPaths(model.schema);
32
+ modelMeta.push({ typeName, collection, schema: model.schema, paths });
33
+ emitModelObjectType(schemaComposer, {
34
+ subgraphName,
35
+ typeName,
36
+ collection,
37
+ paths,
38
+ naming,
39
+ });
40
+ }
41
+ for (const meta of modelMeta) {
42
+ emitModelRootFields(schemaComposer, {
43
+ subgraphName,
44
+ typeName: meta.typeName,
45
+ collection: meta.collection,
46
+ paths: meta.paths,
47
+ naming,
48
+ });
49
+ emitRefFields(schemaComposer, {
50
+ subgraphName,
51
+ typeName: meta.typeName,
52
+ schema: meta.schema,
53
+ naming,
54
+ knownTypes: new Set(modelMeta.map(m => m.typeName)),
55
+ collectionsByType: new Map(modelMeta.map(m => [m.typeName, m.collection])),
56
+ });
57
+ }
58
+ const schema = schemaComposer.buildSchema();
59
+ const extensions = (schema.extensions ||= {});
60
+ extensions.directives ||= {};
61
+ extensions.directives.transport = {
62
+ subgraph: subgraphName,
63
+ kind: 'mongo',
64
+ location: opts.endpoint,
65
+ };
66
+ extensions.directives.link = [
67
+ {
68
+ url: FEDERATION_LINK_URL,
69
+ import: ['@key'],
70
+ },
71
+ ];
72
+ markMongoDirectiveStringsAsBlocks(schema);
73
+ return schema;
74
+ }
75
+ async function resolveModel(config, cwd, importFn) {
76
+ if (config.model)
77
+ return config.model;
78
+ if (config.schema) {
79
+ return {
80
+ schema: config.schema,
81
+ collection: { collectionName: config.collection || pluralizeFallback(config.name) },
82
+ };
83
+ }
84
+ if (!config.path) {
85
+ throw new Error(`Model ${config.name} needs path, model, or schema`);
86
+ }
87
+ const model = await loadFromModuleExportExpression(config.path, {
88
+ defaultExportName: config.name,
89
+ cwd,
90
+ importFn,
91
+ });
92
+ if (!model) {
93
+ throw new Error(`Model ${config.name} cannot be imported from ${config.path}`);
94
+ }
95
+ return model;
96
+ }
97
+ function introspectPaths(schema) {
98
+ const out = [];
99
+ const paths = schema.paths || {};
100
+ for (const [name, schemaType] of Object.entries(paths)) {
101
+ const instance = schemaType.instance || schemaType.constructor?.name || 'Mixed';
102
+ const enumValues = schemaType.enumValues || schemaType.options?.enum;
103
+ const ref = schemaType.options?.ref ||
104
+ schemaType.caster?.options?.ref ||
105
+ schemaType.schema?.options?.ref;
106
+ out.push({
107
+ name,
108
+ instance: String(instance),
109
+ isArray: instance === 'Array' || Array.isArray(schemaType.options?.type),
110
+ enumValues: Array.isArray(enumValues) ? enumValues.map(String) : undefined,
111
+ ref: ref ? String(ref) : undefined,
112
+ });
113
+ }
114
+ return out;
115
+ }
116
+ function selectionForPaths(paths) {
117
+ const lines = ['id: _id'];
118
+ for (const path of paths) {
119
+ if (path.name === '_id' || path.name === '__v' || path.name.includes('.'))
120
+ continue;
121
+ if (path.ref) {
122
+ // Scalar id field kept; populated object is a sibling field.
123
+ lines.push(`${path.name}: ${path.name}`);
124
+ continue;
125
+ }
126
+ lines.push(`${path.name}: ${path.name}`);
127
+ }
128
+ return blockArg(lines.join('\n'));
129
+ }
130
+ function emitModelObjectType(schemaComposer, opts) {
131
+ const { subgraphName, typeName, collection, paths, naming } = opts;
132
+ const otc = schemaComposer.createObjectTC({ name: typeName, fields: {} });
133
+ const selection = selectionForPaths(paths);
134
+ otc.setField('id', { type: new GraphQLNonNull(GraphQLID) });
135
+ for (const path of paths) {
136
+ if (path.name === '_id' || path.name === '__v' || path.name.includes('.'))
137
+ continue;
138
+ otc.setField(path.name, { type: mapPathToOutput(path) });
139
+ }
140
+ otc.setDirectives([
141
+ { name: 'key', args: { fields: 'id' } },
142
+ {
143
+ name: 'mongo',
144
+ args: {
145
+ subgraph: subgraphName,
146
+ collection,
147
+ kind: 'FIND_ONE',
148
+ filter: blockArg('_id: $this.id'),
149
+ selection,
150
+ },
151
+ },
152
+ ]);
153
+ createFilterSortAndInputs(schemaComposer, naming, typeName, paths);
154
+ createConnectionTypes(schemaComposer, naming, typeName);
155
+ createPayloadType(schemaComposer, naming, typeName);
156
+ }
157
+ function emitModelRootFields(schemaComposer, opts) {
158
+ const { subgraphName, typeName, collection, paths, naming } = opts;
159
+ const selection = selectionForPaths(paths);
160
+ const filterType = naming.filterInput(typeName);
161
+ const sortType = naming.sortInput(typeName);
162
+ const queryTC = schemaComposer.Query;
163
+ const mutationTC = schemaComposer.Mutation;
164
+ const mongo = (kind, extra = {}) => ({
165
+ name: 'mongo',
166
+ args: { subgraph: subgraphName, collection, kind, selection, ...extra },
167
+ });
168
+ queryTC.setField(naming.findByIdField(typeName), {
169
+ type: typeName,
170
+ args: { _id: { type: new GraphQLNonNull(GraphQLID) } },
171
+ directives: [mongo('FIND_ONE', { filter: blockArg('_id: $args._id') })],
172
+ });
173
+ queryTC.setField(naming.dataLoaderField(typeName), {
174
+ type: typeName,
175
+ args: { _id: { type: new GraphQLNonNull(GraphQLID) } },
176
+ directives: [mongo('FIND_ONE', { filter: blockArg('_id: $args._id') })],
177
+ });
178
+ queryTC.setField(naming.findByIdsField(typeName), {
179
+ type: `[${typeName}!]!`,
180
+ args: {
181
+ _ids: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID))) },
182
+ limit: { type: GraphQLInt, defaultValue: 100 },
183
+ sort: { type: sortType },
184
+ },
185
+ directives: [
186
+ mongo('FIND_MANY', {
187
+ filter: blockArg('_id: $args._ids'),
188
+ limit: '$args.limit',
189
+ sort: '$args.sort',
190
+ }),
191
+ ],
192
+ });
193
+ queryTC.setField(naming.dataLoaderManyField(typeName), {
194
+ type: `[${typeName}]!`,
195
+ args: {
196
+ _ids: { type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(GraphQLID))) },
197
+ },
198
+ directives: [mongo('FIND_MANY', { filter: blockArg('_id: $args._ids') })],
199
+ });
200
+ queryTC.setField(naming.findManyField(typeName), {
201
+ type: `[${typeName}!]!`,
202
+ args: {
203
+ filter: { type: filterType },
204
+ limit: { type: GraphQLInt, defaultValue: 100 },
205
+ skip: { type: GraphQLInt },
206
+ sort: { type: sortType },
207
+ },
208
+ directives: [
209
+ mongo('FIND_MANY', {
210
+ filter: '$args.filter',
211
+ sort: '$args.sort',
212
+ limit: '$args.limit',
213
+ skip: '$args.skip',
214
+ }),
215
+ ],
216
+ });
217
+ queryTC.setField(naming.findOneField(typeName), {
218
+ type: typeName,
219
+ args: {
220
+ filter: { type: filterType },
221
+ skip: { type: GraphQLInt },
222
+ sort: { type: sortType },
223
+ },
224
+ directives: [
225
+ mongo('FIND_ONE', {
226
+ filter: '$args.filter',
227
+ sort: '$args.sort',
228
+ skip: '$args.skip',
229
+ }),
230
+ ],
231
+ });
232
+ queryTC.setField(naming.countField(typeName), {
233
+ type: new GraphQLNonNull(GraphQLInt),
234
+ args: { filter: { type: filterType } },
235
+ directives: [mongo('COUNT', { filter: '$args.filter', selection: blockArg('$') })],
236
+ });
237
+ queryTC.setField(naming.connectionField(typeName), {
238
+ type: naming.connectionType(typeName),
239
+ args: {
240
+ filter: { type: filterType },
241
+ first: { type: GraphQLInt },
242
+ after: { type: GraphQLString },
243
+ sort: { type: sortType },
244
+ },
245
+ directives: [
246
+ mongo('CONNECTION', {
247
+ filter: '$args.filter',
248
+ sort: '$args.sort',
249
+ first: '$args.first',
250
+ after: '$args.after',
251
+ selection: blockArg(`
252
+ nodes {
253
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 1)}
254
+ }
255
+ edges {
256
+ cursor: $cursor
257
+ node {
258
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 2)}
259
+ }
260
+ }
261
+ pageInfo {
262
+ hasNextPage: $hasNextPage
263
+ hasPreviousPage: $hasPreviousPage
264
+ startCursor: $startCursor
265
+ endCursor: $endCursor
266
+ }
267
+ totalCount: $totalCount
268
+ `),
269
+ }),
270
+ ],
271
+ });
272
+ queryTC.setField(naming.paginationField(typeName), {
273
+ type: naming.paginationType(typeName),
274
+ args: {
275
+ filter: { type: filterType },
276
+ page: { type: GraphQLInt },
277
+ perPage: { type: GraphQLInt, defaultValue: 20 },
278
+ sort: { type: sortType },
279
+ },
280
+ directives: [
281
+ mongo('PAGINATION', {
282
+ filter: '$args.filter',
283
+ sort: '$args.sort',
284
+ page: '$args.page',
285
+ perPage: '$args.perPage',
286
+ selection: blockArg(`
287
+ count: $count
288
+ items {
289
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 1)}
290
+ }
291
+ pageInfo {
292
+ currentPage: $currentPage
293
+ perPage: $perPage
294
+ pageCount: $pageCount
295
+ itemCount: $itemCount
296
+ hasNextPage: $hasNextPage
297
+ hasPreviousPage: $hasPreviousPage
298
+ }
299
+ `),
300
+ }),
301
+ ],
302
+ });
303
+ const setBlock = blockArg(paths
304
+ .filter(p => p.name !== '_id' && p.name !== '__v' && !p.name.includes('.'))
305
+ .map(p => `${p.name}: $args.record.${p.name}`)
306
+ .join('\n'));
307
+ const payloadSelection = blockArg(`
308
+ record {
309
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 1)}
310
+ }
311
+ recordId: $_id
312
+ `);
313
+ mutationTC.setField(naming.createOneField(typeName), {
314
+ type: naming.payloadType(typeName),
315
+ args: { record: { type: `${naming.createInput(typeName)}!` } },
316
+ directives: [mongo('INSERT_ONE', { set: setBlock, selection: payloadSelection })],
317
+ });
318
+ mutationTC.setField(naming.createManyField(typeName), {
319
+ type: naming.payloadType(typeName),
320
+ args: { records: { type: `[${naming.createInput(typeName)}!]!` } },
321
+ directives: [
322
+ mongo('INSERT_MANY', {
323
+ set: blockArg('records: $args.records'),
324
+ selection: blockArg(`
325
+ records {
326
+ ${indent(selectionForPaths(paths).replace(/^\n/, ''), 1)}
327
+ }
328
+ recordIds: $recordIds
329
+ createdCount: $createdCount
330
+ `),
331
+ }),
332
+ ],
333
+ });
334
+ mutationTC.setField(naming.updateByIdField(typeName), {
335
+ type: naming.payloadType(typeName),
336
+ args: {
337
+ _id: { type: new GraphQLNonNull(GraphQLID) },
338
+ record: { type: `${naming.updateInput(typeName)}!` },
339
+ },
340
+ directives: [
341
+ mongo('UPDATE_ONE', {
342
+ filter: blockArg('_id: $args._id'),
343
+ set: setBlock,
344
+ selection: payloadSelection,
345
+ }),
346
+ ],
347
+ });
348
+ mutationTC.setField(naming.updateOneField(typeName), {
349
+ type: naming.payloadType(typeName),
350
+ args: {
351
+ filter: { type: filterType },
352
+ record: { type: `${naming.updateInput(typeName)}!` },
353
+ },
354
+ directives: [
355
+ mongo('UPDATE_ONE', {
356
+ filter: '$args.filter',
357
+ set: setBlock,
358
+ selection: payloadSelection,
359
+ }),
360
+ ],
361
+ });
362
+ mutationTC.setField(naming.updateManyField(typeName), {
363
+ type: naming.payloadType(typeName),
364
+ args: {
365
+ filter: { type: filterType },
366
+ record: { type: `${naming.updateInput(typeName)}!` },
367
+ },
368
+ directives: [
369
+ mongo('UPDATE_MANY', {
370
+ filter: '$args.filter',
371
+ set: setBlock,
372
+ selection: blockArg(`
373
+ modifiedCount: $modifiedCount
374
+ matchedCount: $matchedCount
375
+ `),
376
+ }),
377
+ ],
378
+ });
379
+ mutationTC.setField(naming.removeByIdField(typeName), {
380
+ type: naming.payloadType(typeName),
381
+ args: { _id: { type: new GraphQLNonNull(GraphQLID) } },
382
+ directives: [
383
+ mongo('DELETE_ONE', {
384
+ filter: blockArg('_id: $args._id'),
385
+ selection: payloadSelection,
386
+ }),
387
+ ],
388
+ });
389
+ mutationTC.setField(naming.removeOneField(typeName), {
390
+ type: naming.payloadType(typeName),
391
+ args: { filter: { type: filterType } },
392
+ directives: [
393
+ mongo('DELETE_ONE', {
394
+ filter: '$args.filter',
395
+ selection: payloadSelection,
396
+ }),
397
+ ],
398
+ });
399
+ mutationTC.setField(naming.removeManyField(typeName), {
400
+ type: naming.payloadType(typeName),
401
+ args: { filter: { type: `${filterType}!` } },
402
+ directives: [
403
+ mongo('DELETE_MANY', {
404
+ filter: '$args.filter',
405
+ selection: blockArg('deletedCount: $deletedCount'),
406
+ }),
407
+ ],
408
+ });
409
+ }
410
+ function emitRefFields(schemaComposer, opts) {
411
+ const paths = introspectPaths(opts.schema);
412
+ const otc = schemaComposer.getOTC(opts.typeName);
413
+ for (const path of paths) {
414
+ if (!path.ref || !opts.knownTypes.has(path.ref))
415
+ continue;
416
+ const refCollection = opts.collectionsByType.get(path.ref);
417
+ if (!refCollection)
418
+ continue;
419
+ const refPaths = introspectPaths(
420
+ // best-effort: empty selection of id only if we cannot re-introspect
421
+ opts.schema);
422
+ void refPaths;
423
+ const fieldName = path.isArray ? pluralizeFallback(path.ref) : path.ref[0].toLowerCase() + path.ref.slice(1);
424
+ // Prefer path name without Id suffix when present (authorId -> author)
425
+ const pretty = path.name.endsWith('Id') || path.name.endsWith('Ids')
426
+ ? path.name.replace(/Ids?$/, '')
427
+ : path.name + 'Doc';
428
+ const finalName = otc.hasField(pretty) ? fieldName : pretty;
429
+ if (otc.hasField(finalName) && finalName !== path.name) {
430
+ // already set
431
+ }
432
+ const refSelection = blockArg('id: _id');
433
+ if (path.isArray) {
434
+ otc.setField(finalName, {
435
+ type: `[${path.ref}!]!`,
436
+ directives: [
437
+ {
438
+ name: 'mongo',
439
+ args: {
440
+ subgraph: opts.subgraphName,
441
+ collection: refCollection,
442
+ kind: 'FIND_MANY',
443
+ filter: blockArg(`_id: $this.${path.name}`),
444
+ selection: refSelection,
445
+ },
446
+ },
447
+ ],
448
+ });
449
+ }
450
+ else {
451
+ otc.setField(finalName, {
452
+ type: path.ref,
453
+ directives: [
454
+ {
455
+ name: 'mongo',
456
+ args: {
457
+ subgraph: opts.subgraphName,
458
+ collection: refCollection,
459
+ kind: 'FIND_ONE',
460
+ filter: blockArg(`_id: $this.${path.name}`),
461
+ selection: refSelection,
462
+ },
463
+ },
464
+ ],
465
+ });
466
+ }
467
+ }
468
+ }
469
+ function mapPathToOutput(path) {
470
+ if (path.enumValues?.length) {
471
+ return path.isArray ? new GraphQLList(GraphQLString) : GraphQLString;
472
+ }
473
+ if (path.ref) {
474
+ const idType = GraphQLID;
475
+ return path.isArray ? new GraphQLList(idType) : idType;
476
+ }
477
+ if (path.isArray && path.instance !== 'Array') {
478
+ return new GraphQLList(mapMongoPathToGraphQL(path.instance));
479
+ }
480
+ return mapMongoPathToGraphQL(path.instance, { asId: path.name === '_id' });
481
+ }
482
+ function createFilterSortAndInputs(schemaComposer, naming, typeName, paths) {
483
+ const filterName = naming.filterInput(typeName);
484
+ if (!schemaComposer.has(filterName)) {
485
+ schemaComposer.createInputTC({
486
+ name: filterName,
487
+ fields: {
488
+ AND: { type: `[${filterName}!]` },
489
+ OR: { type: `[${filterName}!]` },
490
+ NOT: { type: filterName },
491
+ id: { type: 'IDFilter' },
492
+ ...Object.fromEntries(paths
493
+ .filter(p => p.name !== '_id' && p.name !== '__v' && !p.name.includes('.'))
494
+ .map(p => {
495
+ let filterType = 'StringFilter';
496
+ if (p.instance === 'Number' || p.instance === 'Decimal128')
497
+ filterType = 'FloatFilter';
498
+ else if (p.instance === 'Boolean')
499
+ filterType = 'BooleanFilter';
500
+ else if (p.instance === 'Date')
501
+ filterType = 'DateTimeFilter';
502
+ else if (p.ref || p.instance === 'ObjectID' || p.instance === 'ObjectId')
503
+ filterType = 'IDFilter';
504
+ return [p.name, { type: filterType }];
505
+ })),
506
+ },
507
+ });
508
+ }
509
+ if (!schemaComposer.has(naming.sortInput(typeName))) {
510
+ if (!schemaComposer.has('SortDirection')) {
511
+ schemaComposer.createEnumTC({
512
+ name: 'SortDirection',
513
+ values: { ASC: { value: 'ASC' }, DESC: { value: 'DESC' } },
514
+ });
515
+ }
516
+ schemaComposer.createInputTC({
517
+ name: naming.sortInput(typeName),
518
+ fields: {
519
+ id: 'SortDirection',
520
+ ...Object.fromEntries(paths
521
+ .filter(p => p.name !== '_id' && p.name !== '__v' && !p.name.includes('.'))
522
+ .map(p => [p.name, { type: 'SortDirection' }])),
523
+ },
524
+ });
525
+ }
526
+ const createFields = {};
527
+ const updateFields = {};
528
+ for (const path of paths) {
529
+ if (path.name === '_id' || path.name === '__v' || path.name.includes('.'))
530
+ continue;
531
+ const gqlType = mapPathToOutput(path);
532
+ createFields[path.name] = { type: gqlType };
533
+ updateFields[path.name] = { type: gqlType };
534
+ }
535
+ if (!schemaComposer.has(naming.createInput(typeName))) {
536
+ schemaComposer.createInputTC({ name: naming.createInput(typeName), fields: createFields });
537
+ }
538
+ if (!schemaComposer.has(naming.updateInput(typeName))) {
539
+ schemaComposer.createInputTC({ name: naming.updateInput(typeName), fields: updateFields });
540
+ }
541
+ }
542
+ function createConnectionTypes(schemaComposer, naming, typeName) {
543
+ if (!schemaComposer.has(naming.edgeType(typeName))) {
544
+ schemaComposer.createObjectTC({
545
+ name: naming.edgeType(typeName),
546
+ fields: { cursor: 'String!', node: `${typeName}!` },
547
+ });
548
+ }
549
+ if (!schemaComposer.has(naming.connectionType(typeName))) {
550
+ schemaComposer.createObjectTC({
551
+ name: naming.connectionType(typeName),
552
+ fields: {
553
+ edges: `[${naming.edgeType(typeName)}!]!`,
554
+ nodes: `[${typeName}!]!`,
555
+ pageInfo: 'PageInfo!',
556
+ totalCount: 'Int!',
557
+ },
558
+ });
559
+ }
560
+ if (!schemaComposer.has(naming.paginationType(typeName))) {
561
+ schemaComposer.createObjectTC({
562
+ name: naming.paginationType(typeName),
563
+ fields: {
564
+ count: 'Int',
565
+ items: `[${typeName}]`,
566
+ pageInfo: 'PaginationInfo',
567
+ },
568
+ });
569
+ }
570
+ }
571
+ function createPayloadType(schemaComposer, naming, typeName) {
572
+ if (!schemaComposer.has(naming.payloadType(typeName))) {
573
+ schemaComposer.createObjectTC({
574
+ name: naming.payloadType(typeName),
575
+ fields: {
576
+ record: typeName,
577
+ recordId: GraphQLID,
578
+ records: `[${typeName}!]`,
579
+ recordIds: '[ID!]',
580
+ createdCount: GraphQLInt,
581
+ modifiedCount: GraphQLInt,
582
+ matchedCount: GraphQLInt,
583
+ deletedCount: GraphQLInt,
584
+ },
585
+ });
586
+ }
587
+ }
588
+ function ensurePageInfo(schemaComposer) {
589
+ if (!schemaComposer.has('PageInfo')) {
590
+ schemaComposer.createObjectTC({
591
+ name: 'PageInfo',
592
+ fields: {
593
+ hasNextPage: 'Boolean!',
594
+ hasPreviousPage: 'Boolean!',
595
+ startCursor: 'String',
596
+ endCursor: 'String',
597
+ },
598
+ });
599
+ }
600
+ if (!schemaComposer.has('PaginationInfo')) {
601
+ schemaComposer.createObjectTC({
602
+ name: 'PaginationInfo',
603
+ fields: {
604
+ currentPage: 'Int!',
605
+ perPage: 'Int!',
606
+ pageCount: 'Int',
607
+ itemCount: 'Int',
608
+ hasNextPage: 'Boolean',
609
+ hasPreviousPage: 'Boolean',
610
+ },
611
+ });
612
+ }
613
+ }
614
+ function ensureSharedFilterInputs(schemaComposer) {
615
+ if (!schemaComposer.has('IDFilter')) {
616
+ schemaComposer.createInputTC({
617
+ name: 'IDFilter',
618
+ fields: {
619
+ eq: GraphQLID,
620
+ ne: GraphQLID,
621
+ in: { type: new GraphQLList(new GraphQLNonNull(GraphQLID)) },
622
+ nin: { type: new GraphQLList(new GraphQLNonNull(GraphQLID)) },
623
+ exists: 'Boolean',
624
+ },
625
+ });
626
+ }
627
+ if (!schemaComposer.has('StringFilter')) {
628
+ schemaComposer.createInputTC({
629
+ name: 'StringFilter',
630
+ fields: {
631
+ eq: GraphQLString,
632
+ ne: GraphQLString,
633
+ in: { type: '[String!]' },
634
+ nin: { type: '[String!]' },
635
+ regex: GraphQLString,
636
+ exists: 'Boolean',
637
+ },
638
+ });
639
+ }
640
+ if (!schemaComposer.has('FloatFilter')) {
641
+ schemaComposer.createInputTC({
642
+ name: 'FloatFilter',
643
+ fields: {
644
+ eq: GraphQLFloat,
645
+ ne: GraphQLFloat,
646
+ in: { type: '[Float!]' },
647
+ nin: { type: '[Float!]' },
648
+ gt: GraphQLFloat,
649
+ gte: GraphQLFloat,
650
+ lt: GraphQLFloat,
651
+ lte: GraphQLFloat,
652
+ exists: 'Boolean',
653
+ },
654
+ });
655
+ }
656
+ if (!schemaComposer.has('BooleanFilter')) {
657
+ schemaComposer.createInputTC({
658
+ name: 'BooleanFilter',
659
+ fields: { eq: 'Boolean', ne: 'Boolean', exists: 'Boolean' },
660
+ });
661
+ }
662
+ if (!schemaComposer.has('DateTimeFilter')) {
663
+ schemaComposer.createInputTC({
664
+ name: 'DateTimeFilter',
665
+ fields: {
666
+ eq: 'DateTime',
667
+ ne: 'DateTime',
668
+ in: { type: '[DateTime!]' },
669
+ nin: { type: '[DateTime!]' },
670
+ gt: 'DateTime',
671
+ gte: 'DateTime',
672
+ lt: 'DateTime',
673
+ lte: 'DateTime',
674
+ exists: 'Boolean',
675
+ },
676
+ });
677
+ }
678
+ }
679
+ function markMongoDirectiveStringsAsBlocks(schema) {
680
+ const markNode = (astNode) => {
681
+ const directives = astNode?.directives;
682
+ if (!directives)
683
+ return;
684
+ for (const directive of directives) {
685
+ if (directive.name.value !== 'mongo' || !directive.arguments)
686
+ continue;
687
+ for (const arg of directive.arguments) {
688
+ if (arg.value.kind !== 'StringValue')
689
+ continue;
690
+ if (arg.name.value !== 'filter' &&
691
+ arg.name.value !== 'where' &&
692
+ arg.name.value !== 'set' &&
693
+ arg.name.value !== 'selection' &&
694
+ arg.name.value !== 'pipeline') {
695
+ continue;
696
+ }
697
+ if (isBareBinder(arg.value.value))
698
+ continue;
699
+ arg.value.block = true;
700
+ }
701
+ }
702
+ };
703
+ for (const type of Object.values(schema.getTypeMap())) {
704
+ if (!(type instanceof GraphQLObjectType))
705
+ continue;
706
+ markNode(type.astNode);
707
+ for (const field of Object.values(type.getFields())) {
708
+ markNode(field.astNode);
709
+ }
710
+ }
711
+ }
712
+ function isBareBinder(value) {
713
+ const trimmed = value.trim();
714
+ if (!trimmed.startsWith('$') ||
715
+ trimmed.includes('\n') ||
716
+ trimmed.includes(':') ||
717
+ trimmed.includes(' ')) {
718
+ return false;
719
+ }
720
+ if (trimmed.includes('...'))
721
+ return false;
722
+ const segments = trimmed.slice(1).split('.');
723
+ if (!segments.length || segments.some(s => !s))
724
+ return false;
725
+ for (const seg of segments) {
726
+ const c0 = seg.charCodeAt(0);
727
+ const okStart = (c0 >= 65 && c0 <= 90) || (c0 >= 97 && c0 <= 122) || c0 === 95;
728
+ if (!okStart)
729
+ return false;
730
+ for (let i = 1; i < seg.length; i++) {
731
+ const c = seg.charCodeAt(i);
732
+ const ok = (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 95;
733
+ if (!ok)
734
+ return false;
735
+ }
736
+ }
737
+ return true;
738
+ }
739
+ function blockArg(body) {
740
+ const trimmed = body.replace(/^\n+|\n+$/g, '');
741
+ const indented = trimmed
742
+ .split('\n')
743
+ .map(line => (line.length ? ` ${line}` : line))
744
+ .join('\n');
745
+ return indented.includes('\n') ? indented : `\n${indented}`;
746
+ }
747
+ function indent(body, levels) {
748
+ const pad = ' '.repeat(levels);
749
+ return body
750
+ .split('\n')
751
+ .map(line => (line.length ? pad + line : line))
752
+ .join('\n');
753
+ }
754
+ function pluralizeFallback(name) {
755
+ const lower = name.toLowerCase();
756
+ if (lower.endsWith('s'))
757
+ return lower;
758
+ return `${lower}s`;
759
+ }