@nestbridge/vite 0.1.0 → 1.0.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.
@@ -1,6 +1,6 @@
1
- import { readFileSync, mkdirSync, writeFileSync, globSync } from 'node:fs';
1
+ import { readFileSync, existsSync, mkdirSync, writeFileSync, globSync } from 'node:fs';
2
2
  import ts from 'typescript';
3
- import { relative, dirname, extname, join, resolve } from 'node:path';
3
+ import { relative, dirname, extname, resolve, join } from 'node:path';
4
4
  import { normalizePath } from 'vite';
5
5
 
6
6
  const findDecorator = (node, decoratorName) => {
@@ -292,6 +292,608 @@ const analyzeControllers = (filePaths) => {
292
292
  return { controllers, diagnostics };
293
293
  };
294
294
 
295
+ const GRAPHQL_OPERATION_DECORATOR_NAMES = {
296
+ Query: "query",
297
+ Mutation: "mutation"
298
+ };
299
+
300
+ const PRIMITIVE_SCALAR_TYPES = {
301
+ string: "String",
302
+ number: "Float",
303
+ boolean: "Boolean"
304
+ };
305
+ const unwrapPromise = (typeNode) => {
306
+ if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName) && typeNode.typeName.text === "Promise" && typeNode.typeArguments?.[0] !== void 0) {
307
+ return unwrapPromise(typeNode.typeArguments[0]);
308
+ }
309
+ return typeNode;
310
+ };
311
+ const unwrapNullable = (typeNode) => {
312
+ if (!ts.isUnionTypeNode(typeNode)) {
313
+ return { inner: typeNode, isNullable: false };
314
+ }
315
+ const nonNullMembers = typeNode.types.filter(
316
+ (member) => member.kind !== ts.SyntaxKind.NullKeyword && member.kind !== ts.SyntaxKind.UndefinedKeyword
317
+ );
318
+ const [onlyMember] = nonNullMembers;
319
+ if (nonNullMembers.length !== 1 || onlyMember === void 0) {
320
+ return { inner: typeNode, isNullable: nonNullMembers.length !== typeNode.types.length };
321
+ }
322
+ return { inner: onlyMember, isNullable: true };
323
+ };
324
+ const unwrapArrayElement = (typeNode) => {
325
+ if (ts.isArrayTypeNode(typeNode)) {
326
+ return typeNode.elementType;
327
+ }
328
+ if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName) && typeNode.typeName.text === "Array" && typeNode.typeArguments?.[0] !== void 0) {
329
+ return typeNode.typeArguments[0];
330
+ }
331
+ return void 0;
332
+ };
333
+ const identifierTextOf = (typeNode) => {
334
+ if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
335
+ return typeNode.typeName.text;
336
+ }
337
+ switch (typeNode.kind) {
338
+ case ts.SyntaxKind.StringKeyword:
339
+ return "string";
340
+ case ts.SyntaxKind.NumberKeyword:
341
+ return "number";
342
+ case ts.SyntaxKind.BooleanKeyword:
343
+ return "boolean";
344
+ default:
345
+ return void 0;
346
+ }
347
+ };
348
+ const unwrapTypeNode = (typeNode) => {
349
+ const withoutPromise = unwrapPromise(typeNode);
350
+ const { inner: withoutNullable, isNullable } = unwrapNullable(withoutPromise);
351
+ const arrayElement = unwrapArrayElement(withoutNullable);
352
+ const element = arrayElement === void 0 ? withoutNullable : unwrapNullable(arrayElement).inner;
353
+ const identifierText = identifierTextOf(element);
354
+ if (identifierText === void 0) {
355
+ return void 0;
356
+ }
357
+ return { identifierText, isArray: arrayElement !== void 0, isNullable };
358
+ };
359
+ const graphqlScalarNameFor = (identifierText) => PRIMITIVE_SCALAR_TYPES[identifierText] ?? identifierText;
360
+ const graphqlTypeStringFor = (unwrapped, explicitTypeName) => {
361
+ const baseName = explicitTypeName ?? graphqlScalarNameFor(unwrapped.identifierText);
362
+ const wrapped = unwrapped.isArray ? `[${baseName}!]` : baseName;
363
+ return unwrapped.isNullable ? wrapped : `${wrapped}!`;
364
+ };
365
+
366
+ const readTypeThunkExpression = (thunk) => {
367
+ if (!ts.isBlock(thunk.body)) {
368
+ return thunk.body;
369
+ }
370
+ const returnStatement = thunk.body.statements.find(ts.isReturnStatement);
371
+ return returnStatement?.expression;
372
+ };
373
+
374
+ const readArgsTypeOption = (decorator) => {
375
+ if (!ts.isCallExpression(decorator.expression)) {
376
+ return void 0;
377
+ }
378
+ const optionsArgument = decorator.expression.arguments.find(ts.isObjectLiteralExpression);
379
+ if (optionsArgument === void 0) {
380
+ return void 0;
381
+ }
382
+ const typeProperty = optionsArgument.properties.find(
383
+ (property) => ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === "type"
384
+ );
385
+ if (typeProperty === void 0) {
386
+ return void 0;
387
+ }
388
+ const thunk = typeProperty.initializer;
389
+ if (!ts.isArrowFunction(thunk) && !ts.isFunctionExpression(thunk)) {
390
+ return void 0;
391
+ }
392
+ const returnedExpression = readTypeThunkExpression(thunk);
393
+ if (returnedExpression === void 0) {
394
+ return void 0;
395
+ }
396
+ if (ts.isArrayLiteralExpression(returnedExpression)) {
397
+ const element = returnedExpression.elements[0];
398
+ return element !== void 0 && ts.isIdentifier(element) ? { typeName: element.text, isArray: true } : void 0;
399
+ }
400
+ return ts.isIdentifier(returnedExpression) ? { typeName: returnedExpression.text, isArray: false } : void 0;
401
+ };
402
+
403
+ const extractResolverArgumentDefinition = (parameter, index, context) => {
404
+ const decorator = findAnyDecorator(parameter, ["Args"]);
405
+ const location = locationOf(context.sourceFile, parameter);
406
+ if (decorator === void 0) {
407
+ context.diagnostics.push({
408
+ code: "unsupported-argument",
409
+ title: "Unsupported argument.",
410
+ controllerName: context.resolverName,
411
+ memberName: context.methodName,
412
+ detail: `Parameter "${parameter.name.getText()}" must be decorated with @Args to be transported through a NestBridge GraphQL client.`,
413
+ filePath: context.filePath,
414
+ line: location.line,
415
+ column: location.column
416
+ });
417
+ return void 0;
418
+ }
419
+ if (!ts.isIdentifier(parameter.name)) {
420
+ context.diagnostics.push({
421
+ code: "unsupported-argument",
422
+ title: "Unsupported argument.",
423
+ controllerName: context.resolverName,
424
+ memberName: context.methodName,
425
+ detail: "Destructured parameters cannot be transported through a NestBridge GraphQL client.",
426
+ filePath: context.filePath,
427
+ line: location.line,
428
+ column: location.column
429
+ });
430
+ return void 0;
431
+ }
432
+ const nameArgument = readStaticStringArgument(decorator);
433
+ if (!nameArgument.ok) {
434
+ context.diagnostics.push({
435
+ code: "unsupported-argument",
436
+ title: "Unsupported argument.",
437
+ controllerName: context.resolverName,
438
+ memberName: context.methodName,
439
+ detail: "@Args() name must be a statically analyzable string literal.",
440
+ found: `@Args(${nameArgument.argumentText})`,
441
+ filePath: context.filePath,
442
+ line: location.line,
443
+ column: location.column
444
+ });
445
+ return void 0;
446
+ }
447
+ if (nameArgument.value === void 0) {
448
+ context.diagnostics.push({
449
+ code: "unsupported-argument",
450
+ title: "Unsupported argument.",
451
+ controllerName: context.resolverName,
452
+ memberName: context.methodName,
453
+ detail: "A whole @Args() is not supported; provide an argument name such as @Args('id').",
454
+ filePath: context.filePath,
455
+ line: location.line,
456
+ column: location.column
457
+ });
458
+ return void 0;
459
+ }
460
+ if (parameter.type === void 0) {
461
+ context.diagnostics.push({
462
+ code: "unsupported-argument",
463
+ title: "Unsupported argument.",
464
+ controllerName: context.resolverName,
465
+ memberName: context.methodName,
466
+ detail: `@Args() parameter "${parameter.name.text}" needs an explicit type annotation.`,
467
+ filePath: context.filePath,
468
+ line: location.line,
469
+ column: location.column
470
+ });
471
+ return void 0;
472
+ }
473
+ const unwrapped = unwrapTypeNode(parameter.type);
474
+ if (unwrapped === void 0) {
475
+ context.diagnostics.push({
476
+ code: "unsupported-argument",
477
+ title: "Unsupported argument.",
478
+ controllerName: context.resolverName,
479
+ memberName: context.methodName,
480
+ detail: `@Args() parameter "${parameter.name.text}" has a type NestBridge cannot statically resolve to a GraphQL type.`,
481
+ found: parameter.type.getText(),
482
+ filePath: context.filePath,
483
+ line: location.line,
484
+ column: location.column
485
+ });
486
+ return void 0;
487
+ }
488
+ const explicitType = readArgsTypeOption(decorator);
489
+ return {
490
+ index,
491
+ parameterName: parameter.name.text,
492
+ name: nameArgument.value,
493
+ graphqlType: graphqlTypeStringFor(unwrapped, explicitType?.typeName)
494
+ };
495
+ };
496
+
497
+ const parsedFilesByPath = /* @__PURE__ */ new Map();
498
+ const parseFile = (filePath) => {
499
+ const cached = parsedFilesByPath.get(filePath);
500
+ if (cached !== void 0) {
501
+ return cached;
502
+ }
503
+ const content = readFileSync(filePath, "utf-8");
504
+ const sourceFile = ts.createSourceFile(
505
+ filePath,
506
+ content,
507
+ ts.ScriptTarget.ESNext,
508
+ true,
509
+ ts.ScriptKind.TS
510
+ );
511
+ parsedFilesByPath.set(filePath, sourceFile);
512
+ return sourceFile;
513
+ };
514
+ const resolveModuleFile = (fromFilePath, moduleSpecifierText) => {
515
+ if (!moduleSpecifierText.startsWith(".")) {
516
+ return void 0;
517
+ }
518
+ const base = resolve(dirname(fromFilePath), moduleSpecifierText);
519
+ const candidates = [`${base}.ts`, `${base}.tsx`, resolve(base, "index.ts")];
520
+ return candidates.find((candidate) => existsSync(candidate));
521
+ };
522
+ const findExportedDeclaration = (sourceFile, name) => sourceFile.statements.find(
523
+ (statement) => ts.isClassDeclaration(statement) && statement.name?.text === name
524
+ );
525
+ const findImportSource = (sourceFile, localName) => {
526
+ for (const statement of sourceFile.statements) {
527
+ if (!ts.isImportDeclaration(statement) || !ts.isStringLiteralLike(statement.moduleSpecifier)) {
528
+ continue;
529
+ }
530
+ const namedBindings = statement.importClause?.namedBindings;
531
+ if (namedBindings === void 0 || !ts.isNamedImports(namedBindings)) {
532
+ continue;
533
+ }
534
+ const element = namedBindings.elements.find((candidate) => candidate.name.text === localName);
535
+ if (element !== void 0) {
536
+ return {
537
+ moduleSpecifierText: statement.moduleSpecifier.text,
538
+ importedName: element.propertyName?.text ?? element.name.text
539
+ };
540
+ }
541
+ }
542
+ return void 0;
543
+ };
544
+ const findReExportSource = (sourceFile, name) => {
545
+ for (const statement of sourceFile.statements) {
546
+ if (!ts.isExportDeclaration(statement) || statement.moduleSpecifier === void 0 || !ts.isStringLiteralLike(statement.moduleSpecifier)) {
547
+ continue;
548
+ }
549
+ if (statement.exportClause === void 0) {
550
+ return statement.moduleSpecifier.text;
551
+ }
552
+ if (ts.isNamedExports(statement.exportClause) && statement.exportClause.elements.some(
553
+ (element) => (element.propertyName?.text ?? element.name.text) === name
554
+ )) {
555
+ return statement.moduleSpecifier.text;
556
+ }
557
+ }
558
+ return void 0;
559
+ };
560
+ const resolveClassDeclaration = (name, fromSourceFile, fromFilePath, visited = /* @__PURE__ */ new Set()) => {
561
+ if (visited.has(fromFilePath)) {
562
+ return void 0;
563
+ }
564
+ visited.add(fromFilePath);
565
+ const direct = findExportedDeclaration(fromSourceFile, name);
566
+ if (direct !== void 0) {
567
+ return { classDeclaration: direct, sourceFile: fromSourceFile, filePath: fromFilePath };
568
+ }
569
+ const importSource = findImportSource(fromSourceFile, name);
570
+ if (importSource !== void 0) {
571
+ const resolvedPath = resolveModuleFile(fromFilePath, importSource.moduleSpecifierText);
572
+ if (resolvedPath !== void 0) {
573
+ const nextSourceFile = parseFile(resolvedPath);
574
+ const result = resolveClassDeclaration(
575
+ importSource.importedName,
576
+ nextSourceFile,
577
+ resolvedPath,
578
+ visited
579
+ );
580
+ if (result !== void 0) {
581
+ return result;
582
+ }
583
+ }
584
+ }
585
+ const reExportModuleSpecifierText = findReExportSource(fromSourceFile, name);
586
+ if (reExportModuleSpecifierText !== void 0) {
587
+ const resolvedPath = resolveModuleFile(fromFilePath, reExportModuleSpecifierText);
588
+ if (resolvedPath !== void 0) {
589
+ const nextSourceFile = parseFile(resolvedPath);
590
+ return resolveClassDeclaration(name, nextSourceFile, resolvedPath, visited);
591
+ }
592
+ }
593
+ return void 0;
594
+ };
595
+
596
+ const PRIMITIVE_SCALAR_NAMES$1 = /* @__PURE__ */ new Set(["string", "number", "boolean"]);
597
+ const extractSelectionFields = (classDeclaration, sourceFile, filePath, context) => {
598
+ const typeName = classDeclaration.name?.text ?? "(anonymous type)";
599
+ const location = locationOf(sourceFile, classDeclaration);
600
+ if (context.visitedTypeNames.has(typeName)) {
601
+ context.diagnostics.push({
602
+ code: "circular-type",
603
+ title: "Circular type.",
604
+ controllerName: context.resolverName,
605
+ memberName: context.methodName,
606
+ detail: `Type "${typeName}" references itself, directly or indirectly. NestBridge cannot build a finite GraphQL selection set for it.`,
607
+ filePath,
608
+ line: location.line,
609
+ column: location.column
610
+ });
611
+ return void 0;
612
+ }
613
+ const nextVisited = new Set(context.visitedTypeNames).add(typeName);
614
+ const properties = classDeclaration.members.filter(
615
+ (member) => ts.isPropertyDeclaration(member) && findDecorator(member, "Field") !== void 0
616
+ );
617
+ const fields = [];
618
+ for (const property of properties) {
619
+ if (!ts.isIdentifier(property.name)) {
620
+ continue;
621
+ }
622
+ const fieldName = property.name.text;
623
+ const fieldLocation = locationOf(sourceFile, property);
624
+ if (property.type === void 0) {
625
+ context.diagnostics.push({
626
+ code: "unsupported-return-type",
627
+ title: "Unsupported field type.",
628
+ controllerName: context.resolverName,
629
+ memberName: context.methodName,
630
+ detail: `Field "${fieldName}" on "${typeName}" needs an explicit type annotation.`,
631
+ filePath,
632
+ line: fieldLocation.line,
633
+ column: fieldLocation.column
634
+ });
635
+ return void 0;
636
+ }
637
+ const unwrapped = unwrapTypeNode(property.type);
638
+ if (unwrapped === void 0) {
639
+ context.diagnostics.push({
640
+ code: "unsupported-return-type",
641
+ title: "Unsupported field type.",
642
+ controllerName: context.resolverName,
643
+ memberName: context.methodName,
644
+ detail: `Field "${fieldName}" on "${typeName}" has a type NestBridge cannot statically resolve.`,
645
+ found: property.type.getText(),
646
+ filePath,
647
+ line: fieldLocation.line,
648
+ column: fieldLocation.column
649
+ });
650
+ return void 0;
651
+ }
652
+ if (PRIMITIVE_SCALAR_NAMES$1.has(unwrapped.identifierText)) {
653
+ fields.push({ name: fieldName });
654
+ continue;
655
+ }
656
+ const resolved = resolveClassDeclaration(unwrapped.identifierText, sourceFile, filePath);
657
+ if (resolved === void 0) {
658
+ fields.push({ name: fieldName });
659
+ continue;
660
+ }
661
+ if (findDecorator(resolved.classDeclaration, "ObjectType") === void 0) {
662
+ context.diagnostics.push({
663
+ code: "unsupported-return-type",
664
+ title: "Unsupported field type.",
665
+ controllerName: context.resolverName,
666
+ memberName: context.methodName,
667
+ detail: `Field "${fieldName}" on "${typeName}" resolves to class "${unwrapped.identifierText}", which is not decorated with @ObjectType(). NestBridge cannot build a GraphQL selection set for it.`,
668
+ filePath,
669
+ line: fieldLocation.line,
670
+ column: fieldLocation.column
671
+ });
672
+ return void 0;
673
+ }
674
+ const children = extractSelectionFields(
675
+ resolved.classDeclaration,
676
+ resolved.sourceFile,
677
+ resolved.filePath,
678
+ {
679
+ ...context,
680
+ visitedTypeNames: nextVisited
681
+ }
682
+ );
683
+ if (children === void 0) {
684
+ return void 0;
685
+ }
686
+ fields.push({ name: fieldName, children });
687
+ }
688
+ return fields;
689
+ };
690
+
691
+ const readNameFromOptions = (optionsArgument) => {
692
+ const nameProperty = optionsArgument.properties.find(
693
+ (property) => ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === "name"
694
+ );
695
+ if (nameProperty === void 0 || !ts.isStringLiteralLike(nameProperty.initializer)) {
696
+ return void 0;
697
+ }
698
+ return nameProperty.initializer.text;
699
+ };
700
+ const readGraphqlOperationName = (decorator) => {
701
+ const expression = decorator.expression;
702
+ if (!ts.isCallExpression(expression)) {
703
+ return { ok: true, value: void 0 };
704
+ }
705
+ let value;
706
+ for (const argument of expression.arguments) {
707
+ if (ts.isArrowFunction(argument) || ts.isFunctionExpression(argument)) {
708
+ continue;
709
+ }
710
+ if (ts.isStringLiteralLike(argument)) {
711
+ value = argument.text;
712
+ continue;
713
+ }
714
+ if (ts.isObjectLiteralExpression(argument)) {
715
+ value = readNameFromOptions(argument) ?? value;
716
+ continue;
717
+ }
718
+ return { ok: false, argumentText: argument.getText() };
719
+ }
720
+ return { ok: true, value };
721
+ };
722
+
723
+ const readGraphqlReturnTypeOption = (decorator) => {
724
+ if (!ts.isCallExpression(decorator.expression)) {
725
+ return void 0;
726
+ }
727
+ const thunk = decorator.expression.arguments.find(
728
+ (argument) => ts.isArrowFunction(argument) || ts.isFunctionExpression(argument)
729
+ );
730
+ if (thunk === void 0) {
731
+ return void 0;
732
+ }
733
+ const returnedExpression = readTypeThunkExpression(thunk);
734
+ if (returnedExpression === void 0) {
735
+ return void 0;
736
+ }
737
+ if (ts.isArrayLiteralExpression(returnedExpression)) {
738
+ const element = returnedExpression.elements[0];
739
+ return element !== void 0 && ts.isIdentifier(element) ? element.text : void 0;
740
+ }
741
+ return ts.isIdentifier(returnedExpression) ? returnedExpression.text : void 0;
742
+ };
743
+
744
+ const PRIMITIVE_SCALAR_NAMES = /* @__PURE__ */ new Set(["string", "number", "boolean"]);
745
+ const extractResolverMethodDefinition = (method, context) => {
746
+ const decorator = findAnyDecorator(method, Object.keys(GRAPHQL_OPERATION_DECORATOR_NAMES));
747
+ if (decorator === void 0) {
748
+ return void 0;
749
+ }
750
+ const methodName = method.name.getText();
751
+ const decoratorName = decoratorNameOf(decorator);
752
+ const location = locationOf(context.sourceFile, method);
753
+ if (decoratorName === void 0) {
754
+ return void 0;
755
+ }
756
+ const operationKind = GRAPHQL_OPERATION_DECORATOR_NAMES[decoratorName];
757
+ if (operationKind === void 0) {
758
+ return void 0;
759
+ }
760
+ const nameArgument = readGraphqlOperationName(decorator);
761
+ if (!nameArgument.ok) {
762
+ context.diagnostics.push({
763
+ code: "unsupported-route",
764
+ title: "Unsupported operation name.",
765
+ controllerName: context.resolverName,
766
+ memberName: methodName,
767
+ detail: "GraphQL operation names must be statically analyzable string literals.",
768
+ found: `@${decoratorName}(${nameArgument.argumentText})`,
769
+ filePath: context.filePath,
770
+ line: location.line,
771
+ column: location.column
772
+ });
773
+ return void 0;
774
+ }
775
+ const decoratorReturnType = readGraphqlReturnTypeOption(decorator);
776
+ const identifierText = decoratorReturnType ?? (method.type === void 0 ? void 0 : unwrapTypeNode(method.type)?.identifierText);
777
+ if (identifierText === void 0) {
778
+ context.diagnostics.push({
779
+ code: "unsupported-return-type",
780
+ title: "Unsupported return type.",
781
+ controllerName: context.resolverName,
782
+ memberName: methodName,
783
+ detail: 'GraphQL resolver methods need a type thunk on @Query()/@Mutation() (e.g. "() => UserType") or an explicit return type annotation so NestBridge can build a selection set.',
784
+ filePath: context.filePath,
785
+ line: location.line,
786
+ column: location.column
787
+ });
788
+ return void 0;
789
+ }
790
+ let selection = [];
791
+ if (!PRIMITIVE_SCALAR_NAMES.has(identifierText.toLowerCase())) {
792
+ const resolved = resolveClassDeclaration(identifierText, context.sourceFile, context.filePath);
793
+ if (resolved === void 0 && decoratorReturnType === void 0) {
794
+ context.diagnostics.push({
795
+ code: "unsupported-return-type",
796
+ title: "Unsupported return type.",
797
+ controllerName: context.resolverName,
798
+ memberName: methodName,
799
+ detail: `NestBridge could not locate the declaration of type "${identifierText}".`,
800
+ filePath: context.filePath,
801
+ line: location.line,
802
+ column: location.column
803
+ });
804
+ return void 0;
805
+ }
806
+ if (resolved !== void 0) {
807
+ const fields = extractSelectionFields(
808
+ resolved.classDeclaration,
809
+ resolved.sourceFile,
810
+ resolved.filePath,
811
+ {
812
+ resolverName: context.resolverName,
813
+ methodName,
814
+ diagnostics: context.diagnostics,
815
+ visitedTypeNames: /* @__PURE__ */ new Set()
816
+ }
817
+ );
818
+ if (fields === void 0) {
819
+ return void 0;
820
+ }
821
+ selection = fields;
822
+ }
823
+ }
824
+ const args = method.parameters.map(
825
+ (parameter, index) => extractResolverArgumentDefinition(parameter, index, {
826
+ sourceFile: context.sourceFile,
827
+ filePath: context.filePath,
828
+ resolverName: context.resolverName,
829
+ methodName,
830
+ diagnostics: context.diagnostics
831
+ })
832
+ );
833
+ if (args.some((argument) => argument === void 0)) {
834
+ return void 0;
835
+ }
836
+ return {
837
+ name: methodName,
838
+ operationKind,
839
+ operationName: nameArgument.value ?? methodName,
840
+ arguments: args.filter((argument) => argument !== void 0),
841
+ selection,
842
+ line: location.line,
843
+ column: location.column
844
+ };
845
+ };
846
+
847
+ const extractResolverDefinition = (classDeclaration, sourceFile, filePath, diagnostics) => {
848
+ const resolverName = classDeclaration.name?.text ?? "(anonymous resolver)";
849
+ const methods = classDeclaration.members.filter((member) => ts.isMethodDeclaration(member)).map(
850
+ (method) => extractResolverMethodDefinition(method, {
851
+ sourceFile,
852
+ filePath,
853
+ resolverName,
854
+ diagnostics
855
+ })
856
+ ).filter((method) => method !== void 0);
857
+ return {
858
+ name: resolverName,
859
+ sourceFile: filePath,
860
+ methods
861
+ };
862
+ };
863
+
864
+ const findResolverClasses = (sourceFile) => {
865
+ return sourceFile.statements.filter(
866
+ (statement) => ts.isClassDeclaration(statement) && findDecorator(statement, "Resolver") !== void 0
867
+ );
868
+ };
869
+
870
+ const analyzeResolvers = (filePaths) => {
871
+ const diagnostics = [];
872
+ const resolvers = [];
873
+ for (const filePath of filePaths) {
874
+ const content = readFileSync(filePath, "utf-8");
875
+ const sourceFile = ts.createSourceFile(
876
+ filePath,
877
+ content,
878
+ ts.ScriptTarget.ESNext,
879
+ true,
880
+ ts.ScriptKind.TS
881
+ );
882
+ for (const classDeclaration of findResolverClasses(sourceFile)) {
883
+ const resolver = extractResolverDefinition(
884
+ classDeclaration,
885
+ sourceFile,
886
+ filePath,
887
+ diagnostics
888
+ );
889
+ if (resolver !== void 0) {
890
+ resolvers.push(resolver);
891
+ }
892
+ }
893
+ }
894
+ return { resolvers, diagnostics };
895
+ };
896
+
295
897
  const toPosixPath = (filePath) => filePath.replace(/\\/g, "/");
296
898
  const importSpecifierFor = (sourceFile, outputFilePath) => {
297
899
  if (!sourceFile.startsWith(".") && !/^[A-Za-z]:[\\/]/.test(sourceFile) && !sourceFile.startsWith("/")) {
@@ -396,7 +998,7 @@ const generatePathExpression = (method) => {
396
998
 
397
999
  const generateQueryExpression = (parameters) => mergeNamedParametersExpression(parameters.filter((parameter) => parameter.kind === "query"));
398
1000
 
399
- const generateMethod = (method) => {
1001
+ const generateMethod$1 = (method) => {
400
1002
  const requestProperties = [
401
1003
  `method: ${JSON.stringify(method.httpMethod)}`,
402
1004
  `path: ${generatePathExpression(method)}`
@@ -422,7 +1024,7 @@ const generateMethod = (method) => {
422
1024
  ].join("\n");
423
1025
  };
424
1026
  const generateControllerModule = (controller) => {
425
- const methods = controller.methods.map(generateMethod).join("\n\n");
1027
+ const methods = controller.methods.map(generateMethod$1).join("\n\n");
426
1028
  return [
427
1029
  "import { request } from '@nestbridge/runtime';",
428
1030
  "",
@@ -435,6 +1037,61 @@ const generateControllerModule = (controller) => {
435
1037
  ].join("\n");
436
1038
  };
437
1039
 
1040
+ const capitalize = (value) => `${value.charAt(0).toUpperCase()}${value.slice(1)}`;
1041
+ const renderSelectionSet = (fields) => {
1042
+ const rendered = fields.map(
1043
+ (field) => field.children === void 0 ? field.name : `${field.name} ${renderSelectionSet(field.children)}`
1044
+ );
1045
+ return `{ ${rendered.join(" ")} }`;
1046
+ };
1047
+ const generateGraphqlDocument = (method) => {
1048
+ const variableDeclarations = method.arguments.map((argument) => `$${argument.name}: ${argument.graphqlType}`).join(", ");
1049
+ const fieldArguments = method.arguments.map((argument) => `${argument.name}: $${argument.name}`).join(", ");
1050
+ const variablesClause = variableDeclarations.length > 0 ? `(${variableDeclarations})` : "";
1051
+ const fieldArgumentsClause = fieldArguments.length > 0 ? `(${fieldArguments})` : "";
1052
+ const fieldSelection = method.selection.length > 0 ? ` ${renderSelectionSet(method.selection)}` : "";
1053
+ return `${method.operationKind} ${capitalize(method.name)}${variablesClause} { ${method.operationName}${fieldArgumentsClause}${fieldSelection} }`;
1054
+ };
1055
+
1056
+ const generateResolverArgumentList = (resolverArguments) => [...resolverArguments].sort((a, b) => a.index - b.index).map((argument) => argument.parameterName).join(", ");
1057
+
1058
+ const generateVariablesExpression = (resolverArguments) => {
1059
+ if (resolverArguments.length === 0) {
1060
+ return void 0;
1061
+ }
1062
+ const entries = resolverArguments.map(
1063
+ (argument) => `${JSON.stringify(argument.name)}: ${argument.parameterName}`
1064
+ );
1065
+ return `{ ${entries.join(", ")} }`;
1066
+ };
1067
+ const generateMethod = (method) => {
1068
+ const requestProperties = [`document: ${JSON.stringify(generateGraphqlDocument(method))}`];
1069
+ const variablesExpression = generateVariablesExpression(method.arguments);
1070
+ if (variablesExpression !== void 0) {
1071
+ requestProperties.push(`variables: ${variablesExpression}`);
1072
+ }
1073
+ return [
1074
+ ` ${method.name}(${generateResolverArgumentList(method.arguments)}) {`,
1075
+ " return graphqlRequest({",
1076
+ ...requestProperties.map((property) => ` ${property},`),
1077
+ " });",
1078
+ " }"
1079
+ ].join("\n");
1080
+ };
1081
+ const generateResolverModule = (resolver) => {
1082
+ const methods = resolver.methods.map(generateMethod).join("\n\n");
1083
+ return [
1084
+ "import { graphqlRequest } from '@nestbridge/runtime';",
1085
+ "",
1086
+ `export class ${resolver.name} {`,
1087
+ " constructor() {}",
1088
+ "",
1089
+ methods,
1090
+ "}",
1091
+ ""
1092
+ ].join("\n");
1093
+ };
1094
+
438
1095
  const stripLeadingParentSegments = (relativePath) => {
439
1096
  const segments = relativePath.split(/[\\/]/);
440
1097
  const firstOwnedIndex = segments.findIndex((segment) => segment !== "..");
@@ -458,30 +1115,46 @@ const writeControllerDeclarations = (controllers, root, outputDir) => {
458
1115
  }
459
1116
  };
460
1117
 
461
- const discoverControllerFiles = (patterns, root) => {
1118
+ const writeResolverDeclarations = (resolvers, root, outputDir) => {
1119
+ for (const resolver of resolvers) {
1120
+ const outputFilePath = mirroredDeclarationPath(root, outputDir, resolver.sourceFile);
1121
+ mkdirSync(dirname(outputFilePath), { recursive: true });
1122
+ writeFileSync(outputFilePath, generateControllerDeclaration(resolver, outputFilePath), "utf-8");
1123
+ }
1124
+ };
1125
+
1126
+ const discoverFiles = (patterns, root) => {
462
1127
  const matches = globSync([...patterns], { cwd: root });
463
1128
  return [...new Set(matches.map((match) => resolve(root, match)))].sort();
464
1129
  };
465
1130
 
466
1131
  const resolveNestBridgeOptions = (options) => ({
467
1132
  controllers: Array.isArray(options.controllers) ? options.controllers : [options.controllers],
1133
+ resolvers: options.resolvers === void 0 ? [] : Array.isArray(options.resolvers) ? options.resolvers : [options.resolvers],
468
1134
  baseURL: options.baseURL,
469
1135
  debug: options.debug ?? false,
470
1136
  outputDir: options.outputDir ?? ".nestbridge"
471
1137
  });
472
1138
 
473
- const VIRTUAL_MODULE_PREFIX = "virtual:nestbridge/controller/";
474
- const RESOLVED_VIRTUAL_MODULE_PREFIX = `\0${VIRTUAL_MODULE_PREFIX}`;
475
- const encodeControllerVirtualId = (absoluteControllerPath) => `${VIRTUAL_MODULE_PREFIX}${encodeURIComponent(absoluteControllerPath)}`;
1139
+ const VIRTUAL_MODULE_PREFIX$1 = "virtual:nestbridge/controller/";
1140
+ const RESOLVED_VIRTUAL_MODULE_PREFIX$1 = `\0${VIRTUAL_MODULE_PREFIX$1}`;
1141
+ const encodeControllerVirtualId = (absoluteControllerPath) => `${VIRTUAL_MODULE_PREFIX$1}${encodeURIComponent(absoluteControllerPath)}`;
476
1142
  const resolvedControllerVirtualId = (virtualId) => `\0${virtualId}`;
477
- const isResolvedControllerVirtualId = (id) => id.startsWith(RESOLVED_VIRTUAL_MODULE_PREFIX);
478
- const decodeControllerVirtualId = (resolvedId) => decodeURIComponent(resolvedId.slice(RESOLVED_VIRTUAL_MODULE_PREFIX.length));
1143
+ const isResolvedControllerVirtualId = (id) => id.startsWith(RESOLVED_VIRTUAL_MODULE_PREFIX$1);
1144
+ const decodeControllerVirtualId = (resolvedId) => decodeURIComponent(resolvedId.slice(RESOLVED_VIRTUAL_MODULE_PREFIX$1.length));
1145
+
1146
+ const VIRTUAL_MODULE_PREFIX = "virtual:nestbridge/resolver/";
1147
+ const RESOLVED_VIRTUAL_MODULE_PREFIX = `\0${VIRTUAL_MODULE_PREFIX}`;
1148
+ const encodeResolverVirtualId = (absoluteResolverPath) => `${VIRTUAL_MODULE_PREFIX}${encodeURIComponent(absoluteResolverPath)}`;
1149
+ const resolvedResolverVirtualId = (virtualId) => `\0${virtualId}`;
1150
+ const isResolvedResolverVirtualId = (id) => id.startsWith(RESOLVED_VIRTUAL_MODULE_PREFIX);
1151
+ const decodeResolverVirtualId = (resolvedId) => decodeURIComponent(resolvedId.slice(RESOLVED_VIRTUAL_MODULE_PREFIX.length));
479
1152
 
480
1153
  const createControllerRegistry = (patterns, root) => {
481
1154
  const controllersByFile = /* @__PURE__ */ new Map();
482
1155
  const refresh = () => {
483
1156
  controllersByFile.clear();
484
- const files = discoverControllerFiles(patterns, root);
1157
+ const files = discoverFiles(patterns, root);
485
1158
  const { controllers, diagnostics } = analyzeControllers(files);
486
1159
  for (const controller of controllers) {
487
1160
  controllersByFile.set(normalizePath(controller.sourceFile), controller);
@@ -496,10 +1169,30 @@ const createControllerRegistry = (patterns, root) => {
496
1169
  };
497
1170
  };
498
1171
 
1172
+ const createResolverRegistry = (patterns, root) => {
1173
+ const resolversByFile = /* @__PURE__ */ new Map();
1174
+ const refresh = () => {
1175
+ resolversByFile.clear();
1176
+ const files = discoverFiles(patterns, root);
1177
+ const { resolvers, diagnostics } = analyzeResolvers(files);
1178
+ for (const resolver of resolvers) {
1179
+ resolversByFile.set(normalizePath(resolver.sourceFile), resolver);
1180
+ }
1181
+ return { resolvers, diagnostics };
1182
+ };
1183
+ return {
1184
+ refresh,
1185
+ get: (filePath) => resolversByFile.get(filePath),
1186
+ has: (filePath) => resolversByFile.has(filePath),
1187
+ all: () => [...resolversByFile.values()]
1188
+ };
1189
+ };
1190
+
499
1191
  const nestBridge = (options) => {
500
1192
  const resolvedOptions = resolveNestBridgeOptions(options);
501
1193
  let viteConfig;
502
- let registry;
1194
+ let controllerRegistry;
1195
+ let resolverRegistry;
503
1196
  const log = (message) => {
504
1197
  if (resolvedOptions.debug) {
505
1198
  console.log(`[nestbridge] ${message}`);
@@ -522,18 +1215,22 @@ const nestBridge = (options) => {
522
1215
  }
523
1216
  };
524
1217
  const runAnalysis = (reporter) => {
525
- const { controllers, diagnostics } = registry.refresh();
526
- reportDiagnostics(diagnostics, reporter);
1218
+ const { controllers, diagnostics: controllerDiagnostics } = controllerRegistry.refresh();
1219
+ const { resolvers, diagnostics: resolverDiagnostics } = resolverRegistry.refresh();
1220
+ reportDiagnostics([...controllerDiagnostics, ...resolverDiagnostics], reporter);
527
1221
  writeControllerDeclarations(controllers, viteConfig.root, resolvedOptions.outputDir);
528
- log(`analyzed ${controllers.length} controller(s), ${diagnostics.length} diagnostic(s)`);
529
- return controllers;
1222
+ writeResolverDeclarations(resolvers, viteConfig.root, resolvedOptions.outputDir);
1223
+ log(
1224
+ `analyzed ${controllers.length} controller(s), ${resolvers.length} resolver(s), ${controllerDiagnostics.length + resolverDiagnostics.length} diagnostic(s)`
1225
+ );
530
1226
  };
531
1227
  return {
532
1228
  name: "nestbridge",
533
1229
  enforce: "pre",
534
1230
  configResolved(config) {
535
1231
  viteConfig = config;
536
- registry = createControllerRegistry(resolvedOptions.controllers, config.root);
1232
+ controllerRegistry = createControllerRegistry(resolvedOptions.controllers, config.root);
1233
+ resolverRegistry = createResolverRegistry(resolvedOptions.resolvers, config.root);
537
1234
  },
538
1235
  buildStart() {
539
1236
  runAnalysis(this);
@@ -547,38 +1244,42 @@ const nestBridge = (options) => {
547
1244
  return null;
548
1245
  }
549
1246
  const absolutePath = normalizePath(resolved.id);
550
- if (!registry.has(absolutePath)) {
551
- return null;
1247
+ if (controllerRegistry.has(absolutePath)) {
1248
+ return resolvedControllerVirtualId(encodeControllerVirtualId(absolutePath));
1249
+ }
1250
+ if (resolverRegistry.has(absolutePath)) {
1251
+ return resolvedResolverVirtualId(encodeResolverVirtualId(absolutePath));
552
1252
  }
553
- return resolvedControllerVirtualId(encodeControllerVirtualId(absolutePath));
1253
+ return null;
554
1254
  },
555
1255
  load(id) {
556
- if (!isResolvedControllerVirtualId(id)) {
557
- return null;
1256
+ if (isResolvedControllerVirtualId(id)) {
1257
+ const controller = controllerRegistry.get(decodeControllerVirtualId(id));
1258
+ return controller === void 0 ? null : generateControllerModule(controller);
1259
+ }
1260
+ if (isResolvedResolverVirtualId(id)) {
1261
+ const resolver = resolverRegistry.get(decodeResolverVirtualId(id));
1262
+ return resolver === void 0 ? null : generateResolverModule(resolver);
558
1263
  }
559
- const controller = registry.get(decodeControllerVirtualId(id));
560
- return controller === void 0 ? null : generateControllerModule(controller);
1264
+ return null;
561
1265
  },
562
1266
  handleHotUpdate(ctx) {
563
1267
  const normalizedFile = normalizePath(ctx.file);
564
- const matchedBefore = registry.has(normalizedFile);
565
- const matchesNow = discoverControllerFiles(
566
- resolvedOptions.controllers,
567
- viteConfig.root
568
- ).includes(normalizedFile);
1268
+ const matchedBefore = controllerRegistry.has(normalizedFile) || resolverRegistry.has(normalizedFile);
1269
+ const matchesNow = discoverFiles(resolvedOptions.controllers, viteConfig.root).includes(normalizedFile) || discoverFiles(resolvedOptions.resolvers, viteConfig.root).includes(normalizedFile);
569
1270
  if (!matchedBefore && !matchesNow) {
570
1271
  return void 0;
571
1272
  }
572
1273
  runAnalysis(devReporter);
573
- log(`controller changed: ${normalizedFile}`);
574
- const virtualId = resolvedControllerVirtualId(encodeControllerVirtualId(normalizedFile));
1274
+ log(`nestbridge source changed: ${normalizedFile}`);
1275
+ const virtualId = controllerRegistry.has(normalizedFile) ? resolvedControllerVirtualId(encodeControllerVirtualId(normalizedFile)) : resolvedResolverVirtualId(encodeResolverVirtualId(normalizedFile));
575
1276
  const moduleNode = ctx.server.moduleGraph.getModuleById(virtualId);
576
1277
  return moduleNode === void 0 ? void 0 : [moduleNode, ...ctx.modules];
577
1278
  }
578
1279
  };
579
1280
  };
580
1281
 
581
- const version = "0.1.0";
1282
+ const version = "1.0.0";
582
1283
 
583
1284
  const VERSION = version;
584
1285