/// <summary>Initializes a new instance of the <see cref="ExtensionCode"/> class.</summary> /// <param name="code">The code.</param> /// <param name="extendedClasses">The list of extended class names.</param> public TypeScriptExtensionCode(string code, string[] extendedClasses) { code = code.Replace("\r", string.Empty); code = Regex.Replace(code, "import generated = (.*?)\\n", string.Empty, RegexOptions.Multiline); code = Regex.Replace(code, "import (.*?) = (.*?)\\n", match => { CodeBefore += ConversionUtilities.TrimWhiteSpaces(match.Groups[0].Value) + "\n"; return(string.Empty); }, RegexOptions.Multiline); CodeBefore = ConversionUtilities.TrimWhiteSpaces(CodeBefore); code = Regex.Replace(code, "(export )?class (.*?) ([\\s\\S]*?)\\n}", match => { var className = match.Groups[2].Value; if (extendedClasses?.Contains(className) == true) { Classes[className] = (match.Groups[1].Success ? match.Groups[0].Value : "export " + match.Groups[0].Value).Replace("generated.", string.Empty); return(string.Empty); } return(match.Groups[0].Value); }, RegexOptions.Multiline); CodeAfter = ConversionUtilities.TrimWhiteSpaces(code); }
/// <summary>Initializes a new instance of the <see cref="ExtensionCode"/> class.</summary> /// <param name="code">The code.</param> /// <param name="extendedClasses">The list of extended class names.</param> public TypeScriptExtensionCode(string code, string[] extendedClasses) { code = code .Replace("\r", string.Empty) .Replace("generated.", string.Empty); // Remove "generated" imports code = Regex.Replace(code, "import generated (=|from) (.*?)\\n", string.Empty, RegexOptions.Multiline); code = Regex.Replace(code, "import \\* as generated from (.*?)\\n", string.Empty, RegexOptions.Multiline); // Add other imports to CodeBefore code = Regex.Replace(code, "(import (.*?) (=|from) (.*?)\\n)|(/// <reference path(.*?)\\n)", match => { CodeBefore += ConversionUtilities.TrimWhiteSpaces(match.Groups[0].Value) + "\n"; return(string.Empty); }, RegexOptions.Multiline); CodeBefore = ConversionUtilities.TrimWhiteSpaces(CodeBefore); code = Regex.Replace(code, "(export )?class (.*?) ([\\s\\S]*?)\\n}", match => { var className = match.Groups[2].Value; if (extendedClasses?.Contains(className) == true) { Classes[className] = match.Groups[1].Success ? match.Groups[0].Value : "export " + match.Groups[0].Value; return(string.Empty); } return(match.Groups[0].Value); }, RegexOptions.Multiline); CodeAfter = ConversionUtilities.TrimWhiteSpaces(code); }
/// <summary>Generates the file.</summary> /// <returns>The file contents.</returns> public override string GenerateFile() { var output = GenerateType(_resolver.GenerateTypeName()).Code + "\n\n" + _resolver.GenerateTypes() + "\n\n" + Settings.TransformedExtensionCode + "\n\n"; return(ConversionUtilities.TrimWhiteSpaces(output)); }
internal List <OperationModel> GetOperations <TGenerator>(SwaggerService service, TypeResolverBase <TGenerator> resolver) where TGenerator : TypeGeneratorBase { service.GenerateOperationIds(); var operations = service.Paths .SelectMany(pair => pair.Value.Select(p => new { Path = pair.Key.Trim('/'), HttpMethod = p.Key, Operation = p.Value })) .Select(tuple => { var operation = tuple.Operation; var responses = operation.Responses.Select(response => new ResponseModel(response, this)).ToList(); var defaultResponse = responses.SingleOrDefault(r => r.StatusCode == "default"); if (defaultResponse != null) { responses.Remove(defaultResponse); } return(new OperationModel { Path = tuple.Path, HttpMethod = tuple.HttpMethod, Operation = tuple.Operation, OperationName = BaseSettings.OperationNameGenerator.GetOperationName(service, tuple.Path, tuple.HttpMethod, tuple.Operation), ResultType = GetResultType(operation), HasResultType = HasResultType(operation), ResultDescription = GetResultDescription(operation), ExceptionType = GetExceptionType(operation), HasFormParameters = operation.Parameters.Any(p => p.Kind == SwaggerParameterKind.FormData), Responses = responses, DefaultResponse = defaultResponse, Parameters = operation.Parameters.Select(p => { if (p.ActualSchema.Type == JsonObjectType.File) { p.ActualSchema.Type = JsonObjectType.String; // TODO: Implement File type handling } return new ParameterModel { Schema = p.ActualSchema, Name = p.Name, VariableNameLower = ConversionUtilities.ConvertToLowerCamelCase(p.Name.Replace("-", "_").Replace(".", "_")), Kind = p.Kind, IsRequired = p.IsRequired, Type = ResolveParameterType(p, resolver), IsLast = operation.Parameters.LastOrDefault() == p, Description = ConversionUtilities.TrimWhiteSpaces(p.Description) }; }).ToList(), }); }).ToList(); return(operations); }
internal string GetResultDescription(SwaggerOperation operation) { var response = GetSuccessResponse(operation); if (response != null) { return(ConversionUtilities.TrimWhiteSpaces(response.Description)); } return(null); }
/// <summary>Generates the file.</summary> /// <returns>The file contents.</returns> protected override string GenerateFile(CodeArtifactCollection artifactCollection) { var model = new FileTemplateModel(Settings) { Types = artifactCollection.Concatenate(), ExtensionCode = (TypeScriptExtensionCode)artifactCollection.ExtensionCode }; var template = Settings.TemplateFactory.CreateTemplate("TypeScript", "File", model); return(ConversionUtilities.TrimWhiteSpaces(template.Render())); }
/// <summary>Generates the file.</summary> /// <returns>The file contents.</returns> protected override string GenerateFile(IEnumerable <CodeArtifact> artifacts) { var model = new FileTemplateModel(Settings) { Types = artifacts.OrderByBaseDependency().Concatenate(), ExtensionCode = _extensionCode }; var template = Settings.TemplateFactory.CreateTemplate("TypeScript", "File", model); return(ConversionUtilities.TrimWhiteSpaces(template.Render())); }
/// <summary>Generates the file.</summary> /// <returns>The file contents.</returns> public override string GenerateFile() { var classes = GenerateType(_resolver.GenerateTypeName()).Code + "\n\n" + _resolver.GenerateTypes(); var template = new FileTemplate() as ITemplate; template.Initialize(new FileTemplateModel { Namespace = Settings.Namespace ?? string.Empty, Classes = ConversionUtilities.TrimWhiteSpaces(classes) }); return(template.Render()); }
/// <inheritdoc /> protected override string GenerateFile(CodeArtifactCollection artifactCollection) { var model = new FileTemplateModel { Namespace = Settings.Namespace ?? string.Empty, TypesCode = artifactCollection.Concatenate() }; var template = Settings.TemplateFactory.CreateTemplate("CSharp", "File", model); return(ConversionUtilities.TrimWhiteSpaces(template.Render())); }
/// <summary>Generates the file.</summary> /// <param name="rootTypeNameHint">The root type name hint.</param> /// <returns>The file contents.</returns> public override string GenerateFile(string rootTypeNameHint) { _resolver.Resolve(_schema, false, rootTypeNameHint); // register root type var model = new FileTemplateModel { Namespace = Settings.Namespace ?? string.Empty, Classes = ConversionUtilities.TrimWhiteSpaces(_resolver.GenerateClasses()) }; var template = Settings.TemplateFactory.CreateTemplate("CSharp", "File", model); return(ConversionUtilities.TrimWhiteSpaces(template.Render())); }
/// <summary>Generates the file.</summary> /// <returns>The file contents.</returns> public override string GenerateFile() { _resolver.Resolve(_schema, false, string.Empty); // register root type var template = new FileTemplate() as ITemplate; template.Initialize(new FileTemplateModel { Toolchain = JsonSchema4.ToolchainVersion, Namespace = Settings.Namespace ?? string.Empty, Classes = ConversionUtilities.TrimWhiteSpaces(_resolver.GenerateTypes(null)) }); return(ConversionUtilities.TrimWhiteSpaces(template.Render())); }
/// <summary>Generates the file.</summary> /// <param name="rootTypeNameHint">The root type name hint.</param> /// <returns>The file contents.</returns> public override string GenerateFile(string rootTypeNameHint) { _resolver.Resolve(_schema, false, rootTypeNameHint); // register root type var extensionCode = new TypeScriptExtensionCode(Settings.ExtensionCode, Settings.ExtendedClasses); var model = new FileTemplateModel(Settings) { Types = ConversionUtilities.TrimWhiteSpaces(_resolver.GenerateTypes(extensionCode)), ExtensionCode = extensionCode }; var template = Settings.TemplateFactory.CreateTemplate("TypeScript", "File", model); return(ConversionUtilities.TrimWhiteSpaces(template.Render())); }
/// <summary>Generates the file.</summary> /// <returns>The file contents.</returns> public override string GenerateFile() { _resolver.Resolve(_schema, false, string.Empty); // register root type var model = new FileTemplateModel(Settings) { Types = ConversionUtilities.TrimWhiteSpaces(_resolver.GenerateTypes(Settings.ProcessedExtensionCode)), ExtensionCodeBefore = Settings.ProcessedExtensionCode.CodeBefore, ExtensionCodeAfter = Settings.ProcessedExtensionCode.CodeAfter }; var template = Settings.TemplateFactory.CreateTemplate("TypeScript", "File", model); return(ConversionUtilities.TrimWhiteSpaces(template.Render())); }
/// <summary>Generates the file.</summary> /// <returns>The file contents.</returns> public override string GenerateFile() { _resolver.Resolve(_schema, false, string.Empty); // register root type var template = new FileTemplate() as ITemplate; template.Initialize(new FileTemplateModel { Types = ConversionUtilities.TrimWhiteSpaces(_resolver.GenerateTypes(Settings.ProcessedExtensionCode)), HasModuleName = !string.IsNullOrEmpty(Settings.ModuleName), ModuleName = Settings.ModuleName, ExtensionCodeBefore = Settings.ProcessedExtensionCode.CodeBefore, ExtensionCodeAfter = Settings.ProcessedExtensionCode.CodeAfter }); return(ConversionUtilities.TrimWhiteSpaces(template.Render())); }
/// <summary>Initializes a new instance of the <see cref="ExtensionCode" /> class.</summary> /// <param name="code">The code.</param> /// <param name="extendedClasses">The extended classes.</param> /// <param name="baseClasses">The base classes.</param> public TypeScriptExtensionCode(string code, string[] extendedClasses, string[] baseClasses = null) { code = code .Replace("\r", string.Empty) .Replace("generated.", string.Empty) + "\n"; code = Regex.Replace(code, "import generated (=|from) (.*?)\\n", string.Empty, RegexOptions.Multiline); code = Regex.Replace(code, "import \\* as generated from (.*?)\\n", string.Empty, RegexOptions.Multiline); code = Regex.Replace(code, "(import ((.|\\n)*?) (=|from) (.*?)\\n)|(/// <reference path(.*?)\\n)", match => { var importCode = ConversionUtilities.TrimWhiteSpaces(match.Groups[0].Value); if (!importCode.ToLowerInvariant().Contains("// ignore")) { ImportCode += importCode + "\n"; } return(string.Empty); }, RegexOptions.Multiline); code = Regex.Replace(code, "(@.*\r?\n)?(export )?class (.*?) ([\\s\\S]*?)\\n}", match => { var hasExport = match.Groups[2].Success; var className = match.Groups[3].Value; var classCode = hasExport ? match.Groups[0].Value : match.Groups[0].Value.Replace("class ", "export class "); if (extendedClasses?.Contains(className) == true) { ExtensionClasses[className] = classCode; return(string.Empty); } if (baseClasses?.Contains(className) == true) { TopCode += classCode + "\n\n"; return(string.Empty); } return(match.Groups[0].Value); }, RegexOptions.Multiline); ImportCode = ConversionUtilities.TrimWhiteSpaces(ImportCode); TopCode = ConversionUtilities.TrimWhiteSpaces(TopCode); BottomCode = ConversionUtilities.TrimWhiteSpaces(code.Trim()); }
/// <summary>Initializes a new instance of the <see cref="ExtensionCode" /> class.</summary> /// <param name="code">The code.</param> /// <param name="extendedClasses">The extended classes.</param> /// <param name="baseClasses">The base classes.</param> public TypeScriptExtensionCode(string code, string[] extendedClasses, string[] baseClasses = null) { code = code .Replace("\r", string.Empty) .Replace("generated.", string.Empty); code = Regex.Replace(code, "import generated (=|from) (.*?)\\n", string.Empty, RegexOptions.Multiline); code = Regex.Replace(code, "import \\* as generated from (.*?)\\n", string.Empty, RegexOptions.Multiline); code = Regex.Replace(code, "(import (.*?) (=|from) (.*?)\\n)|(/// <reference path(.*?)\\n)", match => { ImportCode += ConversionUtilities.TrimWhiteSpaces(match.Groups[0].Value) + "\n"; return(string.Empty); }, RegexOptions.Multiline); code = Regex.Replace(code, "(export )?class (.*?) ([\\s\\S]*?)\\n}", match => { var className = match.Groups[2].Value; if (extendedClasses?.Contains(className) == true) { ExtensionClasses[className] = match.Groups[1].Success ? match.Groups[0].Value : "export " + match.Groups[0].Value; return(string.Empty); } if (baseClasses?.Contains(className) == true) { TopCode += (match.Groups[1].Success ? match.Groups[0].Value : "export " + match.Groups[0].Value) + "\n\n"; return(string.Empty); } return(match.Groups[0].Value); }, RegexOptions.Multiline); ImportCode = ConversionUtilities.TrimWhiteSpaces(ImportCode); TopCode = ConversionUtilities.TrimWhiteSpaces(TopCode); BottomCode = ConversionUtilities.TrimWhiteSpaces(code); }
public async Task CreateClient(TextWriter writer) { var interfacesToWrite = new InterfaceManager(); writer.WriteLine( @"import * as hal from 'htmlrapier.halcyon/src/EndpointClient'; import { Fetcher } from 'htmlrapier/src/fetcher';" ); await WriteClient(interfacesToWrite, writer); //Write interfaces, kind of weird, no good docs for this var settings = new TypeScriptGeneratorSettings() { TypeStyle = TypeScriptTypeStyle.Interface, ForceAllPropertiesOptional = true, DateTimeType = TypeScriptDateTimeType.String, EnumNameGenerator = new EnumValueEnumNameGenerator(), }; //Gather up everything to write, skip duplicate instances of the same thing Dictionary <String, CodeArtifact> codeArtifacts = new Dictionary <String, CodeArtifact>(); ExtensionCode lastExtensionCode = null; foreach (var item in interfacesToWrite.Interfaces) { //Remove any properties from item that are hal embeds var propertiesToRemove = item.Value.Properties.Where(i => i.Value.IsHalEmbedded()).ToList(); foreach (var remove in propertiesToRemove) { item.Value.Properties.Remove(remove.Key); } var resolver = new TypeScriptTypeResolver(settings); resolver.RegisterSchemaDefinitions(new Dictionary <String, JsonSchema4>() { { item.Key, item.Value } }); //Add all discovered generators var generator = new TypeScriptGenerator(item.Value, settings, resolver); var artifacts = generator.GenerateTypes(); foreach (var artifact in artifacts.Artifacts) { if (!codeArtifacts.ContainsKey(artifact.TypeName)) { codeArtifacts.Add(artifact.TypeName, artifact); } } lastExtensionCode = artifacts.ExtensionCode; } //Write the classes officially //From TypeScriptGenerator.cs GenerateFile, (NJsonSchema 9.10.49) var model = new FileTemplateModel(settings) { Types = ConversionUtilities.TrimWhiteSpaces(string.Join("\n\n", CodeArtifactCollection.OrderByBaseDependency(codeArtifacts.Values).Select(p => p.Code))), ExtensionCode = (TypeScriptExtensionCode)lastExtensionCode }; var template = settings.TemplateFactory.CreateTemplate("TypeScript", "File", model); var classes = ConversionUtilities.TrimWhiteSpaces(template.Render()); writer.WriteLine(classes); //Write out common interfaces we reuse in all clients writer.WriteLine(@" export interface HalEndpointDocQuery { includeRequest?: boolean; includeResponse?: boolean; }"); //End Write Interfaces }
public async Task CreateClient(TextWriter writer) { var interfacesToWrite = new InterfaceManager(); writer.WriteLine( $@"using Threax.AspNetCore.Halcyon.Client; using System.Threading.Tasks; using System.Collections.Generic; using System.Net.Http; using System.Linq; namespace {options.Namespace} {{" ); await WriteClient(interfacesToWrite, writer); writer.WriteLine("}"); //Write interfaces, kind of weird, no good docs for this var settings = new CSharpGeneratorSettings() { Namespace = options.Namespace, GenerateDataAnnotations = false, ClassStyle = CSharpClassStyle.Poco, RequiredPropertiesMustBeDefined = false, EnumNameGenerator = new EnumValueEnumNameGenerator(), ArrayType = "List" //This is imported in the using statements above (System.Collections.Generic.List) }; //Gather up everything to write, skip duplicate instances of the same thing Dictionary <String, CodeArtifact> codeArtifacts = new Dictionary <String, CodeArtifact>(); foreach (var item in interfacesToWrite.Interfaces) { //Remove any properties from item that are hal embeds var propertiesToRemove = item.Value.Properties.Where(i => i.Value.IsHalEmbedded()).ToList(); foreach (var remove in propertiesToRemove) { item.Value.Properties.Remove(remove.Key); } var resolver = new CSharpTypeResolver(settings); resolver.RegisterSchemaDefinitions(new Dictionary <String, JsonSchema4>() { { item.Key, item.Value } }); //Add all discovered generators var generator = new CSharpGenerator(item.Value, settings, resolver); var artifacts = generator.GenerateTypes(); foreach (var artifact in artifacts.Artifacts) { if (!codeArtifacts.ContainsKey(artifact.TypeName)) { codeArtifacts.Add(artifact.TypeName, artifact); } } } //Write the classes officially //From TypeScriptGenerator.cs GenerateFile, (NJsonSchema 9.10.49) var model = new FileTemplateModel() { Namespace = settings.Namespace ?? string.Empty, TypesCode = ConversionUtilities.TrimWhiteSpaces(string.Join("\n\n", CodeArtifactCollection.OrderByBaseDependency(codeArtifacts.Values).Select(p => p.Code))), }; var template = settings.TemplateFactory.CreateTemplate("CSharp", "File", model); var classes = ConversionUtilities.TrimWhiteSpaces(template.Render()); writer.WriteLine(classes); //End Write Interfaces }
public string Render() { return(ConversionUtilities.TrimWhiteSpaces(TransformText())); }
/// <summary>Concatenates the results.</summary> /// <returns>The result.</returns> public string Concatenate() { return(ConversionUtilities.TrimWhiteSpaces(string.Join("\n\n", Artifacts.Select(p => p.Code)))); }