Beispiel #1
0
        private void AppendInterfaceDef(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            AddNamespaceHeaderEnum(classModel.Name, classModel.Type.Assembly.FullName, sb);

            var typeName   = this.GetTypeName(classModel);
            var visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            _docAppender.AppendClassDoc(sb, classModel, typeName);

            sb.AppendFormatIndented("{0}interface {1}", visibility, typeName);
            if (classModel.BaseType != null)
            {
                sb.AppendFormat(" extends {0}", this.GetFullyQualifiedTypeName(classModel.BaseType));
            }

            var interfaces = classModel.Interfaces.Where(m => CsharpTypeInfoProvider.ExposedInterfaces.Contains(m.Type)).ToList();

            if (interfaces.Count > 0)
            {
                var implementations = interfaces.Select(GetFullyQualifiedTypeName).ToArray();
                var prefixFormat    = " implements {0}";

                sb.AppendFormat(prefixFormat, string.Join(" ,", implementations));
            }

            sb.AppendLine(" {");

            GenerateProperties(classModel, sb, generatorOutput);

            sb.AppendLineIndented("}");
            _generatedClasses.Add(classModel);
        }
        /// <summary>
        /// Generates TypeScript definitions for classes and/or enums in the model.
        /// </summary>
        /// <param name="model">The code model with classes to generate definitions for.</param>
        /// <param name="generatorOutput">The type of definitions to generate</param>
        /// <returns>TypeScript definitions for classes and/or enums in the model..</returns>
        public string Generate(TsModel model, TsGeneratorOutput generatorOutput)
        {
            var sb = new ScriptBuilder(this.IndentationString);

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties ||
                (generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                if ((generatorOutput & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants)
                {
                    // We can't generate constants together with properties or fields, because we can't set values in a .d.ts file.
                    throw new InvalidOperationException("Cannot generate constants together with properties or fields");
                }

                foreach (var reference in _references.Concat(model.References))
                {
                    this.AppendReference(reference, sb);
                }
                sb.AppendLine();
            }

            // We can't just sort by the module name, because a formatter can jump in and change it so
            // format by the desired target name
            foreach (var module in model.Modules.OrderBy(m => GetModuleName(m)))
            {
                this.AppendModule(module, sb, generatorOutput);
            }

            return(sb.ToString());
        }
        /// <summary>
        /// Generates TypeScript definitions for classes and/or enums in the model.
        /// </summary>
        /// <param name="model">The code model with classes to generate definitions for.</param>
        /// <param name="generatorOutput">The type of definitions to generate</param>
        /// <returns>TypeScript definitions for classes and/or enums in the model..</returns>
        public string Generate(TsModel model, TsGeneratorOutput generatorOutput)
        {
            var sb = new ScriptBuilder(this.IndentationString);

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties ||
                (generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                if ((generatorOutput & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants)
                {
                    // We can't generate constants together with properties or fields, because we can't set values in a .d.ts file.
                    throw new InvalidOperationException("Cannot generate constants together with properties or fields");
                }

                foreach (var reference in _references.Concat(model.References))
                {
                    this.AppendReference(reference, sb);
                }
                sb.AppendLine();
            }

            foreach (var module in model.Modules)
            {
                this.AppendModule(module, sb, generatorOutput);
            }

            return(sb.ToString());
        }
Beispiel #4
0
        private void GenerateProperties(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }

            using (sb.IncreaseIndentation())
            {
                foreach (var property in members)
                {
                    if (property.IsIgnored ||
                        PropertyTypesToIgnore(property.PropertyType.Type) ||
                        (_typesPropertiesToIgnore.ContainsKey(classModel.Type) && _typesPropertiesToIgnore[classModel.Type].Contains(property.Name)))
                    {
                        continue;
                    }

                    AddDocCommentForCustomJsonConverter(sb, property);
                    _docAppender.AppendPropertyDoc(sb, property, this.GetPropertyName(property), this.GetPropertyType(property));
                    sb.AppendLineIndented($"{this.GetPropertyName(property)}: {this.GetPropertyType(property)};");
                }

                if (classModel.Type == typeof(PropertyBase))
                {
                    sb.AppendLineIndented($"type: string;");
                }
            }
        }
        public static string GetTypeLitePocos(this IEnumerable <Type> types, TsGeneratorOutput output, bool useNamespace = true, bool isExported = true)
        {
            var replacements = new List <string>();
            var def          = TypeScript.Definitions();

            foreach (var type in types)
            {
                def.For(type);
                var r = type.DeclaringType?.FullName;
                if (r != null && string.IsNullOrEmpty(type.Namespace))
                {
                    replacements.Add(r);
                }
            }
            var script = def.Generate(output);

            if (isExported)
            {
                script = script.Replace("interface ", "export interface ");
            }
            if (useNamespace)
            {
                script = script.Replace("declare module ", "namespace ");
            }
            return(script);
        }
Beispiel #6
0
        private void GenerateModuleContent(ScriptBuilder sb, TsGeneratorOutput generatorOutput, List <TsClass> classes, List <TsEnum> enums)
        {
            if ((generatorOutput & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums)
            {
                foreach (var enumModel in enums)
                {
                    this.AppendEnumDefinition(enumModel, sb, generatorOutput);
                }
            }

            if (((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties) ||
                (generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                foreach (var classModel in classes)
                {
                    this.AppendClassDefinition(classModel, sb, generatorOutput);
                }
            }

            if ((generatorOutput & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants)
            {
                foreach (var classModel in classes)
                {
                    if (classModel.IsIgnored)
                    {
                        continue;
                    }

                    this.AppendConstantModule(classModel, sb);
                }
            }
        }
        public static string GetTypeLitePoco(this Type type, TsGeneratorOutput output, bool useNamespace = true, bool isExported = true)
        {
            var name = type.DeclaringType?.FullName;
            var poco = TypeScript.Definitions().For(type).Generate(output);

            if (isExported)
            {
                poco = poco.Replace("interface ", " export interface ");
            }
            if (useNamespace)
            {
                poco = poco.Replace("declare module ", "namespace ");
            }
            return(poco);
        }
        protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            string typeName = this.GetTypeName(classModel);
            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";
            sb.AppendFormatIndented(
                "{0}class {1} extends {2}",
                visibility,
                typeName,
                //all bottom-level classes must extend Backbone.Model.
                classModel.BaseType != null ? this.GetFullyQualifiedTypeName(classModel.BaseType) : "Backbone.Model");

            sb.AppendLine(" {");

            var members = new List<TsProperty>();
            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (var property in members)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }

                    sb.AppendLineIndented(string.Format(
                        "get {0}(): {1} {{ return this.get(\"{0}\"); }}",
                        this.GetPropertyName(property), this.GetPropertyType(property)));

                    sb.AppendLineIndented(string.Format(
                        "set {0}(v: {1}) {{ this.set(\"{0}\", v); }}",
                        this.GetPropertyName(property), this.GetPropertyType(property)));
                }
            }

            sb.AppendLineIndented("}");

            _generatedClasses.Add(classModel);
        }
Beispiel #9
0
        protected virtual void AppendModule(TsModule module, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            List <TsClass> classesByName = module.Classes.Where(c => !_typeConvertors.IsConvertorRegistered(c.Type) && !c.IsIgnored).OrderBy(c => GetTypeName(c)).ToList();
            List <TsClass> classes       = SortByDependency(classesByName);

            var enums = module.Enums.Where(e => !_typeConvertors.IsConvertorRegistered(e.Type) && !e.IsIgnored).OrderBy(e => GetTypeName(e)).ToList();

            if ((generatorOutput == TsGeneratorOutput.Enums && enums.Count == 0) ||
                (generatorOutput == TsGeneratorOutput.Properties && classes.Count == 0) ||
                (enums.Count == 0 && classes.Count == 0))
            {
                return;
            }

            if (generatorOutput == TsGeneratorOutput.Constants && !classes.Any(c => c.Constants.Any()))
            {
                return;
            }

            var moduleName           = GetModuleName(module);
            var generateModuleHeader = moduleName != string.Empty;

            if (generateModuleHeader)
            {
                if (generatorOutput != TsGeneratorOutput.Enums &&
                    (generatorOutput & TsGeneratorOutput.Constants) != TsGeneratorOutput.Constants)
                {
                    sb.Append(Mode == TsGenerationModes.Definitions ? "declare " : " export ");
                }

                sb.AppendLine($"{(Mode == TsGenerationModes.Definitions ? "namespace" : "module")} {moduleName} {{");

                using (sb.IncreaseIndentation())
                {
                    GenerateModuleContent(sb, generatorOutput, classes, enums);
                }

                sb.AppendLine("}");
            }
            else
            {
                GenerateModuleContent(sb, generatorOutput, classes, enums);
            }
        }
Beispiel #10
0
        private void AppendClassDef(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            AddNamespaceHeader(classModel.Name, sb);

            var typeName   = this.GetTypeName(classModel);
            var visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            AddRequestRenameInformation(sb, classModel);
            AddDocCommentForCustomJsonConverter(sb, classModel);
            _docAppender.AppendClassDoc(sb, classModel, typeName);

            sb.AppendFormatIndented("{0}class {1}", visibility, typeName);
            if (CsharpTypeInfoProvider.StringAbstractions.Contains(classModel.Type))
            {
                sb.AppendLineIndented(" extends String {}");
                return;
            }

            void EnforceBaseClass <TInterface, TBase>()
            {
                if (classModel.BaseType != null)
                {
                    return;
                }
                if (classModel.Type == typeof(TBase))
                {
                    return;
                }
                if (typeof(TInterface).IsAssignableFrom(classModel.Type))
                {
                    classModel.BaseType = new TsClass(typeof(TBase));
                }
            }

            EnforceBaseClass <IAnalyzer, AnalyzerBase>();
            EnforceBaseClass <ITokenizer, TokenizerBase>();
            EnforceBaseClass <ITokenFilter, TokenFilterBase>();
            EnforceBaseClass <ICharFilter, CharFilterBase>();
            EnforceBaseClass <IProperty, PropertyBase>();
            EnforceBaseClass <IResponse, ResponseBase>();

            if (classModel.BaseType != null)
            {
                sb.AppendFormat(" extends {0}", this.GetFullyQualifiedTypeName(classModel.BaseType));
            }

            var interfaces = classModel.Interfaces.Where(m => CsharpTypeInfoProvider.ExposedInterfaces.Contains(m.Type)).ToList();

            if (interfaces.Count > 0)
            {
                var implementations = interfaces.Select(GetFullyQualifiedTypeName).ToArray();
                var prefixFormat    = " implements {0}";

                sb.AppendFormat(prefixFormat, string.Join(" ,", implementations));
            }

            sb.AppendLine(" {");

            GenerateProperties(classModel, sb, generatorOutput);

            sb.AppendLineIndented("}");
            _generatedClasses.Add(classModel);

            //generate a closed cat response type (NEST uses catresponse<TRecord> for all)
            if (typeof(ICatRecord).IsAssignableFrom(classModel.Type))
            {
                var catResponseName = classModel.Type.Name.Replace("Record", "Response");
                AddNamespaceHeader(classModel.Name, sb);
                sb.AppendLineIndented($"class {catResponseName} extends ResponseBase {{");
                using (sb.IncreaseIndentation())
                    sb.AppendLineIndented($"records: {typeName}[];");
                sb.AppendLineIndented("}");
            }
        }
Beispiel #11
0
        protected virtual void AppendEnumDefinition(TsEnum enumModel, ScriptBuilder sb, TsGeneratorOutput output)
        {
            string typeName   = this.GetTypeName(enumModel);
            string visibility = (output & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums || (output & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants ? "export " : "";

            _docAppender.AppendEnumDoc(sb, enumModel, typeName);

            string constSpecifier = this.GenerateConstEnums ? "const " : string.Empty;

            sb.AppendLineIndented(string.Format("{0}{2}enum {1} {{", visibility, typeName, constSpecifier));

            using (sb.IncreaseIndentation()) {
                int    i                = 1;
                string valuesList       = "";
                string descriptionsList = "";

                foreach (var v in enumModel.Values)
                {
                    _docAppender.AppendEnumValueDoc(sb, v);
                    bool appendComma = enumModel.IsOutputValuesList || enumModel.IsOutputDescriptionsList || (i < enumModel.Values.Count);
                    if (enumModel.IsValueAsStringOfName)
                    {
                        sb.AppendLineIndented(string.Format(appendComma ? "{0} = '{0}'," : "{0} = '{0}'", v.Name));
                        if (enumModel.IsOutputValuesList)
                        {
                            valuesList += string.Format((i < enumModel.Values.Count) ? "{0}|" : "{0}", v.Name);
                        }
                    }
                    else
                    {
                        sb.AppendLineIndented(string.Format(appendComma ? "{0} = {1}," : "{0} = {1}", v.Name, v.Value));
                        if (enumModel.IsOutputValuesList)
                        {
                            valuesList += string.Format(i < enumModel.Values.Count ? "{0}|" : "{0}", v.Value);
                        }
                    }
                    if (enumModel.IsOutputDescriptionsList)
                    {
                        descriptionsList += string.Format(i < enumModel.Values.Count ? "{0}|" : "{0}", v.Description);
                    }
                    i++;
                }
                if (enumModel.IsOutputValuesList)
                {
                    sb.AppendLineIndented(string.Format(enumModel.IsOutputDescriptionsList ? "_ValuesList = '{0}'," : "_ValuesList = '{0}'", valuesList));
                }
                if (enumModel.IsOutputDescriptionsList)
                {
                    sb.AppendLineIndented(string.Format("_DescriptionsList = '{0}'", descriptionsList));
                }
            }

            sb.AppendLineIndented("}");

            _generatedEnums.Add(enumModel);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="classModel"></param>
        /// <param name="sb"></param>
        /// <param name="generatorOutput"></param>
        protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            string typeName   = this.GetTypeName(classModel);
            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            sb.AppendFormatIndented("{0}interface {1}", visibility, typeName);
            if (classModel.BaseType != null)
            {
                sb.AppendFormat(" extends {0}", this.GetFullyQualifiedTypeName(classModel.BaseType));
            }
            sb.AppendLine(" {");
            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (var property in members)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }
                    var propTypeName = this.GetPropertyType(property);
                    if (property.PropertyType.IsCollection())
                    {
                        //Note: new member functon checking if property is collection or not
                        //Also remove the array brackets from the name
                        if (propTypeName.Length > 2 && propTypeName.Substring(propTypeName.Length - 2) == "[]")
                        {
                            propTypeName = propTypeName.Substring(0, propTypeName.Length - 2);
                        }
                        propTypeName = "KnockoutObservableArray<" + propTypeName + ">";
                    }
                    else
                    {
                        propTypeName = "KnockoutObservable<" + propTypeName + ">";
                    }
                    sb.AppendLineIndented(string.Format("{0}: {1};", this.GetPropertyName(property), propTypeName));
                }
            }
            sb.AppendLineIndented("}");
            _generatedClasses.Add(classModel);
        }
Beispiel #13
0
        protected virtual void AppendEnumDefinition(TsEnum enumModel, ScriptBuilder sb, TsGeneratorOutput output)
        {
            string typeName   = this.GetTypeName(enumModel);
            string visibility = (output & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums || (output & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants ? "export " : "";

            _docAppender.AppendEnumDoc(sb, enumModel, typeName);

            string constSpecifier = this.GenerateConstEnums ? "const " : string.Empty;

            sb.AppendLineIndented(string.Format("{0}{2}enum {1} {{", visibility, typeName, constSpecifier));

            using (sb.IncreaseIndentation()) {
                int i = 1;
                foreach (var v in enumModel.Values)
                {
                    _docAppender.AppendEnumValueDoc(sb, v);
                    sb.AppendLineIndented(string.Format(i < enumModel.Values.Count ? "{0} = {1}," : "{0} = {1}", v.Name, v.Value));
                    i++;
                }
            }

            sb.AppendLineIndented("}");

            _generatedEnums.Add(enumModel);
        }
Beispiel #14
0
 protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
 {
     base.AppendClassDefinition(classModel, sb, generatorOutput);
 }
Beispiel #15
0
 protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
 {
     if (classModel.Type.IsInterface && CsharpTypeInfoProvider.ExposedInterfaces.Contains(classModel.Type))
     {
         AppendInterfaceDef(classModel, sb, generatorOutput);
     }
     else
     {
         AppendClassDef(classModel, sb, generatorOutput);
     }
 }
Beispiel #16
0
        protected override void AppendEnumDefinition(TsEnum enumModel, ScriptBuilder sb, TsGeneratorOutput output)
        {
            if (!AddNamespaceHeaderEnum(enumModel.Name, enumModel.Type.Assembly.FullName, sb))
            {
                return;
            }
            if (_typesToIgnore.Contains(enumModel.Type))
            {
                return;
            }

            var typeName   = this.GetTypeName(enumModel);
            var visibility = string.Empty;

            _docAppender.AppendEnumDoc(sb, enumModel, typeName);

            var constSpecifier = this.GenerateConstEnums ? "const " : string.Empty;

            sb.AppendLineIndented(string.Format("{0}{2}enum {1} {{", visibility, typeName, constSpecifier));

            using (sb.IncreaseIndentation())
            {
                var i = 1;
                foreach (var v in enumModel.Values)
                {
                    _docAppender.AppendEnumValueDoc(sb, v);
                    var enumMemberAttribute = v.Field.GetCustomAttribute <EnumMemberAttribute>();
                    var name = (!string.IsNullOrEmpty(enumMemberAttribute?.Value) ? enumMemberAttribute.Value : v.Name).QuoteMaybe();

                    sb.AppendLineIndented(string.Format(i < enumModel.Values.Count ? "{0} = {1}," : "{0} = {1}", name, v.Value));
                    i++;
                }
            }

            sb.AppendLineIndented("}");

            _generatedEnums.Add(enumModel);
        }
 protected override void AppendEnumDefinition(TsEnum enumModel, ScriptBuilder sb, TsGeneratorOutput output)
 {
     base.AppendEnumDefinition(enumModel, sb, TsGeneratorOutput.Enums);
 }
Beispiel #18
0
        protected override void AppendModule(TsModule module, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            var classes = module.Classes.Where(c => !_typeConvertors.IsConvertorRegistered(c.Type) && !c.IsIgnored).ToList();
            var enums   = module.Enums.Where(e => !_typeConvertors.IsConvertorRegistered(e.Type) && !e.IsIgnored).ToList();

            if ((generatorOutput == TsGeneratorOutput.Enums && enums.Count == 0) ||
                (generatorOutput == TsGeneratorOutput.Properties && classes.Count == 0) ||
                (enums.Count == 0 && classes.Count == 0))
            {
                return;
            }

            if ((generatorOutput & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums)
            {
                foreach (var enumModel in enums)
                {
                    if (Ignore(enumModel))
                    {
                        continue;
                    }
                    this.AppendEnumDefinition(enumModel, sb, generatorOutput);
                }
            }

            if (((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties) ||
                (generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                var cc             = classes.Select(c => new { c, order = OrderTypes(c) }).ToList();
                var orderedClasses = cc.OrderBy(c => c.order).ToList();
                foreach (var oc in orderedClasses)
                {
                    var classModel = oc.c;
                    var t          = classModel.Type;
//					var x = $"// {oc.order} - {oc.c.Type.FullName}";
//					sb.AppendIndented(x);
                    if (t.IsInterface && !CsharpTypeInfoProvider.ExposedInterfaces.Contains(t) && CsharpTypeInfoProvider.ExposedInterfaces.Any(i => i.IsAssignableFrom(t)))
                    {
                        continue;
                    }
                    var c = ReMapClass(classModel);
                    if (Ignore(c))
                    {
                        continue;
                    }
                    if (this._appended.Contains(c.Name))
                    {
                        continue;
                    }
                    if (this._appended.Contains("I" + c.Name))
                    {
                        continue;
                    }
                    this.AppendClassDefinition(c, sb, generatorOutput);
                    this._appended.Add(c.Name);
                }
            }

            if ((generatorOutput & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants)
            {
                foreach (var classModel in classes)
                {
                    if (classModel.IsIgnored)
                    {
                        continue;
                    }

                    this.AppendConstantModule(classModel, sb);
                }
            }
        }
Beispiel #19
0
        protected virtual void AppendModule(TsModule module, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            var classes = module.Classes.Where(c => !_typeConvertors.IsConvertorRegistered(c.Type) && !c.IsIgnored).OrderBy(c => GetTypeName(c)).ToList();
            var enums   = module.Enums.Where(e => !_typeConvertors.IsConvertorRegistered(e.Type) && !e.IsIgnored).OrderBy(e => GetTypeName(e)).ToList();

            if ((generatorOutput == TsGeneratorOutput.Enums && enums.Count == 0) ||
                (generatorOutput == TsGeneratorOutput.Properties && classes.Count == 0) ||
                (enums.Count == 0 && classes.Count == 0))
            {
                return;
            }

            if (generatorOutput == TsGeneratorOutput.Properties && !classes.Any(c => c.Fields.Any() || c.Properties.Any()))
            {
                return;
            }

            if (generatorOutput == TsGeneratorOutput.Constants && !classes.Any(c => c.Constants.Any()))
            {
                return;
            }

            var moduleName           = GetModuleName(module);
            var generateModuleHeader = moduleName != string.Empty;

            if (generateModuleHeader)
            {
                if (generatorOutput != TsGeneratorOutput.Enums &&
                    (generatorOutput & TsGeneratorOutput.Constants) != TsGeneratorOutput.Constants)
                {
                    sb.Append("declare ");
                }

                sb.AppendLine(string.Format("namespace {0} {{", moduleName));
            }

            using (sb.IncreaseIndentation()) {
                if ((generatorOutput & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums)
                {
                    foreach (var enumModel in enums)
                    {
                        this.AppendEnumDefinition(enumModel, sb, generatorOutput);
                    }
                }

                if (((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties) ||
                    (generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
                {
                    foreach (var classModel in classes)
                    {
                        this.AppendClassDefinition(classModel, sb, generatorOutput);
                    }
                }

                if ((generatorOutput & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants)
                {
                    foreach (var classModel in classes)
                    {
                        if (classModel.IsIgnored)
                        {
                            continue;
                        }

                        this.AppendConstantModule(classModel, sb);
                    }
                }
            }
            if (generateModuleHeader)
            {
                sb.AppendLine("}");
            }
        }
Beispiel #20
0
        protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            if (classModel.Name == "ConnectionConfigurationValues")
            {
                return;
            }
            if (classModel.Name == "RequestData")
            {
                return;
            }
            if (classModel.Name == "ISortOrder")
            {
                return;
            }

            if (classModel.Type.IsInterface && CsharpTypeInfoProvider.ExposedInterfaces.Contains(classModel.Type))
            {
                AppendInterfaceDef(classModel, sb, generatorOutput);
            }
            else
            {
                AppendClassDef(classModel, sb, generatorOutput);
            }
        }
Beispiel #21
0
 protected override void AppendModule(TsModule module, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
 {
     base.AppendModule(module, sb, generatorOutput);
 }
        private void AppendKoInterfaceDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            string typeName   = this.GetTypeName(classModel);
            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            sb.AppendIndented($"{visibility}interface {typeName}");
            if (classModel.BaseType != null)
            {
                sb.Append($" extends {this.GetFullyQualifiedTypeName(classModel.BaseType)}");
            }
            sb.AppendLine(" {");
            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (TsProperty property in members)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }
                    string propTypeName = this.GetPropertyType(property);
                    if (IsCollection(property))
                    {
                        if (propTypeName.Length > 2 && propTypeName.Substring(propTypeName.Length - 2) == "[]")
                        {
                            propTypeName = propTypeName.Substring(0, propTypeName.Length - 2);
                        }
                        propTypeName = "ko.ObservableArray<" + propTypeName + ">";
                    }
                    else
                    {
                        propTypeName = "ko.Subscribable<" + propTypeName + ">";
                    }
                    sb.AppendLineIndented($"{this.GetPropertyName(property)}: {propTypeName};");
                }
            }
            sb.AppendLineIndented("}");
        }
        protected override void AppendModule(TsModule module, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            // Use reflection to grab the internal property which was removed!
            var typeConverters = (TypeConvertorCollection)_typeConvertersMember.GetValue(this);

            var classes = module.Classes.Where(c => !typeConverters.IsConvertorRegistered(c.Type) && !c.IsIgnored)
                          // .OrderBy(c => GetTypeName(c))			// Sorting breaks inheritance
                          .ToList();
            var baseClasses = classes
                              .Where(c => c.BaseType != null)
                              .Select(c => c.BaseType.Type.FullName)
                              .Distinct()
                              .OrderBy(c => c)
                              .ToList();
            var enums = module.Enums.Where(e => !typeConverters.IsConvertorRegistered(e.Type) && !e.IsIgnored).OrderBy(e => GetTypeName(e)).ToList();

            if ((generatorOutput == TsGeneratorOutput.Enums && enums.Count == 0) ||
                (generatorOutput == TsGeneratorOutput.Properties && classes.Count == 0) ||
                (enums.Count == 0 && classes.Count == 0))
            {
                return;
            }

            if (generatorOutput == TsGeneratorOutput.Properties && !classes.Any(c => c.Fields.Any() || c.Properties.Any()))
            {
                return;
            }

            if (generatorOutput == TsGeneratorOutput.Constants && !classes.Any(c => c.Constants.Any()))
            {
                return;
            }

            string moduleName           = GetModuleName(module);
            bool   generateModuleHeader = moduleName != string.Empty;

            if (generateModuleHeader)
            {
                if (generatorOutput != TsGeneratorOutput.Enums &&
                    (generatorOutput & TsGeneratorOutput.Constants) != TsGeneratorOutput.Constants)
                {
                    sb.Append(Mode == TsGenerationModes.Definitions ? "declare " : " export ");
                }

                sb.AppendLine($"{(Mode == TsGenerationModes.Definitions ? "namespace" : "module")} {moduleName} {{");
            }

            using (sb.IncreaseIndentation())
            {
                if ((generatorOutput & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums)
                {
                    foreach (TsEnum enumModel in enums)
                    {
                        this.AppendEnumDefinition(enumModel, sb, generatorOutput);
                    }
                }

                if (((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties) ||
                    (generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
                {
                    foreach (TsClass baseClassModel in classes.Where(c => baseClasses.Contains(c.Type.FullName)))
                    {
                        this.AppendClassDefinition(baseClassModel, sb, generatorOutput);
                    }
                }

                if (((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties) ||
                    (generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
                {
                    foreach (TsClass classModel in classes.Where(c => !baseClasses.Contains(c.Type.FullName)))
                    {
                        this.AppendClassDefinition(classModel, sb, generatorOutput);
                    }
                }

                if ((generatorOutput & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants)
                {
                    foreach (TsClass classModel in classes)
                    {
                        if (classModel.IsIgnored)
                        {
                            continue;
                        }

                        this.AppendConstantModule(classModel, sb);
                    }
                }
            }
            if (generateModuleHeader)
            {
                sb.AppendLine("}");
            }
        }
Beispiel #24
0
        /// <summary>
        /// Generates class definition and appends it to the output.
        /// </summary>
        /// <param name="classModel">The class to generate definition for.</param>
        /// <param name="sb">The output.</param>
        /// <param name="generatorOutput"></param>
        protected virtual void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            string typeName   = this.GetTypeName(classModel);
            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            _docAppender.AppendClassDoc(sb, classModel, typeName);
            sb.AppendFormatIndented("{0}interface {1}", visibility, typeName);
            if (classModel.BaseType != null)
            {
                sb.AppendFormat(" extends {0}", this.GetFullyQualifiedTypeName(classModel.BaseType));
            }

            if (classModel.Interfaces.Count > 0)
            {
                var implementations = classModel.Interfaces.Select(GetFullyQualifiedTypeName).ToArray();

                var prefixFormat = classModel.Type.IsInterface ? " extends {0}"
                    : classModel.BaseType != null ? " , {0}"
                    : " extends {0}";

                sb.AppendFormat(prefixFormat, string.Join(" ,", implementations));
            }

            sb.AppendLine(" {");

            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation()) {
                foreach (var property in members.Where(p => !p.IsIgnored).OrderBy(p => this.GetPropertyName(p)))
                {
                    _docAppender.AppendPropertyDoc(sb, property, this.GetPropertyName(property), this.GetPropertyType(property));
                    sb.AppendLineIndented(string.Format("{0}: {1};", this.GetPropertyName(property), this.GetPropertyType(property)));
                }
            }

            sb.AppendLineIndented("}");

            _generatedClasses.Add(classModel);
        }
        /// <summary>
        /// Appends the appropriate class definition for the specified member
        /// </summary>
        /// <param name="classModel"></param>
        /// <param name="sb"></param>
        /// <param name="generatorOutput"></param>
        protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            Tags.TryGetValue(classModel, out string tag);

            sb.AppendLineIndented($"// {classModel.Name} ({tag})");
            switch (tag)
            {
            case KoClass:
                AppendClassDefinition(classModel, sb, generatorOutput, true);
                break;

            case KoInterface:
                AppendKoInterfaceDefinition(classModel, sb, generatorOutput);
                break;

            case Poco:
                AppendClassDefinition(classModel, sb, generatorOutput, false);
                break;

            default:
                base.AppendClassDefinition(classModel, sb, generatorOutput);
                break;
            }

            _generatedClasses.Add(classModel);
        }
Beispiel #26
0
        protected override void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput)
        {
            string typeName   = this.GetTypeName(classModel);
            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            sb.AppendFormatIndented(
                "{0}class {1} extends {2}",
                visibility,
                typeName,
                //all bottom-level classes must extend Backbone.Model.
                classModel.BaseType != null ? this.GetFullyQualifiedTypeName(classModel.BaseType) : "Backbone.Model");

            sb.AppendLine(" {");

            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (var property in members)
                {
                    if (property.IsIgnored)
                    {
                        continue;
                    }

                    sb.AppendLineIndented(string.Format(
                                              "get {0}(): {1} {{ return this.get(\"{0}\"); }}",
                                              this.GetPropertyName(property), this.GetPropertyType(property)));

                    sb.AppendLineIndented(string.Format(
                                              "set {0}(v: {1}) {{ this.set(\"{0}\", v); }}",
                                              this.GetPropertyName(property), this.GetPropertyType(property)));
                }
            }

            sb.AppendLineIndented("}");

            _generatedClasses.Add(classModel);
        }
        private void AppendClassDefinition(TsClass classModel, ScriptBuilder sb, TsGeneratorOutput generatorOutput, bool ko)
        {
            string typeName = this.GetTypeName(classModel);

            string visibility = this.GetTypeVisibility(classModel, typeName) ? "export " : "";

            sb.AppendIndented($"{visibility}class {typeName}");
            if (classModel.BaseType != null)
            {
                string baseTypeName = this.GetFullyQualifiedTypeName(classModel.BaseType);
                if (baseTypeName.StartsWith(classModel.Module.Name + ".", StringComparison.Ordinal))
                {
                    baseTypeName = baseTypeName.Substring(classModel.Module.Name.Length + 1);
                }

                sb.Append($" extends {baseTypeName}");
                sb.AppendLine(" {");
                using (sb.IncreaseIndentation())
                {
                    sb.AppendLineIndented("constructor() {");
                    using (sb.IncreaseIndentation())
                    {
                        sb.AppendLineIndented("super();");
                    }
                    sb.AppendLineIndented("}");
                }
            }
            else
            {
                sb.AppendLine(" {");
            }
            var members = new List <TsProperty>();

            if ((generatorOutput & TsGeneratorOutput.Properties) == TsGeneratorOutput.Properties)
            {
                members.AddRange(classModel.Properties);
            }
            if ((generatorOutput & TsGeneratorOutput.Fields) == TsGeneratorOutput.Fields)
            {
                members.AddRange(classModel.Fields);
            }
            using (sb.IncreaseIndentation())
            {
                foreach (TsProperty property in members.Where(m => !m.IsIgnored))
                {
                    string propTypeName = this.GetPropertyType(property);
                    if (IsCollection(property))
                    {
                        if (propTypeName.EndsWith("[]", StringComparison.Ordinal))
                        {
                            propTypeName = propTypeName.Substring(0, propTypeName.Length - "[]".Length);
                        }
                        if (ko)
                        {
                            sb.AppendLineIndented($"{this.GetPropertyName(property)}: ko.ObservableArray<{propTypeName}> = ko.observableArray([]);");
                        }
                        else
                        {
                            sb.AppendLineIndented($"{this.GetPropertyName(property)}: {propTypeName}[];");
                        }
                    }
                    else
                    {
                        if (ko)
                        {
                            sb.AppendLineIndented($"{this.GetPropertyName(property)}: ko.Subscribable<{propTypeName}> = ko.observable(null);");
                        }
                        else
                        {
                            sb.AppendLineIndented($"{this.GetPropertyName(property)}: {propTypeName};");
                        }
                    }
                }
            }

            sb.AppendLineIndented("}");
            _generatedClasses.Add(classModel);
        }
Beispiel #28
0
        /// <summary>
        /// Generates TypeScript definitions for types included in this model builder. Optionally restricts output to classes or enums.
        /// </summary>
        /// <param name="output">The type of definitions to generate</param>
        /// <returns>TypeScript definition for types included in this model builder.</returns>
        public string Generate(TsGeneratorOutput output)
        {
            var model = _modelBuilder.Build();

            return(_scriptGenerator.Generate(model, output));
        }
        protected virtual void AppendEnumDefinition(TsEnum enumModel, IndentedStringBuilder sb, TsGeneratorOutput output)
        {
            var typeName   = GetTypeName(enumModel);
            var visibility = (output & TsGeneratorOutput.Enums) == TsGeneratorOutput.Enums || (output & TsGeneratorOutput.Constants) == TsGeneratorOutput.Constants ? "export " : "";

            DocAppender.AppendEnumDoc(sb, enumModel, typeName);

            var constSpecifier = Options.GenerateConstEnums ? "const " : string.Empty;

            sb.AppendLine(string.Format("{0}{2}enum {1} {{", visibility, typeName, constSpecifier));

            using (sb.Indent())
            {
                var i = 1;
                foreach (var v in enumModel.Values)
                {
                    DocAppender.AppendEnumValueDoc(sb, v);
                    sb.AppendLine(string.Format(i < enumModel.Values.Count ? "{0} = {1}," : "{0} = {1}", v.Name, v.Value));
                    i++;
                }
            }

            sb.AppendLine("}");

            GeneratedEnums.Add(enumModel);
        }