feat(dart): dart-next generator - #18970

Draft
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next
Draft

feat(dart): dart-next generator#18970
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next

Conversation

@ahmednfwela

@ahmednfwelaahmednfwela commented Jun 19, 2024

Copy link
Copy Markdown
Contributor

supersedes #15485

This generator is designed to replace both dart and dart-dio generators, and has the following features:

  1. NO dependency on 3rd party modelling/serialization libraries (built_value, freezed, etc...), everything is done in-house (also no need to run dart run build_runner build).
  2. Heavy use of the new Extension types to add strict static typing with no run-time cost. an example of this is:
    • UndefinedWrapper<T> which makes any non-required variable recognize undefined as a valid value, in which case, it will NOT be included during serialization.
    • Enums: an enum is just an expression of the available values a variable can have, it shouldn't replace the data type, which is a perfect use case for extension types (see this file for an example).
  3. Pluggable networking libraries, by extending NetworkingClientBase
    • Support initially will be for package:http, but package:dio can be added as well
  4. Heavy use of mustache's ability to recursively include templates (example), which minimizes java code that was used to hack around nested types.
  5. separate shared_infrastructure package that has simple base models that should NOT be changed, but the generator will also include an option to inline it. this is done so we can maintain a version of it on pub.dev which users can opt-in to use.
  6. Use package:cross_file to handle files
  7. support multiple mime types, not just json.
  8. generate reflection information for models.
  9. Support request/response streaming.

Current tasks:

  • finalize JSON model serialization
  • support discriminators when available
  • finalize XML support
  • finalize API classes
  • write tests in java
  • generate model tests (roundtrip serialization)
  • generate API tests by mocking

P.S. testing and templating for this generator is done here https://github.com/ahmednfwela/dart-next-generator-testing

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc core team: @wing328@jimschubert@cbornet@jmini@etherealjoy

I made a non-breaking change in DefaultCodegen by adding a new method updateCodegenPropertyEnum to fix name conflicts in inner enums for languages that don't support namespaces

publicvoidupdateCodegenPropertyEnum(CodegenPropertyvar, CodegenModelmodel)

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc dart committee for early review:
@jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) @ahmednfwela (2021/08)

@bahag-chandrana

Copy link
Copy Markdown

I think this is a great effort yet a complicated approach to create a single solution that handles different cases.

Simplicity over complex use cases.

I understand we need to handle fields that are not defined in a json or xml. I assume the purpose of UndefinedWrapper extension type is meant for this. While this might help deserialization scenarios, it highly obstructs serialization scenarios. Take the following create a simple Apple instance.

Dart approach:

// easy to define null propertiesfinal apple =Apple();
// easy to define an apple instance with both properties.final apple =Apple(cultivar:'Pink Lady', origin:'Australia');

Proposed approach:

// easy to define null propertiesfinal apple =Apple();
// complicated approach to define an apple instance with both properties.final apple =Apple(cultivar:UndefinedWrapper('Pink Lady'), origin:UndefinedWrapper('Australia'));

Now imagine a scenario where you have to deal with an api where we have to pass a huge object in post request.
This also leads to learning new pattern even for common cases.

While UndefinedWrapper might solve a problem, it may introduce a cognitive load when these instances are actually used. Take for example I want to check if an apple instance has a name.

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

The same can be achieved by simply exporting an extension on 'Object?` Following works on primitives as well. But nevertheless we can completely skip it and just use plain null check.

extensionUndefinedonObject? {
boolget isDefined =>this!=null;
boolget isUndefined =>this==null;
}

Same comment on your proposal for a new form of enum.

build_runner is not bad!

The purpose of existing code generation for serialization is to keep the codebase readable and leave the obvious stuffs to the generator. I agree these can be often slow on a larger projects. But when we use an api client generator how often do we have to run the build_runner? Once or twice if the spec is not clear. But then it stays in the repository. With dart macros around the corner do we really need another completely new serialization deserialization logic. Perhaps its helpful for XML cases, which I can agree. But i strongly believe the whole build_runner for any form of serialization will vanish the day macros are launched and an XML macro could be the next bet.

Questions:

  1. What is the purpose of the reflection classes? e.g. __return.reflection.dart , apple.reflection.dart
  2. Can we extend with other serialization libraries in future if we want it?
  3. What is the purpose of openapi_infrastructure package? It thought the aim is to reduce external dependencies.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

thanks for your review @bahag-chandrana , let me first shed some light on some key points before I answer your questions.

The target of this generator is 100% spec compliance.

Meaning that the generated spec files MUST be able to accurately reflect a given openapi specification, with all of its supported features.

Of course the openapi spec is huge, and has some ambiguity.

This is why I decided to first cover the most important aspect of openapi, schemas.


A schema is essentially a description of a type.

But openapi's only concern is validating a given json (or xml) value against a schema.

it does NOT put any rules on what models should look like at the client side before they are sent to the server, and this is why I created this discussion before: OAI/OpenAPI-Specification#2807.

This means that in order to achieve my goal, which is 100% compliance, I needed to introduce a lot of "new" concepts to dart to be able to perfectly represent a given schema.


Problem 1: non-required nullable types

Here is a fairly common schema:

my_object:
type: objectproperties: name:
type: stringnullable: true

the name property here can be either

  1. a valid string "a b c"
{ "name": "a b c" }
  1. a null
{ "name": null }
  1. not present, or undefined
{ }

in a perfect world, if dart supported union types, we can represent this as follows:

classUndefined {
constUndefined();
}
final<String|null|Undefined> name;

and if name is Undefined, we ignore it during serialization, or -during deserialization- set it to Undefined if it's not present in the json.

However, the closest thing we have to union types is nullable types, e.g. String? which represents <String | null>.

So it's simply impossible to represent Undefined without a wrapper class, which is what extension types were made for.

While i definitely agree that UndefinedWrapper adds a cognitive load, it's also the ONLY design (until union types are added) that serves my goal of 100% compliance.

Also in your example

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

we can introduce an extension method to handle this common case

extensionUndefinedWrapperNullableExt<T> onUndefinedWrapper<T?> {
boolget isAvailable => src.split(
defined: (src) => src !=null,
unDefined: () =>false,
);
}

also if dart-lang/language#3614 gets implemented, that cognitive load of having to wrap UndefinedWrapper around all values is gone.


Problem 2: reflection

As you know, using dart:mirrors to reflect on dart code is not possible (unlike c# reflection), so the alternative is to either use macros (still kinda limited and in preview) or put information about the code as part of the code (which is what build_runner does).

Now to implement an openapi schema as a dart class, the following features are expected of it:

  1. Proper handling of required and nullable constructs
  2. Proper handling of enums
  3. Proper handling of oneof,anyof, allof constructs
  4. Value-based equality == and hashcode
  5. Cloning.
  6. Modifying values in a class.
  7. serialize/deserialize/canDeserialize methods

And there is not a single existing generator based on build_runner that can do all of that right now, some libraries even have long standing bugs for years now.

So after getting fed up with all the existing build_runner packages, I created my own solution to reflect the generated schemas as part of the generation process, where each type tree has its own reflection tree that is able to deliver all of the features I mentioned above.

This makes sure that tree shaking is applicable, and that we can follow separation of concerns principle, where the generated model classes only serve one purpose, storing values, and the reflection classes do the rest of the requested features.


So for Question 1:

All reflection classes extend SerializationReflection<T>, but model reflections inherit from ModelReflection, which is where most of the magic happens (serialization/deserialization, example generation, equality checking, hashing, etc...).

The beautiful thing about this design, is that ALL the generated reflection classes can be replaced with macros!


Question 2:

Simply no, because there is no need to.
A serialization library will -at best- do a subset of the features a fully fledged reflection class can do.


Question 3:

You can consider it an abstraction layer above package:http and package:dio, which unifies features between them (especially multipart support).

This enables the user to define their own networking adapter that does NOT care about any of serialization logic, as it's only dealing with raw bytes and pure HTTP concepts.

And this solves the main issue this generator was created for, decoupling networking from serialization

@DmitrySboychakov

Copy link
Copy Markdown

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

maybe after I finish the initial PR and release it as experimental, I will add a flag to treat null as undefined if the property is not required

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

Hi @ahmednfwela
Is there any chance to move iteratively on existing dart-dio?
With all respect to your hard work - 2years of previous PR were abandoned.
This PR aims to replace them all - how hard it could be to migrate to dart-next?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

actually all the work is already done, the only thing missing is proper testing

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

actually all the work is already done, the only thing missing is proper testing

Pretty significant piece of work I would say.

Could you clarify what is the roadmap before merging dart-next as experimental generator into master?
I could help with testing if it is in master

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

well, first I think i might need help with writing all the java tests, these are present in:

  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenModelTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenOptionsTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenTest.java

so that I can generate the samples and CI can pass.

@cds803

Copy link
Copy Markdown

Are there any new developments regarding dart-next? We are very and urgently in need of a new version. Thank you for the author's contributions.

@allComputableThings

Copy link
Copy Markdown

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

  1. it's a new generator that replaces all the existing dart generators
  2. yes, it supports allof, oneof,anyof
  3. yes, it outputs dart classes and their reflection

@allComputableThings

Copy link
Copy Markdown

Hi Ahmed,

Are you still maintaining this? I'm trying to get a working example of polymorphism. I tried cloning the latest branch from https://github.com/ahmednfwela/openapi-generator

With:

components:
schemas:
Store:
type: object
properties:
pet:
oneOf:
# - $ref: "#/components/schemas/Cat"
- $ref: "#/components/schemas/Dog"
discriminator:
propertyName: petType
mapping:
# Cat: "#/components/schemas/Cat"
Dog: "#/components/schemas/Dog"
Pet:
discriminator:
propertyName: petType
required:
- name
- petType # required for inheritance to work
properties:
name:
type: string
petType:
type: string
Dog:
allOf:
- $ref: '#/components/schemas/Pet' # Dog has all properties of a Pet
properties: # extra properties only for dogs. Should be parts of allOf?
packSize:
description: The size of the pack the dog is from
type: integer
openapi: 3.0.3
security: []
servers: []
paths: {}
info:
version: 1.0.0
title: Swagger Petstore

Produces

class Dog {...}

not

class Dog extends Pet {...}

Is the branch stale? Should continue from https://github.com/OpenAPITools/openapi-generator/ ?
AFAICT in the main branch of https://github.com/OpenAPITools/openapi-generator

  • -g dart doesn't support polymorphism (Dog does not extend Pet)
  • -g dart-dio has non-standard constructors for model objects. (BuiltValue)

dart-next has non-standard constructors for model objects.

Does anyone have a solution for dart polymorphism that produces plain old Dart objects (not BuiltValue, but having an ordinary constructor with parameters matching attribute names)?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

@allComputableThings i am maintaining this, it's just that I am completely overloaded with work that I just don't have time for open source that much

I am not sure how you generated your example, but have a look at this

https://github.com/ahmednfwela/openapi-generator/blob/feat%2Fdart-next/samples%2Fopenapi3%2Fclient%2Fpetstore%2Fdart%2Fnext%2Flib%2Fsrc%2Fmodels%2Fcat.dart#L13

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants

@ahmednfwela@bahag-chandrana@DmitrySboychakov@vasilich6107@cds803@allComputableThings
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

feat(dart): dart-next generator - #18970

Draft
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next
Draft

feat(dart): dart-next generator#18970
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next

Conversation

@ahmednfwela

@ahmednfwelaahmednfwela commented Jun 19, 2024

Copy link
Copy Markdown
Contributor

supersedes #15485

This generator is designed to replace both dart and dart-dio generators, and has the following features:

  1. NO dependency on 3rd party modelling/serialization libraries (built_value, freezed, etc...), everything is done in-house (also no need to run dart run build_runner build).
  2. Heavy use of the new Extension types to add strict static typing with no run-time cost. an example of this is:
    • UndefinedWrapper<T> which makes any non-required variable recognize undefined as a valid value, in which case, it will NOT be included during serialization.
    • Enums: an enum is just an expression of the available values a variable can have, it shouldn't replace the data type, which is a perfect use case for extension types (see this file for an example).
  3. Pluggable networking libraries, by extending NetworkingClientBase
    • Support initially will be for package:http, but package:dio can be added as well
  4. Heavy use of mustache's ability to recursively include templates (example), which minimizes java code that was used to hack around nested types.
  5. separate shared_infrastructure package that has simple base models that should NOT be changed, but the generator will also include an option to inline it. this is done so we can maintain a version of it on pub.dev which users can opt-in to use.
  6. Use package:cross_file to handle files
  7. support multiple mime types, not just json.
  8. generate reflection information for models.
  9. Support request/response streaming.

Current tasks:

  • finalize JSON model serialization
  • support discriminators when available
  • finalize XML support
  • finalize API classes
  • write tests in java
  • generate model tests (roundtrip serialization)
  • generate API tests by mocking

P.S. testing and templating for this generator is done here https://github.com/ahmednfwela/dart-next-generator-testing

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc core team: @wing328@jimschubert@cbornet@jmini@etherealjoy

I made a non-breaking change in DefaultCodegen by adding a new method updateCodegenPropertyEnum to fix name conflicts in inner enums for languages that don't support namespaces

publicvoidupdateCodegenPropertyEnum(CodegenPropertyvar, CodegenModelmodel)

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc dart committee for early review:
@jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) @ahmednfwela (2021/08)

@bahag-chandrana

Copy link
Copy Markdown

I think this is a great effort yet a complicated approach to create a single solution that handles different cases.

Simplicity over complex use cases.

I understand we need to handle fields that are not defined in a json or xml. I assume the purpose of UndefinedWrapper extension type is meant for this. While this might help deserialization scenarios, it highly obstructs serialization scenarios. Take the following create a simple Apple instance.

Dart approach:

// easy to define null propertiesfinal apple =Apple();
// easy to define an apple instance with both properties.final apple =Apple(cultivar:'Pink Lady', origin:'Australia');

Proposed approach:

// easy to define null propertiesfinal apple =Apple();
// complicated approach to define an apple instance with both properties.final apple =Apple(cultivar:UndefinedWrapper('Pink Lady'), origin:UndefinedWrapper('Australia'));

Now imagine a scenario where you have to deal with an api where we have to pass a huge object in post request.
This also leads to learning new pattern even for common cases.

While UndefinedWrapper might solve a problem, it may introduce a cognitive load when these instances are actually used. Take for example I want to check if an apple instance has a name.

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

The same can be achieved by simply exporting an extension on 'Object?` Following works on primitives as well. But nevertheless we can completely skip it and just use plain null check.

extensionUndefinedonObject? {
boolget isDefined =>this!=null;
boolget isUndefined =>this==null;
}

Same comment on your proposal for a new form of enum.

build_runner is not bad!

The purpose of existing code generation for serialization is to keep the codebase readable and leave the obvious stuffs to the generator. I agree these can be often slow on a larger projects. But when we use an api client generator how often do we have to run the build_runner? Once or twice if the spec is not clear. But then it stays in the repository. With dart macros around the corner do we really need another completely new serialization deserialization logic. Perhaps its helpful for XML cases, which I can agree. But i strongly believe the whole build_runner for any form of serialization will vanish the day macros are launched and an XML macro could be the next bet.

Questions:

  1. What is the purpose of the reflection classes? e.g. __return.reflection.dart , apple.reflection.dart
  2. Can we extend with other serialization libraries in future if we want it?
  3. What is the purpose of openapi_infrastructure package? It thought the aim is to reduce external dependencies.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

thanks for your review @bahag-chandrana , let me first shed some light on some key points before I answer your questions.

The target of this generator is 100% spec compliance.

Meaning that the generated spec files MUST be able to accurately reflect a given openapi specification, with all of its supported features.

Of course the openapi spec is huge, and has some ambiguity.

This is why I decided to first cover the most important aspect of openapi, schemas.


A schema is essentially a description of a type.

But openapi's only concern is validating a given json (or xml) value against a schema.

it does NOT put any rules on what models should look like at the client side before they are sent to the server, and this is why I created this discussion before: OAI/OpenAPI-Specification#2807.

This means that in order to achieve my goal, which is 100% compliance, I needed to introduce a lot of "new" concepts to dart to be able to perfectly represent a given schema.


Problem 1: non-required nullable types

Here is a fairly common schema:

my_object:
type: objectproperties: name:
type: stringnullable: true

the name property here can be either

  1. a valid string "a b c"
{ "name": "a b c" }
  1. a null
{ "name": null }
  1. not present, or undefined
{ }

in a perfect world, if dart supported union types, we can represent this as follows:

classUndefined {
constUndefined();
}
final<String|null|Undefined> name;

and if name is Undefined, we ignore it during serialization, or -during deserialization- set it to Undefined if it's not present in the json.

However, the closest thing we have to union types is nullable types, e.g. String? which represents <String | null>.

So it's simply impossible to represent Undefined without a wrapper class, which is what extension types were made for.

While i definitely agree that UndefinedWrapper adds a cognitive load, it's also the ONLY design (until union types are added) that serves my goal of 100% compliance.

Also in your example

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

we can introduce an extension method to handle this common case

extensionUndefinedWrapperNullableExt<T> onUndefinedWrapper<T?> {
boolget isAvailable => src.split(
defined: (src) => src !=null,
unDefined: () =>false,
);
}

also if dart-lang/language#3614 gets implemented, that cognitive load of having to wrap UndefinedWrapper around all values is gone.


Problem 2: reflection

As you know, using dart:mirrors to reflect on dart code is not possible (unlike c# reflection), so the alternative is to either use macros (still kinda limited and in preview) or put information about the code as part of the code (which is what build_runner does).

Now to implement an openapi schema as a dart class, the following features are expected of it:

  1. Proper handling of required and nullable constructs
  2. Proper handling of enums
  3. Proper handling of oneof,anyof, allof constructs
  4. Value-based equality == and hashcode
  5. Cloning.
  6. Modifying values in a class.
  7. serialize/deserialize/canDeserialize methods

And there is not a single existing generator based on build_runner that can do all of that right now, some libraries even have long standing bugs for years now.

So after getting fed up with all the existing build_runner packages, I created my own solution to reflect the generated schemas as part of the generation process, where each type tree has its own reflection tree that is able to deliver all of the features I mentioned above.

This makes sure that tree shaking is applicable, and that we can follow separation of concerns principle, where the generated model classes only serve one purpose, storing values, and the reflection classes do the rest of the requested features.


So for Question 1:

All reflection classes extend SerializationReflection<T>, but model reflections inherit from ModelReflection, which is where most of the magic happens (serialization/deserialization, example generation, equality checking, hashing, etc...).

The beautiful thing about this design, is that ALL the generated reflection classes can be replaced with macros!


Question 2:

Simply no, because there is no need to.
A serialization library will -at best- do a subset of the features a fully fledged reflection class can do.


Question 3:

You can consider it an abstraction layer above package:http and package:dio, which unifies features between them (especially multipart support).

This enables the user to define their own networking adapter that does NOT care about any of serialization logic, as it's only dealing with raw bytes and pure HTTP concepts.

And this solves the main issue this generator was created for, decoupling networking from serialization

@DmitrySboychakov

Copy link
Copy Markdown

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

maybe after I finish the initial PR and release it as experimental, I will add a flag to treat null as undefined if the property is not required

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

Hi @ahmednfwela
Is there any chance to move iteratively on existing dart-dio?
With all respect to your hard work - 2years of previous PR were abandoned.
This PR aims to replace them all - how hard it could be to migrate to dart-next?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

actually all the work is already done, the only thing missing is proper testing

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

actually all the work is already done, the only thing missing is proper testing

Pretty significant piece of work I would say.

Could you clarify what is the roadmap before merging dart-next as experimental generator into master?
I could help with testing if it is in master

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

well, first I think i might need help with writing all the java tests, these are present in:

  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenModelTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenOptionsTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenTest.java

so that I can generate the samples and CI can pass.

@cds803

Copy link
Copy Markdown

Are there any new developments regarding dart-next? We are very and urgently in need of a new version. Thank you for the author's contributions.

@allComputableThings

Copy link
Copy Markdown

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

  1. it's a new generator that replaces all the existing dart generators
  2. yes, it supports allof, oneof,anyof
  3. yes, it outputs dart classes and their reflection

@allComputableThings

Copy link
Copy Markdown

Hi Ahmed,

Are you still maintaining this? I'm trying to get a working example of polymorphism. I tried cloning the latest branch from https://github.com/ahmednfwela/openapi-generator

With:

components:
schemas:
Store:
type: object
properties:
pet:
oneOf:
# - $ref: "#/components/schemas/Cat"
- $ref: "#/components/schemas/Dog"
discriminator:
propertyName: petType
mapping:
# Cat: "#/components/schemas/Cat"
Dog: "#/components/schemas/Dog"
Pet:
discriminator:
propertyName: petType
required:
- name
- petType # required for inheritance to work
properties:
name:
type: string
petType:
type: string
Dog:
allOf:
- $ref: '#/components/schemas/Pet' # Dog has all properties of a Pet
properties: # extra properties only for dogs. Should be parts of allOf?
packSize:
description: The size of the pack the dog is from
type: integer
openapi: 3.0.3
security: []
servers: []
paths: {}
info:
version: 1.0.0
title: Swagger Petstore

Produces

class Dog {...}

not

class Dog extends Pet {...}

Is the branch stale? Should continue from https://github.com/OpenAPITools/openapi-generator/ ?
AFAICT in the main branch of https://github.com/OpenAPITools/openapi-generator

  • -g dart doesn't support polymorphism (Dog does not extend Pet)
  • -g dart-dio has non-standard constructors for model objects. (BuiltValue)

dart-next has non-standard constructors for model objects.

Does anyone have a solution for dart polymorphism that produces plain old Dart objects (not BuiltValue, but having an ordinary constructor with parameters matching attribute names)?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

@allComputableThings i am maintaining this, it's just that I am completely overloaded with work that I just don't have time for open source that much

I am not sure how you generated your example, but have a look at this

https://github.com/ahmednfwela/openapi-generator/blob/feat%2Fdart-next/samples%2Fopenapi3%2Fclient%2Fpetstore%2Fdart%2Fnext%2Flib%2Fsrc%2Fmodels%2Fcat.dart#L13

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants

@ahmednfwela@bahag-chandrana@DmitrySboychakov@vasilich6107@cds803@allComputableThings
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(dart): dart-next generator - #18970

Draft
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next
Draft

feat(dart): dart-next generator#18970
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next

Conversation

@ahmednfwela

@ahmednfwelaahmednfwela commented Jun 19, 2024

Copy link
Copy Markdown
Contributor

supersedes #15485

This generator is designed to replace both dart and dart-dio generators, and has the following features:

  1. NO dependency on 3rd party modelling/serialization libraries (built_value, freezed, etc...), everything is done in-house (also no need to run dart run build_runner build).
  2. Heavy use of the new Extension types to add strict static typing with no run-time cost. an example of this is:
    • UndefinedWrapper<T> which makes any non-required variable recognize undefined as a valid value, in which case, it will NOT be included during serialization.
    • Enums: an enum is just an expression of the available values a variable can have, it shouldn't replace the data type, which is a perfect use case for extension types (see this file for an example).
  3. Pluggable networking libraries, by extending NetworkingClientBase
    • Support initially will be for package:http, but package:dio can be added as well
  4. Heavy use of mustache's ability to recursively include templates (example), which minimizes java code that was used to hack around nested types.
  5. separate shared_infrastructure package that has simple base models that should NOT be changed, but the generator will also include an option to inline it. this is done so we can maintain a version of it on pub.dev which users can opt-in to use.
  6. Use package:cross_file to handle files
  7. support multiple mime types, not just json.
  8. generate reflection information for models.
  9. Support request/response streaming.

Current tasks:

  • finalize JSON model serialization
  • support discriminators when available
  • finalize XML support
  • finalize API classes
  • write tests in java
  • generate model tests (roundtrip serialization)
  • generate API tests by mocking

P.S. testing and templating for this generator is done here https://github.com/ahmednfwela/dart-next-generator-testing

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc core team: @wing328@jimschubert@cbornet@jmini@etherealjoy

I made a non-breaking change in DefaultCodegen by adding a new method updateCodegenPropertyEnum to fix name conflicts in inner enums for languages that don't support namespaces

publicvoidupdateCodegenPropertyEnum(CodegenPropertyvar, CodegenModelmodel)

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc dart committee for early review:
@jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) @ahmednfwela (2021/08)

@bahag-chandrana

Copy link
Copy Markdown

I think this is a great effort yet a complicated approach to create a single solution that handles different cases.

Simplicity over complex use cases.

I understand we need to handle fields that are not defined in a json or xml. I assume the purpose of UndefinedWrapper extension type is meant for this. While this might help deserialization scenarios, it highly obstructs serialization scenarios. Take the following create a simple Apple instance.

Dart approach:

// easy to define null propertiesfinal apple =Apple();
// easy to define an apple instance with both properties.final apple =Apple(cultivar:'Pink Lady', origin:'Australia');

Proposed approach:

// easy to define null propertiesfinal apple =Apple();
// complicated approach to define an apple instance with both properties.final apple =Apple(cultivar:UndefinedWrapper('Pink Lady'), origin:UndefinedWrapper('Australia'));

Now imagine a scenario where you have to deal with an api where we have to pass a huge object in post request.
This also leads to learning new pattern even for common cases.

While UndefinedWrapper might solve a problem, it may introduce a cognitive load when these instances are actually used. Take for example I want to check if an apple instance has a name.

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

The same can be achieved by simply exporting an extension on 'Object?` Following works on primitives as well. But nevertheless we can completely skip it and just use plain null check.

extensionUndefinedonObject? {
boolget isDefined =>this!=null;
boolget isUndefined =>this==null;
}

Same comment on your proposal for a new form of enum.

build_runner is not bad!

The purpose of existing code generation for serialization is to keep the codebase readable and leave the obvious stuffs to the generator. I agree these can be often slow on a larger projects. But when we use an api client generator how often do we have to run the build_runner? Once or twice if the spec is not clear. But then it stays in the repository. With dart macros around the corner do we really need another completely new serialization deserialization logic. Perhaps its helpful for XML cases, which I can agree. But i strongly believe the whole build_runner for any form of serialization will vanish the day macros are launched and an XML macro could be the next bet.

Questions:

  1. What is the purpose of the reflection classes? e.g. __return.reflection.dart , apple.reflection.dart
  2. Can we extend with other serialization libraries in future if we want it?
  3. What is the purpose of openapi_infrastructure package? It thought the aim is to reduce external dependencies.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

thanks for your review @bahag-chandrana , let me first shed some light on some key points before I answer your questions.

The target of this generator is 100% spec compliance.

Meaning that the generated spec files MUST be able to accurately reflect a given openapi specification, with all of its supported features.

Of course the openapi spec is huge, and has some ambiguity.

This is why I decided to first cover the most important aspect of openapi, schemas.


A schema is essentially a description of a type.

But openapi's only concern is validating a given json (or xml) value against a schema.

it does NOT put any rules on what models should look like at the client side before they are sent to the server, and this is why I created this discussion before: OAI/OpenAPI-Specification#2807.

This means that in order to achieve my goal, which is 100% compliance, I needed to introduce a lot of "new" concepts to dart to be able to perfectly represent a given schema.


Problem 1: non-required nullable types

Here is a fairly common schema:

my_object:
type: objectproperties: name:
type: stringnullable: true

the name property here can be either

  1. a valid string "a b c"
{ "name": "a b c" }
  1. a null
{ "name": null }
  1. not present, or undefined
{ }

in a perfect world, if dart supported union types, we can represent this as follows:

classUndefined {
constUndefined();
}
final<String|null|Undefined> name;

and if name is Undefined, we ignore it during serialization, or -during deserialization- set it to Undefined if it's not present in the json.

However, the closest thing we have to union types is nullable types, e.g. String? which represents <String | null>.

So it's simply impossible to represent Undefined without a wrapper class, which is what extension types were made for.

While i definitely agree that UndefinedWrapper adds a cognitive load, it's also the ONLY design (until union types are added) that serves my goal of 100% compliance.

Also in your example

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

we can introduce an extension method to handle this common case

extensionUndefinedWrapperNullableExt<T> onUndefinedWrapper<T?> {
boolget isAvailable => src.split(
defined: (src) => src !=null,
unDefined: () =>false,
);
}

also if dart-lang/language#3614 gets implemented, that cognitive load of having to wrap UndefinedWrapper around all values is gone.


Problem 2: reflection

As you know, using dart:mirrors to reflect on dart code is not possible (unlike c# reflection), so the alternative is to either use macros (still kinda limited and in preview) or put information about the code as part of the code (which is what build_runner does).

Now to implement an openapi schema as a dart class, the following features are expected of it:

  1. Proper handling of required and nullable constructs
  2. Proper handling of enums
  3. Proper handling of oneof,anyof, allof constructs
  4. Value-based equality == and hashcode
  5. Cloning.
  6. Modifying values in a class.
  7. serialize/deserialize/canDeserialize methods

And there is not a single existing generator based on build_runner that can do all of that right now, some libraries even have long standing bugs for years now.

So after getting fed up with all the existing build_runner packages, I created my own solution to reflect the generated schemas as part of the generation process, where each type tree has its own reflection tree that is able to deliver all of the features I mentioned above.

This makes sure that tree shaking is applicable, and that we can follow separation of concerns principle, where the generated model classes only serve one purpose, storing values, and the reflection classes do the rest of the requested features.


So for Question 1:

All reflection classes extend SerializationReflection<T>, but model reflections inherit from ModelReflection, which is where most of the magic happens (serialization/deserialization, example generation, equality checking, hashing, etc...).

The beautiful thing about this design, is that ALL the generated reflection classes can be replaced with macros!


Question 2:

Simply no, because there is no need to.
A serialization library will -at best- do a subset of the features a fully fledged reflection class can do.


Question 3:

You can consider it an abstraction layer above package:http and package:dio, which unifies features between them (especially multipart support).

This enables the user to define their own networking adapter that does NOT care about any of serialization logic, as it's only dealing with raw bytes and pure HTTP concepts.

And this solves the main issue this generator was created for, decoupling networking from serialization

@DmitrySboychakov

Copy link
Copy Markdown

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

maybe after I finish the initial PR and release it as experimental, I will add a flag to treat null as undefined if the property is not required

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

Hi @ahmednfwela
Is there any chance to move iteratively on existing dart-dio?
With all respect to your hard work - 2years of previous PR were abandoned.
This PR aims to replace them all - how hard it could be to migrate to dart-next?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

actually all the work is already done, the only thing missing is proper testing

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

actually all the work is already done, the only thing missing is proper testing

Pretty significant piece of work I would say.

Could you clarify what is the roadmap before merging dart-next as experimental generator into master?
I could help with testing if it is in master

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

well, first I think i might need help with writing all the java tests, these are present in:

  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenModelTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenOptionsTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenTest.java

so that I can generate the samples and CI can pass.

@cds803

Copy link
Copy Markdown

Are there any new developments regarding dart-next? We are very and urgently in need of a new version. Thank you for the author's contributions.

@allComputableThings

Copy link
Copy Markdown

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

  1. it's a new generator that replaces all the existing dart generators
  2. yes, it supports allof, oneof,anyof
  3. yes, it outputs dart classes and their reflection

@allComputableThings

Copy link
Copy Markdown

Hi Ahmed,

Are you still maintaining this? I'm trying to get a working example of polymorphism. I tried cloning the latest branch from https://github.com/ahmednfwela/openapi-generator

With:

components:
schemas:
Store:
type: object
properties:
pet:
oneOf:
# - $ref: "#/components/schemas/Cat"
- $ref: "#/components/schemas/Dog"
discriminator:
propertyName: petType
mapping:
# Cat: "#/components/schemas/Cat"
Dog: "#/components/schemas/Dog"
Pet:
discriminator:
propertyName: petType
required:
- name
- petType # required for inheritance to work
properties:
name:
type: string
petType:
type: string
Dog:
allOf:
- $ref: '#/components/schemas/Pet' # Dog has all properties of a Pet
properties: # extra properties only for dogs. Should be parts of allOf?
packSize:
description: The size of the pack the dog is from
type: integer
openapi: 3.0.3
security: []
servers: []
paths: {}
info:
version: 1.0.0
title: Swagger Petstore

Produces

class Dog {...}

not

class Dog extends Pet {...}

Is the branch stale? Should continue from https://github.com/OpenAPITools/openapi-generator/ ?
AFAICT in the main branch of https://github.com/OpenAPITools/openapi-generator

  • -g dart doesn't support polymorphism (Dog does not extend Pet)
  • -g dart-dio has non-standard constructors for model objects. (BuiltValue)

dart-next has non-standard constructors for model objects.

Does anyone have a solution for dart polymorphism that produces plain old Dart objects (not BuiltValue, but having an ordinary constructor with parameters matching attribute names)?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

@allComputableThings i am maintaining this, it's just that I am completely overloaded with work that I just don't have time for open source that much

I am not sure how you generated your example, but have a look at this

https://github.com/ahmednfwela/openapi-generator/blob/feat%2Fdart-next/samples%2Fopenapi3%2Fclient%2Fpetstore%2Fdart%2Fnext%2Flib%2Fsrc%2Fmodels%2Fcat.dart#L13

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants

@ahmednfwela@bahag-chandrana@DmitrySboychakov@vasilich6107@cds803@allComputableThings
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(dart): dart-next generator - #18970

Draft
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next
Draft

feat(dart): dart-next generator#18970
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next

Conversation

@ahmednfwela

@ahmednfwelaahmednfwela commented Jun 19, 2024

Copy link
Copy Markdown
Contributor

supersedes #15485

This generator is designed to replace both dart and dart-dio generators, and has the following features:

  1. NO dependency on 3rd party modelling/serialization libraries (built_value, freezed, etc...), everything is done in-house (also no need to run dart run build_runner build).
  2. Heavy use of the new Extension types to add strict static typing with no run-time cost. an example of this is:
    • UndefinedWrapper<T> which makes any non-required variable recognize undefined as a valid value, in which case, it will NOT be included during serialization.
    • Enums: an enum is just an expression of the available values a variable can have, it shouldn't replace the data type, which is a perfect use case for extension types (see this file for an example).
  3. Pluggable networking libraries, by extending NetworkingClientBase
    • Support initially will be for package:http, but package:dio can be added as well
  4. Heavy use of mustache's ability to recursively include templates (example), which minimizes java code that was used to hack around nested types.
  5. separate shared_infrastructure package that has simple base models that should NOT be changed, but the generator will also include an option to inline it. this is done so we can maintain a version of it on pub.dev which users can opt-in to use.
  6. Use package:cross_file to handle files
  7. support multiple mime types, not just json.
  8. generate reflection information for models.
  9. Support request/response streaming.

Current tasks:

  • finalize JSON model serialization
  • support discriminators when available
  • finalize XML support
  • finalize API classes
  • write tests in java
  • generate model tests (roundtrip serialization)
  • generate API tests by mocking

P.S. testing and templating for this generator is done here https://github.com/ahmednfwela/dart-next-generator-testing

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc core team: @wing328@jimschubert@cbornet@jmini@etherealjoy

I made a non-breaking change in DefaultCodegen by adding a new method updateCodegenPropertyEnum to fix name conflicts in inner enums for languages that don't support namespaces

publicvoidupdateCodegenPropertyEnum(CodegenPropertyvar, CodegenModelmodel)

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc dart committee for early review:
@jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) @ahmednfwela (2021/08)

@bahag-chandrana

Copy link
Copy Markdown

I think this is a great effort yet a complicated approach to create a single solution that handles different cases.

Simplicity over complex use cases.

I understand we need to handle fields that are not defined in a json or xml. I assume the purpose of UndefinedWrapper extension type is meant for this. While this might help deserialization scenarios, it highly obstructs serialization scenarios. Take the following create a simple Apple instance.

Dart approach:

// easy to define null propertiesfinal apple =Apple();
// easy to define an apple instance with both properties.final apple =Apple(cultivar:'Pink Lady', origin:'Australia');

Proposed approach:

// easy to define null propertiesfinal apple =Apple();
// complicated approach to define an apple instance with both properties.final apple =Apple(cultivar:UndefinedWrapper('Pink Lady'), origin:UndefinedWrapper('Australia'));

Now imagine a scenario where you have to deal with an api where we have to pass a huge object in post request.
This also leads to learning new pattern even for common cases.

While UndefinedWrapper might solve a problem, it may introduce a cognitive load when these instances are actually used. Take for example I want to check if an apple instance has a name.

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

The same can be achieved by simply exporting an extension on 'Object?` Following works on primitives as well. But nevertheless we can completely skip it and just use plain null check.

extensionUndefinedonObject? {
boolget isDefined =>this!=null;
boolget isUndefined =>this==null;
}

Same comment on your proposal for a new form of enum.

build_runner is not bad!

The purpose of existing code generation for serialization is to keep the codebase readable and leave the obvious stuffs to the generator. I agree these can be often slow on a larger projects. But when we use an api client generator how often do we have to run the build_runner? Once or twice if the spec is not clear. But then it stays in the repository. With dart macros around the corner do we really need another completely new serialization deserialization logic. Perhaps its helpful for XML cases, which I can agree. But i strongly believe the whole build_runner for any form of serialization will vanish the day macros are launched and an XML macro could be the next bet.

Questions:

  1. What is the purpose of the reflection classes? e.g. __return.reflection.dart , apple.reflection.dart
  2. Can we extend with other serialization libraries in future if we want it?
  3. What is the purpose of openapi_infrastructure package? It thought the aim is to reduce external dependencies.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

thanks for your review @bahag-chandrana , let me first shed some light on some key points before I answer your questions.

The target of this generator is 100% spec compliance.

Meaning that the generated spec files MUST be able to accurately reflect a given openapi specification, with all of its supported features.

Of course the openapi spec is huge, and has some ambiguity.

This is why I decided to first cover the most important aspect of openapi, schemas.


A schema is essentially a description of a type.

But openapi's only concern is validating a given json (or xml) value against a schema.

it does NOT put any rules on what models should look like at the client side before they are sent to the server, and this is why I created this discussion before: OAI/OpenAPI-Specification#2807.

This means that in order to achieve my goal, which is 100% compliance, I needed to introduce a lot of "new" concepts to dart to be able to perfectly represent a given schema.


Problem 1: non-required nullable types

Here is a fairly common schema:

my_object:
type: objectproperties: name:
type: stringnullable: true

the name property here can be either

  1. a valid string "a b c"
{ "name": "a b c" }
  1. a null
{ "name": null }
  1. not present, or undefined
{ }

in a perfect world, if dart supported union types, we can represent this as follows:

classUndefined {
constUndefined();
}
final<String|null|Undefined> name;

and if name is Undefined, we ignore it during serialization, or -during deserialization- set it to Undefined if it's not present in the json.

However, the closest thing we have to union types is nullable types, e.g. String? which represents <String | null>.

So it's simply impossible to represent Undefined without a wrapper class, which is what extension types were made for.

While i definitely agree that UndefinedWrapper adds a cognitive load, it's also the ONLY design (until union types are added) that serves my goal of 100% compliance.

Also in your example

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

we can introduce an extension method to handle this common case

extensionUndefinedWrapperNullableExt<T> onUndefinedWrapper<T?> {
boolget isAvailable => src.split(
defined: (src) => src !=null,
unDefined: () =>false,
);
}

also if dart-lang/language#3614 gets implemented, that cognitive load of having to wrap UndefinedWrapper around all values is gone.


Problem 2: reflection

As you know, using dart:mirrors to reflect on dart code is not possible (unlike c# reflection), so the alternative is to either use macros (still kinda limited and in preview) or put information about the code as part of the code (which is what build_runner does).

Now to implement an openapi schema as a dart class, the following features are expected of it:

  1. Proper handling of required and nullable constructs
  2. Proper handling of enums
  3. Proper handling of oneof,anyof, allof constructs
  4. Value-based equality == and hashcode
  5. Cloning.
  6. Modifying values in a class.
  7. serialize/deserialize/canDeserialize methods

And there is not a single existing generator based on build_runner that can do all of that right now, some libraries even have long standing bugs for years now.

So after getting fed up with all the existing build_runner packages, I created my own solution to reflect the generated schemas as part of the generation process, where each type tree has its own reflection tree that is able to deliver all of the features I mentioned above.

This makes sure that tree shaking is applicable, and that we can follow separation of concerns principle, where the generated model classes only serve one purpose, storing values, and the reflection classes do the rest of the requested features.


So for Question 1:

All reflection classes extend SerializationReflection<T>, but model reflections inherit from ModelReflection, which is where most of the magic happens (serialization/deserialization, example generation, equality checking, hashing, etc...).

The beautiful thing about this design, is that ALL the generated reflection classes can be replaced with macros!


Question 2:

Simply no, because there is no need to.
A serialization library will -at best- do a subset of the features a fully fledged reflection class can do.


Question 3:

You can consider it an abstraction layer above package:http and package:dio, which unifies features between them (especially multipart support).

This enables the user to define their own networking adapter that does NOT care about any of serialization logic, as it's only dealing with raw bytes and pure HTTP concepts.

And this solves the main issue this generator was created for, decoupling networking from serialization

@DmitrySboychakov

Copy link
Copy Markdown

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

maybe after I finish the initial PR and release it as experimental, I will add a flag to treat null as undefined if the property is not required

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

Hi @ahmednfwela
Is there any chance to move iteratively on existing dart-dio?
With all respect to your hard work - 2years of previous PR were abandoned.
This PR aims to replace them all - how hard it could be to migrate to dart-next?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

actually all the work is already done, the only thing missing is proper testing

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

actually all the work is already done, the only thing missing is proper testing

Pretty significant piece of work I would say.

Could you clarify what is the roadmap before merging dart-next as experimental generator into master?
I could help with testing if it is in master

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

well, first I think i might need help with writing all the java tests, these are present in:

  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenModelTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenOptionsTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenTest.java

so that I can generate the samples and CI can pass.

@cds803

Copy link
Copy Markdown

Are there any new developments regarding dart-next? We are very and urgently in need of a new version. Thank you for the author's contributions.

@allComputableThings

Copy link
Copy Markdown

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

  1. it's a new generator that replaces all the existing dart generators
  2. yes, it supports allof, oneof,anyof
  3. yes, it outputs dart classes and their reflection

@allComputableThings

Copy link
Copy Markdown

Hi Ahmed,

Are you still maintaining this? I'm trying to get a working example of polymorphism. I tried cloning the latest branch from https://github.com/ahmednfwela/openapi-generator

With:

components:
schemas:
Store:
type: object
properties:
pet:
oneOf:
# - $ref: "#/components/schemas/Cat"
- $ref: "#/components/schemas/Dog"
discriminator:
propertyName: petType
mapping:
# Cat: "#/components/schemas/Cat"
Dog: "#/components/schemas/Dog"
Pet:
discriminator:
propertyName: petType
required:
- name
- petType # required for inheritance to work
properties:
name:
type: string
petType:
type: string
Dog:
allOf:
- $ref: '#/components/schemas/Pet' # Dog has all properties of a Pet
properties: # extra properties only for dogs. Should be parts of allOf?
packSize:
description: The size of the pack the dog is from
type: integer
openapi: 3.0.3
security: []
servers: []
paths: {}
info:
version: 1.0.0
title: Swagger Petstore

Produces

class Dog {...}

not

class Dog extends Pet {...}

Is the branch stale? Should continue from https://github.com/OpenAPITools/openapi-generator/ ?
AFAICT in the main branch of https://github.com/OpenAPITools/openapi-generator

  • -g dart doesn't support polymorphism (Dog does not extend Pet)
  • -g dart-dio has non-standard constructors for model objects. (BuiltValue)

dart-next has non-standard constructors for model objects.

Does anyone have a solution for dart polymorphism that produces plain old Dart objects (not BuiltValue, but having an ordinary constructor with parameters matching attribute names)?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

@allComputableThings i am maintaining this, it's just that I am completely overloaded with work that I just don't have time for open source that much

I am not sure how you generated your example, but have a look at this

https://github.com/ahmednfwela/openapi-generator/blob/feat%2Fdart-next/samples%2Fopenapi3%2Fclient%2Fpetstore%2Fdart%2Fnext%2Flib%2Fsrc%2Fmodels%2Fcat.dart#L13

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants

@ahmednfwela@bahag-chandrana@DmitrySboychakov@vasilich6107@cds803@allComputableThings
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

feat(dart): dart-next generator - #18970

Draft
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next
Draft

feat(dart): dart-next generator#18970
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next

Conversation

@ahmednfwela

@ahmednfwelaahmednfwela commented Jun 19, 2024

Copy link
Copy Markdown
Contributor

supersedes #15485

This generator is designed to replace both dart and dart-dio generators, and has the following features:

  1. NO dependency on 3rd party modelling/serialization libraries (built_value, freezed, etc...), everything is done in-house (also no need to run dart run build_runner build).
  2. Heavy use of the new Extension types to add strict static typing with no run-time cost. an example of this is:
    • UndefinedWrapper<T> which makes any non-required variable recognize undefined as a valid value, in which case, it will NOT be included during serialization.
    • Enums: an enum is just an expression of the available values a variable can have, it shouldn't replace the data type, which is a perfect use case for extension types (see this file for an example).
  3. Pluggable networking libraries, by extending NetworkingClientBase
    • Support initially will be for package:http, but package:dio can be added as well
  4. Heavy use of mustache's ability to recursively include templates (example), which minimizes java code that was used to hack around nested types.
  5. separate shared_infrastructure package that has simple base models that should NOT be changed, but the generator will also include an option to inline it. this is done so we can maintain a version of it on pub.dev which users can opt-in to use.
  6. Use package:cross_file to handle files
  7. support multiple mime types, not just json.
  8. generate reflection information for models.
  9. Support request/response streaming.

Current tasks:

  • finalize JSON model serialization
  • support discriminators when available
  • finalize XML support
  • finalize API classes
  • write tests in java
  • generate model tests (roundtrip serialization)
  • generate API tests by mocking

P.S. testing and templating for this generator is done here https://github.com/ahmednfwela/dart-next-generator-testing

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc core team: @wing328@jimschubert@cbornet@jmini@etherealjoy

I made a non-breaking change in DefaultCodegen by adding a new method updateCodegenPropertyEnum to fix name conflicts in inner enums for languages that don't support namespaces

publicvoidupdateCodegenPropertyEnum(CodegenPropertyvar, CodegenModelmodel)

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc dart committee for early review:
@jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) @ahmednfwela (2021/08)

@bahag-chandrana

Copy link
Copy Markdown

I think this is a great effort yet a complicated approach to create a single solution that handles different cases.

Simplicity over complex use cases.

I understand we need to handle fields that are not defined in a json or xml. I assume the purpose of UndefinedWrapper extension type is meant for this. While this might help deserialization scenarios, it highly obstructs serialization scenarios. Take the following create a simple Apple instance.

Dart approach:

// easy to define null propertiesfinal apple =Apple();
// easy to define an apple instance with both properties.final apple =Apple(cultivar:'Pink Lady', origin:'Australia');

Proposed approach:

// easy to define null propertiesfinal apple =Apple();
// complicated approach to define an apple instance with both properties.final apple =Apple(cultivar:UndefinedWrapper('Pink Lady'), origin:UndefinedWrapper('Australia'));

Now imagine a scenario where you have to deal with an api where we have to pass a huge object in post request.
This also leads to learning new pattern even for common cases.

While UndefinedWrapper might solve a problem, it may introduce a cognitive load when these instances are actually used. Take for example I want to check if an apple instance has a name.

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

The same can be achieved by simply exporting an extension on 'Object?` Following works on primitives as well. But nevertheless we can completely skip it and just use plain null check.

extensionUndefinedonObject? {
boolget isDefined =>this!=null;
boolget isUndefined =>this==null;
}

Same comment on your proposal for a new form of enum.

build_runner is not bad!

The purpose of existing code generation for serialization is to keep the codebase readable and leave the obvious stuffs to the generator. I agree these can be often slow on a larger projects. But when we use an api client generator how often do we have to run the build_runner? Once or twice if the spec is not clear. But then it stays in the repository. With dart macros around the corner do we really need another completely new serialization deserialization logic. Perhaps its helpful for XML cases, which I can agree. But i strongly believe the whole build_runner for any form of serialization will vanish the day macros are launched and an XML macro could be the next bet.

Questions:

  1. What is the purpose of the reflection classes? e.g. __return.reflection.dart , apple.reflection.dart
  2. Can we extend with other serialization libraries in future if we want it?
  3. What is the purpose of openapi_infrastructure package? It thought the aim is to reduce external dependencies.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

thanks for your review @bahag-chandrana , let me first shed some light on some key points before I answer your questions.

The target of this generator is 100% spec compliance.

Meaning that the generated spec files MUST be able to accurately reflect a given openapi specification, with all of its supported features.

Of course the openapi spec is huge, and has some ambiguity.

This is why I decided to first cover the most important aspect of openapi, schemas.


A schema is essentially a description of a type.

But openapi's only concern is validating a given json (or xml) value against a schema.

it does NOT put any rules on what models should look like at the client side before they are sent to the server, and this is why I created this discussion before: OAI/OpenAPI-Specification#2807.

This means that in order to achieve my goal, which is 100% compliance, I needed to introduce a lot of "new" concepts to dart to be able to perfectly represent a given schema.


Problem 1: non-required nullable types

Here is a fairly common schema:

my_object:
type: objectproperties: name:
type: stringnullable: true

the name property here can be either

  1. a valid string "a b c"
{ "name": "a b c" }
  1. a null
{ "name": null }
  1. not present, or undefined
{ }

in a perfect world, if dart supported union types, we can represent this as follows:

classUndefined {
constUndefined();
}
final<String|null|Undefined> name;

and if name is Undefined, we ignore it during serialization, or -during deserialization- set it to Undefined if it's not present in the json.

However, the closest thing we have to union types is nullable types, e.g. String? which represents <String | null>.

So it's simply impossible to represent Undefined without a wrapper class, which is what extension types were made for.

While i definitely agree that UndefinedWrapper adds a cognitive load, it's also the ONLY design (until union types are added) that serves my goal of 100% compliance.

Also in your example

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

we can introduce an extension method to handle this common case

extensionUndefinedWrapperNullableExt<T> onUndefinedWrapper<T?> {
boolget isAvailable => src.split(
defined: (src) => src !=null,
unDefined: () =>false,
);
}

also if dart-lang/language#3614 gets implemented, that cognitive load of having to wrap UndefinedWrapper around all values is gone.


Problem 2: reflection

As you know, using dart:mirrors to reflect on dart code is not possible (unlike c# reflection), so the alternative is to either use macros (still kinda limited and in preview) or put information about the code as part of the code (which is what build_runner does).

Now to implement an openapi schema as a dart class, the following features are expected of it:

  1. Proper handling of required and nullable constructs
  2. Proper handling of enums
  3. Proper handling of oneof,anyof, allof constructs
  4. Value-based equality == and hashcode
  5. Cloning.
  6. Modifying values in a class.
  7. serialize/deserialize/canDeserialize methods

And there is not a single existing generator based on build_runner that can do all of that right now, some libraries even have long standing bugs for years now.

So after getting fed up with all the existing build_runner packages, I created my own solution to reflect the generated schemas as part of the generation process, where each type tree has its own reflection tree that is able to deliver all of the features I mentioned above.

This makes sure that tree shaking is applicable, and that we can follow separation of concerns principle, where the generated model classes only serve one purpose, storing values, and the reflection classes do the rest of the requested features.


So for Question 1:

All reflection classes extend SerializationReflection<T>, but model reflections inherit from ModelReflection, which is where most of the magic happens (serialization/deserialization, example generation, equality checking, hashing, etc...).

The beautiful thing about this design, is that ALL the generated reflection classes can be replaced with macros!


Question 2:

Simply no, because there is no need to.
A serialization library will -at best- do a subset of the features a fully fledged reflection class can do.


Question 3:

You can consider it an abstraction layer above package:http and package:dio, which unifies features between them (especially multipart support).

This enables the user to define their own networking adapter that does NOT care about any of serialization logic, as it's only dealing with raw bytes and pure HTTP concepts.

And this solves the main issue this generator was created for, decoupling networking from serialization

@DmitrySboychakov

Copy link
Copy Markdown

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

maybe after I finish the initial PR and release it as experimental, I will add a flag to treat null as undefined if the property is not required

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

Hi @ahmednfwela
Is there any chance to move iteratively on existing dart-dio?
With all respect to your hard work - 2years of previous PR were abandoned.
This PR aims to replace them all - how hard it could be to migrate to dart-next?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

actually all the work is already done, the only thing missing is proper testing

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

actually all the work is already done, the only thing missing is proper testing

Pretty significant piece of work I would say.

Could you clarify what is the roadmap before merging dart-next as experimental generator into master?
I could help with testing if it is in master

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

well, first I think i might need help with writing all the java tests, these are present in:

  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenModelTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenOptionsTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenTest.java

so that I can generate the samples and CI can pass.

@cds803

Copy link
Copy Markdown

Are there any new developments regarding dart-next? We are very and urgently in need of a new version. Thank you for the author's contributions.

@allComputableThings

Copy link
Copy Markdown

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

  1. it's a new generator that replaces all the existing dart generators
  2. yes, it supports allof, oneof,anyof
  3. yes, it outputs dart classes and their reflection

@allComputableThings

Copy link
Copy Markdown

Hi Ahmed,

Are you still maintaining this? I'm trying to get a working example of polymorphism. I tried cloning the latest branch from https://github.com/ahmednfwela/openapi-generator

With:

components:
schemas:
Store:
type: object
properties:
pet:
oneOf:
# - $ref: "#/components/schemas/Cat"
- $ref: "#/components/schemas/Dog"
discriminator:
propertyName: petType
mapping:
# Cat: "#/components/schemas/Cat"
Dog: "#/components/schemas/Dog"
Pet:
discriminator:
propertyName: petType
required:
- name
- petType # required for inheritance to work
properties:
name:
type: string
petType:
type: string
Dog:
allOf:
- $ref: '#/components/schemas/Pet' # Dog has all properties of a Pet
properties: # extra properties only for dogs. Should be parts of allOf?
packSize:
description: The size of the pack the dog is from
type: integer
openapi: 3.0.3
security: []
servers: []
paths: {}
info:
version: 1.0.0
title: Swagger Petstore

Produces

class Dog {...}

not

class Dog extends Pet {...}

Is the branch stale? Should continue from https://github.com/OpenAPITools/openapi-generator/ ?
AFAICT in the main branch of https://github.com/OpenAPITools/openapi-generator

  • -g dart doesn't support polymorphism (Dog does not extend Pet)
  • -g dart-dio has non-standard constructors for model objects. (BuiltValue)

dart-next has non-standard constructors for model objects.

Does anyone have a solution for dart polymorphism that produces plain old Dart objects (not BuiltValue, but having an ordinary constructor with parameters matching attribute names)?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

@allComputableThings i am maintaining this, it's just that I am completely overloaded with work that I just don't have time for open source that much

I am not sure how you generated your example, but have a look at this

https://github.com/ahmednfwela/openapi-generator/blob/feat%2Fdart-next/samples%2Fopenapi3%2Fclient%2Fpetstore%2Fdart%2Fnext%2Flib%2Fsrc%2Fmodels%2Fcat.dart#L13

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants

@ahmednfwela@bahag-chandrana@DmitrySboychakov@vasilich6107@cds803@allComputableThings
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(dart): dart-next generator - #18970

Draft
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next
Draft

feat(dart): dart-next generator#18970
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next

Conversation

@ahmednfwela

@ahmednfwelaahmednfwela commented Jun 19, 2024

Copy link
Copy Markdown
Contributor

supersedes #15485

This generator is designed to replace both dart and dart-dio generators, and has the following features:

  1. NO dependency on 3rd party modelling/serialization libraries (built_value, freezed, etc...), everything is done in-house (also no need to run dart run build_runner build).
  2. Heavy use of the new Extension types to add strict static typing with no run-time cost. an example of this is:
    • UndefinedWrapper<T> which makes any non-required variable recognize undefined as a valid value, in which case, it will NOT be included during serialization.
    • Enums: an enum is just an expression of the available values a variable can have, it shouldn't replace the data type, which is a perfect use case for extension types (see this file for an example).
  3. Pluggable networking libraries, by extending NetworkingClientBase
    • Support initially will be for package:http, but package:dio can be added as well
  4. Heavy use of mustache's ability to recursively include templates (example), which minimizes java code that was used to hack around nested types.
  5. separate shared_infrastructure package that has simple base models that should NOT be changed, but the generator will also include an option to inline it. this is done so we can maintain a version of it on pub.dev which users can opt-in to use.
  6. Use package:cross_file to handle files
  7. support multiple mime types, not just json.
  8. generate reflection information for models.
  9. Support request/response streaming.

Current tasks:

  • finalize JSON model serialization
  • support discriminators when available
  • finalize XML support
  • finalize API classes
  • write tests in java
  • generate model tests (roundtrip serialization)
  • generate API tests by mocking

P.S. testing and templating for this generator is done here https://github.com/ahmednfwela/dart-next-generator-testing

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc core team: @wing328@jimschubert@cbornet@jmini@etherealjoy

I made a non-breaking change in DefaultCodegen by adding a new method updateCodegenPropertyEnum to fix name conflicts in inner enums for languages that don't support namespaces

publicvoidupdateCodegenPropertyEnum(CodegenPropertyvar, CodegenModelmodel)

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc dart committee for early review:
@jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) @ahmednfwela (2021/08)

@bahag-chandrana

Copy link
Copy Markdown

I think this is a great effort yet a complicated approach to create a single solution that handles different cases.

Simplicity over complex use cases.

I understand we need to handle fields that are not defined in a json or xml. I assume the purpose of UndefinedWrapper extension type is meant for this. While this might help deserialization scenarios, it highly obstructs serialization scenarios. Take the following create a simple Apple instance.

Dart approach:

// easy to define null propertiesfinal apple =Apple();
// easy to define an apple instance with both properties.final apple =Apple(cultivar:'Pink Lady', origin:'Australia');

Proposed approach:

// easy to define null propertiesfinal apple =Apple();
// complicated approach to define an apple instance with both properties.final apple =Apple(cultivar:UndefinedWrapper('Pink Lady'), origin:UndefinedWrapper('Australia'));

Now imagine a scenario where you have to deal with an api where we have to pass a huge object in post request.
This also leads to learning new pattern even for common cases.

While UndefinedWrapper might solve a problem, it may introduce a cognitive load when these instances are actually used. Take for example I want to check if an apple instance has a name.

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

The same can be achieved by simply exporting an extension on 'Object?` Following works on primitives as well. But nevertheless we can completely skip it and just use plain null check.

extensionUndefinedonObject? {
boolget isDefined =>this!=null;
boolget isUndefined =>this==null;
}

Same comment on your proposal for a new form of enum.

build_runner is not bad!

The purpose of existing code generation for serialization is to keep the codebase readable and leave the obvious stuffs to the generator. I agree these can be often slow on a larger projects. But when we use an api client generator how often do we have to run the build_runner? Once or twice if the spec is not clear. But then it stays in the repository. With dart macros around the corner do we really need another completely new serialization deserialization logic. Perhaps its helpful for XML cases, which I can agree. But i strongly believe the whole build_runner for any form of serialization will vanish the day macros are launched and an XML macro could be the next bet.

Questions:

  1. What is the purpose of the reflection classes? e.g. __return.reflection.dart , apple.reflection.dart
  2. Can we extend with other serialization libraries in future if we want it?
  3. What is the purpose of openapi_infrastructure package? It thought the aim is to reduce external dependencies.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

thanks for your review @bahag-chandrana , let me first shed some light on some key points before I answer your questions.

The target of this generator is 100% spec compliance.

Meaning that the generated spec files MUST be able to accurately reflect a given openapi specification, with all of its supported features.

Of course the openapi spec is huge, and has some ambiguity.

This is why I decided to first cover the most important aspect of openapi, schemas.


A schema is essentially a description of a type.

But openapi's only concern is validating a given json (or xml) value against a schema.

it does NOT put any rules on what models should look like at the client side before they are sent to the server, and this is why I created this discussion before: OAI/OpenAPI-Specification#2807.

This means that in order to achieve my goal, which is 100% compliance, I needed to introduce a lot of "new" concepts to dart to be able to perfectly represent a given schema.


Problem 1: non-required nullable types

Here is a fairly common schema:

my_object:
type: objectproperties: name:
type: stringnullable: true

the name property here can be either

  1. a valid string "a b c"
{ "name": "a b c" }
  1. a null
{ "name": null }
  1. not present, or undefined
{ }

in a perfect world, if dart supported union types, we can represent this as follows:

classUndefined {
constUndefined();
}
final<String|null|Undefined> name;

and if name is Undefined, we ignore it during serialization, or -during deserialization- set it to Undefined if it's not present in the json.

However, the closest thing we have to union types is nullable types, e.g. String? which represents <String | null>.

So it's simply impossible to represent Undefined without a wrapper class, which is what extension types were made for.

While i definitely agree that UndefinedWrapper adds a cognitive load, it's also the ONLY design (until union types are added) that serves my goal of 100% compliance.

Also in your example

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

we can introduce an extension method to handle this common case

extensionUndefinedWrapperNullableExt<T> onUndefinedWrapper<T?> {
boolget isAvailable => src.split(
defined: (src) => src !=null,
unDefined: () =>false,
);
}

also if dart-lang/language#3614 gets implemented, that cognitive load of having to wrap UndefinedWrapper around all values is gone.


Problem 2: reflection

As you know, using dart:mirrors to reflect on dart code is not possible (unlike c# reflection), so the alternative is to either use macros (still kinda limited and in preview) or put information about the code as part of the code (which is what build_runner does).

Now to implement an openapi schema as a dart class, the following features are expected of it:

  1. Proper handling of required and nullable constructs
  2. Proper handling of enums
  3. Proper handling of oneof,anyof, allof constructs
  4. Value-based equality == and hashcode
  5. Cloning.
  6. Modifying values in a class.
  7. serialize/deserialize/canDeserialize methods

And there is not a single existing generator based on build_runner that can do all of that right now, some libraries even have long standing bugs for years now.

So after getting fed up with all the existing build_runner packages, I created my own solution to reflect the generated schemas as part of the generation process, where each type tree has its own reflection tree that is able to deliver all of the features I mentioned above.

This makes sure that tree shaking is applicable, and that we can follow separation of concerns principle, where the generated model classes only serve one purpose, storing values, and the reflection classes do the rest of the requested features.


So for Question 1:

All reflection classes extend SerializationReflection<T>, but model reflections inherit from ModelReflection, which is where most of the magic happens (serialization/deserialization, example generation, equality checking, hashing, etc...).

The beautiful thing about this design, is that ALL the generated reflection classes can be replaced with macros!


Question 2:

Simply no, because there is no need to.
A serialization library will -at best- do a subset of the features a fully fledged reflection class can do.


Question 3:

You can consider it an abstraction layer above package:http and package:dio, which unifies features between them (especially multipart support).

This enables the user to define their own networking adapter that does NOT care about any of serialization logic, as it's only dealing with raw bytes and pure HTTP concepts.

And this solves the main issue this generator was created for, decoupling networking from serialization

@DmitrySboychakov

Copy link
Copy Markdown

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

maybe after I finish the initial PR and release it as experimental, I will add a flag to treat null as undefined if the property is not required

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

Hi @ahmednfwela
Is there any chance to move iteratively on existing dart-dio?
With all respect to your hard work - 2years of previous PR were abandoned.
This PR aims to replace them all - how hard it could be to migrate to dart-next?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

actually all the work is already done, the only thing missing is proper testing

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

actually all the work is already done, the only thing missing is proper testing

Pretty significant piece of work I would say.

Could you clarify what is the roadmap before merging dart-next as experimental generator into master?
I could help with testing if it is in master

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

well, first I think i might need help with writing all the java tests, these are present in:

  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenModelTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenOptionsTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenTest.java

so that I can generate the samples and CI can pass.

@cds803

Copy link
Copy Markdown

Are there any new developments regarding dart-next? We are very and urgently in need of a new version. Thank you for the author's contributions.

@allComputableThings

Copy link
Copy Markdown

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

  1. it's a new generator that replaces all the existing dart generators
  2. yes, it supports allof, oneof,anyof
  3. yes, it outputs dart classes and their reflection

@allComputableThings

Copy link
Copy Markdown

Hi Ahmed,

Are you still maintaining this? I'm trying to get a working example of polymorphism. I tried cloning the latest branch from https://github.com/ahmednfwela/openapi-generator

With:

components:
schemas:
Store:
type: object
properties:
pet:
oneOf:
# - $ref: "#/components/schemas/Cat"
- $ref: "#/components/schemas/Dog"
discriminator:
propertyName: petType
mapping:
# Cat: "#/components/schemas/Cat"
Dog: "#/components/schemas/Dog"
Pet:
discriminator:
propertyName: petType
required:
- name
- petType # required for inheritance to work
properties:
name:
type: string
petType:
type: string
Dog:
allOf:
- $ref: '#/components/schemas/Pet' # Dog has all properties of a Pet
properties: # extra properties only for dogs. Should be parts of allOf?
packSize:
description: The size of the pack the dog is from
type: integer
openapi: 3.0.3
security: []
servers: []
paths: {}
info:
version: 1.0.0
title: Swagger Petstore

Produces

class Dog {...}

not

class Dog extends Pet {...}

Is the branch stale? Should continue from https://github.com/OpenAPITools/openapi-generator/ ?
AFAICT in the main branch of https://github.com/OpenAPITools/openapi-generator

  • -g dart doesn't support polymorphism (Dog does not extend Pet)
  • -g dart-dio has non-standard constructors for model objects. (BuiltValue)

dart-next has non-standard constructors for model objects.

Does anyone have a solution for dart polymorphism that produces plain old Dart objects (not BuiltValue, but having an ordinary constructor with parameters matching attribute names)?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

@allComputableThings i am maintaining this, it's just that I am completely overloaded with work that I just don't have time for open source that much

I am not sure how you generated your example, but have a look at this

https://github.com/ahmednfwela/openapi-generator/blob/feat%2Fdart-next/samples%2Fopenapi3%2Fclient%2Fpetstore%2Fdart%2Fnext%2Flib%2Fsrc%2Fmodels%2Fcat.dart#L13

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants

@ahmednfwela@bahag-chandrana@DmitrySboychakov@vasilich6107@cds803@allComputableThings
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

feat(dart): dart-next generator - #18970

Draft
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next
Draft

feat(dart): dart-next generator#18970
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next

Conversation

@ahmednfwela

@ahmednfwelaahmednfwela commented Jun 19, 2024

Copy link
Copy Markdown
Contributor

supersedes #15485

This generator is designed to replace both dart and dart-dio generators, and has the following features:

  1. NO dependency on 3rd party modelling/serialization libraries (built_value, freezed, etc...), everything is done in-house (also no need to run dart run build_runner build).
  2. Heavy use of the new Extension types to add strict static typing with no run-time cost. an example of this is:
    • UndefinedWrapper<T> which makes any non-required variable recognize undefined as a valid value, in which case, it will NOT be included during serialization.
    • Enums: an enum is just an expression of the available values a variable can have, it shouldn't replace the data type, which is a perfect use case for extension types (see this file for an example).
  3. Pluggable networking libraries, by extending NetworkingClientBase
    • Support initially will be for package:http, but package:dio can be added as well
  4. Heavy use of mustache's ability to recursively include templates (example), which minimizes java code that was used to hack around nested types.
  5. separate shared_infrastructure package that has simple base models that should NOT be changed, but the generator will also include an option to inline it. this is done so we can maintain a version of it on pub.dev which users can opt-in to use.
  6. Use package:cross_file to handle files
  7. support multiple mime types, not just json.
  8. generate reflection information for models.
  9. Support request/response streaming.

Current tasks:

  • finalize JSON model serialization
  • support discriminators when available
  • finalize XML support
  • finalize API classes
  • write tests in java
  • generate model tests (roundtrip serialization)
  • generate API tests by mocking

P.S. testing and templating for this generator is done here https://github.com/ahmednfwela/dart-next-generator-testing

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc core team: @wing328@jimschubert@cbornet@jmini@etherealjoy

I made a non-breaking change in DefaultCodegen by adding a new method updateCodegenPropertyEnum to fix name conflicts in inner enums for languages that don't support namespaces

publicvoidupdateCodegenPropertyEnum(CodegenPropertyvar, CodegenModelmodel)

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc dart committee for early review:
@jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) @ahmednfwela (2021/08)

@bahag-chandrana

Copy link
Copy Markdown

I think this is a great effort yet a complicated approach to create a single solution that handles different cases.

Simplicity over complex use cases.

I understand we need to handle fields that are not defined in a json or xml. I assume the purpose of UndefinedWrapper extension type is meant for this. While this might help deserialization scenarios, it highly obstructs serialization scenarios. Take the following create a simple Apple instance.

Dart approach:

// easy to define null propertiesfinal apple =Apple();
// easy to define an apple instance with both properties.final apple =Apple(cultivar:'Pink Lady', origin:'Australia');

Proposed approach:

// easy to define null propertiesfinal apple =Apple();
// complicated approach to define an apple instance with both properties.final apple =Apple(cultivar:UndefinedWrapper('Pink Lady'), origin:UndefinedWrapper('Australia'));

Now imagine a scenario where you have to deal with an api where we have to pass a huge object in post request.
This also leads to learning new pattern even for common cases.

While UndefinedWrapper might solve a problem, it may introduce a cognitive load when these instances are actually used. Take for example I want to check if an apple instance has a name.

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

The same can be achieved by simply exporting an extension on 'Object?` Following works on primitives as well. But nevertheless we can completely skip it and just use plain null check.

extensionUndefinedonObject? {
boolget isDefined =>this!=null;
boolget isUndefined =>this==null;
}

Same comment on your proposal for a new form of enum.

build_runner is not bad!

The purpose of existing code generation for serialization is to keep the codebase readable and leave the obvious stuffs to the generator. I agree these can be often slow on a larger projects. But when we use an api client generator how often do we have to run the build_runner? Once or twice if the spec is not clear. But then it stays in the repository. With dart macros around the corner do we really need another completely new serialization deserialization logic. Perhaps its helpful for XML cases, which I can agree. But i strongly believe the whole build_runner for any form of serialization will vanish the day macros are launched and an XML macro could be the next bet.

Questions:

  1. What is the purpose of the reflection classes? e.g. __return.reflection.dart , apple.reflection.dart
  2. Can we extend with other serialization libraries in future if we want it?
  3. What is the purpose of openapi_infrastructure package? It thought the aim is to reduce external dependencies.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

thanks for your review @bahag-chandrana , let me first shed some light on some key points before I answer your questions.

The target of this generator is 100% spec compliance.

Meaning that the generated spec files MUST be able to accurately reflect a given openapi specification, with all of its supported features.

Of course the openapi spec is huge, and has some ambiguity.

This is why I decided to first cover the most important aspect of openapi, schemas.


A schema is essentially a description of a type.

But openapi's only concern is validating a given json (or xml) value against a schema.

it does NOT put any rules on what models should look like at the client side before they are sent to the server, and this is why I created this discussion before: OAI/OpenAPI-Specification#2807.

This means that in order to achieve my goal, which is 100% compliance, I needed to introduce a lot of "new" concepts to dart to be able to perfectly represent a given schema.


Problem 1: non-required nullable types

Here is a fairly common schema:

my_object:
type: objectproperties: name:
type: stringnullable: true

the name property here can be either

  1. a valid string "a b c"
{ "name": "a b c" }
  1. a null
{ "name": null }
  1. not present, or undefined
{ }

in a perfect world, if dart supported union types, we can represent this as follows:

classUndefined {
constUndefined();
}
final<String|null|Undefined> name;

and if name is Undefined, we ignore it during serialization, or -during deserialization- set it to Undefined if it's not present in the json.

However, the closest thing we have to union types is nullable types, e.g. String? which represents <String | null>.

So it's simply impossible to represent Undefined without a wrapper class, which is what extension types were made for.

While i definitely agree that UndefinedWrapper adds a cognitive load, it's also the ONLY design (until union types are added) that serves my goal of 100% compliance.

Also in your example

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

we can introduce an extension method to handle this common case

extensionUndefinedWrapperNullableExt<T> onUndefinedWrapper<T?> {
boolget isAvailable => src.split(
defined: (src) => src !=null,
unDefined: () =>false,
);
}

also if dart-lang/language#3614 gets implemented, that cognitive load of having to wrap UndefinedWrapper around all values is gone.


Problem 2: reflection

As you know, using dart:mirrors to reflect on dart code is not possible (unlike c# reflection), so the alternative is to either use macros (still kinda limited and in preview) or put information about the code as part of the code (which is what build_runner does).

Now to implement an openapi schema as a dart class, the following features are expected of it:

  1. Proper handling of required and nullable constructs
  2. Proper handling of enums
  3. Proper handling of oneof,anyof, allof constructs
  4. Value-based equality == and hashcode
  5. Cloning.
  6. Modifying values in a class.
  7. serialize/deserialize/canDeserialize methods

And there is not a single existing generator based on build_runner that can do all of that right now, some libraries even have long standing bugs for years now.

So after getting fed up with all the existing build_runner packages, I created my own solution to reflect the generated schemas as part of the generation process, where each type tree has its own reflection tree that is able to deliver all of the features I mentioned above.

This makes sure that tree shaking is applicable, and that we can follow separation of concerns principle, where the generated model classes only serve one purpose, storing values, and the reflection classes do the rest of the requested features.


So for Question 1:

All reflection classes extend SerializationReflection<T>, but model reflections inherit from ModelReflection, which is where most of the magic happens (serialization/deserialization, example generation, equality checking, hashing, etc...).

The beautiful thing about this design, is that ALL the generated reflection classes can be replaced with macros!


Question 2:

Simply no, because there is no need to.
A serialization library will -at best- do a subset of the features a fully fledged reflection class can do.


Question 3:

You can consider it an abstraction layer above package:http and package:dio, which unifies features between them (especially multipart support).

This enables the user to define their own networking adapter that does NOT care about any of serialization logic, as it's only dealing with raw bytes and pure HTTP concepts.

And this solves the main issue this generator was created for, decoupling networking from serialization

@DmitrySboychakov

Copy link
Copy Markdown

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

maybe after I finish the initial PR and release it as experimental, I will add a flag to treat null as undefined if the property is not required

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

Hi @ahmednfwela
Is there any chance to move iteratively on existing dart-dio?
With all respect to your hard work - 2years of previous PR were abandoned.
This PR aims to replace them all - how hard it could be to migrate to dart-next?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

actually all the work is already done, the only thing missing is proper testing

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

actually all the work is already done, the only thing missing is proper testing

Pretty significant piece of work I would say.

Could you clarify what is the roadmap before merging dart-next as experimental generator into master?
I could help with testing if it is in master

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

well, first I think i might need help with writing all the java tests, these are present in:

  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenModelTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenOptionsTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenTest.java

so that I can generate the samples and CI can pass.

@cds803

Copy link
Copy Markdown

Are there any new developments regarding dart-next? We are very and urgently in need of a new version. Thank you for the author's contributions.

@allComputableThings

Copy link
Copy Markdown

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

  1. it's a new generator that replaces all the existing dart generators
  2. yes, it supports allof, oneof,anyof
  3. yes, it outputs dart classes and their reflection

@allComputableThings

Copy link
Copy Markdown

Hi Ahmed,

Are you still maintaining this? I'm trying to get a working example of polymorphism. I tried cloning the latest branch from https://github.com/ahmednfwela/openapi-generator

With:

components:
schemas:
Store:
type: object
properties:
pet:
oneOf:
# - $ref: "#/components/schemas/Cat"
- $ref: "#/components/schemas/Dog"
discriminator:
propertyName: petType
mapping:
# Cat: "#/components/schemas/Cat"
Dog: "#/components/schemas/Dog"
Pet:
discriminator:
propertyName: petType
required:
- name
- petType # required for inheritance to work
properties:
name:
type: string
petType:
type: string
Dog:
allOf:
- $ref: '#/components/schemas/Pet' # Dog has all properties of a Pet
properties: # extra properties only for dogs. Should be parts of allOf?
packSize:
description: The size of the pack the dog is from
type: integer
openapi: 3.0.3
security: []
servers: []
paths: {}
info:
version: 1.0.0
title: Swagger Petstore

Produces

class Dog {...}

not

class Dog extends Pet {...}

Is the branch stale? Should continue from https://github.com/OpenAPITools/openapi-generator/ ?
AFAICT in the main branch of https://github.com/OpenAPITools/openapi-generator

  • -g dart doesn't support polymorphism (Dog does not extend Pet)
  • -g dart-dio has non-standard constructors for model objects. (BuiltValue)

dart-next has non-standard constructors for model objects.

Does anyone have a solution for dart polymorphism that produces plain old Dart objects (not BuiltValue, but having an ordinary constructor with parameters matching attribute names)?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

@allComputableThings i am maintaining this, it's just that I am completely overloaded with work that I just don't have time for open source that much

I am not sure how you generated your example, but have a look at this

https://github.com/ahmednfwela/openapi-generator/blob/feat%2Fdart-next/samples%2Fopenapi3%2Fclient%2Fpetstore%2Fdart%2Fnext%2Flib%2Fsrc%2Fmodels%2Fcat.dart#L13

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants

@ahmednfwela@bahag-chandrana@DmitrySboychakov@vasilich6107@cds803@allComputableThings
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

feat(dart): dart-next generator - #18970

Draft
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next
Draft

feat(dart): dart-next generator#18970
ahmednfwela wants to merge 31 commits into
OpenAPITools:masterfrom
ahmednfwela:feat/dart-next

Conversation

@ahmednfwela

@ahmednfwelaahmednfwela commented Jun 19, 2024

Copy link
Copy Markdown
Contributor

supersedes #15485

This generator is designed to replace both dart and dart-dio generators, and has the following features:

  1. NO dependency on 3rd party modelling/serialization libraries (built_value, freezed, etc...), everything is done in-house (also no need to run dart run build_runner build).
  2. Heavy use of the new Extension types to add strict static typing with no run-time cost. an example of this is:
    • UndefinedWrapper<T> which makes any non-required variable recognize undefined as a valid value, in which case, it will NOT be included during serialization.
    • Enums: an enum is just an expression of the available values a variable can have, it shouldn't replace the data type, which is a perfect use case for extension types (see this file for an example).
  3. Pluggable networking libraries, by extending NetworkingClientBase
    • Support initially will be for package:http, but package:dio can be added as well
  4. Heavy use of mustache's ability to recursively include templates (example), which minimizes java code that was used to hack around nested types.
  5. separate shared_infrastructure package that has simple base models that should NOT be changed, but the generator will also include an option to inline it. this is done so we can maintain a version of it on pub.dev which users can opt-in to use.
  6. Use package:cross_file to handle files
  7. support multiple mime types, not just json.
  8. generate reflection information for models.
  9. Support request/response streaming.

Current tasks:

  • finalize JSON model serialization
  • support discriminators when available
  • finalize XML support
  • finalize API classes
  • write tests in java
  • generate model tests (roundtrip serialization)
  • generate API tests by mocking

P.S. testing and templating for this generator is done here https://github.com/ahmednfwela/dart-next-generator-testing

PR checklist

  • Read the contribution guidelines.
  • Pull Request title clearly describes the work in the pull request and Pull Request description provides details about how to validate the work. Missing information here may result in delayed response from the community.
  • Run the following to build the project and update samples:
    ./mvnw clean package ./bin/generate-samples.sh ./bin/configs/*.yaml
    ./bin/utils/export_docs_generators.sh
    
    (For Windows users, please run the script in Git BASH)
    Commit all changed files.
    This is important, as CI jobs will verify all generator outputs of your HEAD commit as it would merge with master.
    These must match the expectations made by your contribution.
    You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example ./bin/generate-samples.sh bin/configs/java*.
    IMPORTANT: Do NOT purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed.
  • File the PR against the correct branch: master (upcoming 7.6.0 minor release - breaking changes with fallbacks), 8.0.x (breaking changes without fallbacks)
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc core team: @wing328@jimschubert@cbornet@jmini@etherealjoy

I made a non-breaking change in DefaultCodegen by adding a new method updateCodegenPropertyEnum to fix name conflicts in inner enums for languages that don't support namespaces

publicvoidupdateCodegenPropertyEnum(CodegenPropertyvar, CodegenModelmodel)

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

cc dart committee for early review:
@jaumard (2018/09) @josh-burton (2019/12) @amondnet (2019/12) @sbu-WBT (2020/12) @kuhnroyal (2020/12) @agilob (2020/12) @ahmednfwela (2021/08)

@bahag-chandrana

Copy link
Copy Markdown

I think this is a great effort yet a complicated approach to create a single solution that handles different cases.

Simplicity over complex use cases.

I understand we need to handle fields that are not defined in a json or xml. I assume the purpose of UndefinedWrapper extension type is meant for this. While this might help deserialization scenarios, it highly obstructs serialization scenarios. Take the following create a simple Apple instance.

Dart approach:

// easy to define null propertiesfinal apple =Apple();
// easy to define an apple instance with both properties.final apple =Apple(cultivar:'Pink Lady', origin:'Australia');

Proposed approach:

// easy to define null propertiesfinal apple =Apple();
// complicated approach to define an apple instance with both properties.final apple =Apple(cultivar:UndefinedWrapper('Pink Lady'), origin:UndefinedWrapper('Australia'));

Now imagine a scenario where you have to deal with an api where we have to pass a huge object in post request.
This also leads to learning new pattern even for common cases.

While UndefinedWrapper might solve a problem, it may introduce a cognitive load when these instances are actually used. Take for example I want to check if an apple instance has a name.

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

The same can be achieved by simply exporting an extension on 'Object?` Following works on primitives as well. But nevertheless we can completely skip it and just use plain null check.

extensionUndefinedonObject? {
boolget isDefined =>this!=null;
boolget isUndefined =>this==null;
}

Same comment on your proposal for a new form of enum.

build_runner is not bad!

The purpose of existing code generation for serialization is to keep the codebase readable and leave the obvious stuffs to the generator. I agree these can be often slow on a larger projects. But when we use an api client generator how often do we have to run the build_runner? Once or twice if the spec is not clear. But then it stays in the repository. With dart macros around the corner do we really need another completely new serialization deserialization logic. Perhaps its helpful for XML cases, which I can agree. But i strongly believe the whole build_runner for any form of serialization will vanish the day macros are launched and an XML macro could be the next bet.

Questions:

  1. What is the purpose of the reflection classes? e.g. __return.reflection.dart , apple.reflection.dart
  2. Can we extend with other serialization libraries in future if we want it?
  3. What is the purpose of openapi_infrastructure package? It thought the aim is to reduce external dependencies.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

thanks for your review @bahag-chandrana , let me first shed some light on some key points before I answer your questions.

The target of this generator is 100% spec compliance.

Meaning that the generated spec files MUST be able to accurately reflect a given openapi specification, with all of its supported features.

Of course the openapi spec is huge, and has some ambiguity.

This is why I decided to first cover the most important aspect of openapi, schemas.


A schema is essentially a description of a type.

But openapi's only concern is validating a given json (or xml) value against a schema.

it does NOT put any rules on what models should look like at the client side before they are sent to the server, and this is why I created this discussion before: OAI/OpenAPI-Specification#2807.

This means that in order to achieve my goal, which is 100% compliance, I needed to introduce a lot of "new" concepts to dart to be able to perfectly represent a given schema.


Problem 1: non-required nullable types

Here is a fairly common schema:

my_object:
type: objectproperties: name:
type: stringnullable: true

the name property here can be either

  1. a valid string "a b c"
{ "name": "a b c" }
  1. a null
{ "name": null }
  1. not present, or undefined
{ }

in a perfect world, if dart supported union types, we can represent this as follows:

classUndefined {
constUndefined();
}
final<String|null|Undefined> name;

and if name is Undefined, we ignore it during serialization, or -during deserialization- set it to Undefined if it's not present in the json.

However, the closest thing we have to union types is nullable types, e.g. String? which represents <String | null>.

So it's simply impossible to represent Undefined without a wrapper class, which is what extension types were made for.

While i definitely agree that UndefinedWrapper adds a cognitive load, it's also the ONLY design (until union types are added) that serves my goal of 100% compliance.

Also in your example

if(apple.cultivar.isDefined){
// do something
}
// instead of if(apple.cultivar !=null){
// do something
}

we can introduce an extension method to handle this common case

extensionUndefinedWrapperNullableExt<T> onUndefinedWrapper<T?> {
boolget isAvailable => src.split(
defined: (src) => src !=null,
unDefined: () =>false,
);
}

also if dart-lang/language#3614 gets implemented, that cognitive load of having to wrap UndefinedWrapper around all values is gone.


Problem 2: reflection

As you know, using dart:mirrors to reflect on dart code is not possible (unlike c# reflection), so the alternative is to either use macros (still kinda limited and in preview) or put information about the code as part of the code (which is what build_runner does).

Now to implement an openapi schema as a dart class, the following features are expected of it:

  1. Proper handling of required and nullable constructs
  2. Proper handling of enums
  3. Proper handling of oneof,anyof, allof constructs
  4. Value-based equality == and hashcode
  5. Cloning.
  6. Modifying values in a class.
  7. serialize/deserialize/canDeserialize methods

And there is not a single existing generator based on build_runner that can do all of that right now, some libraries even have long standing bugs for years now.

So after getting fed up with all the existing build_runner packages, I created my own solution to reflect the generated schemas as part of the generation process, where each type tree has its own reflection tree that is able to deliver all of the features I mentioned above.

This makes sure that tree shaking is applicable, and that we can follow separation of concerns principle, where the generated model classes only serve one purpose, storing values, and the reflection classes do the rest of the requested features.


So for Question 1:

All reflection classes extend SerializationReflection<T>, but model reflections inherit from ModelReflection, which is where most of the magic happens (serialization/deserialization, example generation, equality checking, hashing, etc...).

The beautiful thing about this design, is that ALL the generated reflection classes can be replaced with macros!


Question 2:

Simply no, because there is no need to.
A serialization library will -at best- do a subset of the features a fully fledged reflection class can do.


Question 3:

You can consider it an abstraction layer above package:http and package:dio, which unifies features between them (especially multipart support).

This enables the user to define their own networking adapter that does NOT care about any of serialization logic, as it's only dealing with raw bytes and pure HTTP concepts.

And this solves the main issue this generator was created for, decoupling networking from serialization

@DmitrySboychakov

Copy link
Copy Markdown

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Hello @ahmednfwela, thank you for the great contribution. I love the overall design, but..
Let me say I also share some concerns about UndefinedWrapper. My believe that most of users would treat null as undefined without a problem and personally I'd love to see that as feature flag to the generator.

maybe after I finish the initial PR and release it as experimental, I will add a flag to treat null as undefined if the property is not required

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

Hi @ahmednfwela
Is there any chance to move iteratively on existing dart-dio?
With all respect to your hard work - 2years of previous PR were abandoned.
This PR aims to replace them all - how hard it could be to migrate to dart-next?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

actually all the work is already done, the only thing missing is proper testing

@vasilich6107

vasilich6107 commented Jan 13, 2025

Copy link
Copy Markdown
Contributor

actually all the work is already done, the only thing missing is proper testing

Pretty significant piece of work I would say.

Could you clarify what is the roadmap before merging dart-next as experimental generator into master?
I could help with testing if it is in master

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

well, first I think i might need help with writing all the java tests, these are present in:

  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenModelTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenOptionsTest.java
  • modules/openapi-generator/src/test/java/org/openapitools/codegen/dart/next/DartNextClientCodegenTest.java

so that I can generate the samples and CI can pass.

@cds803

Copy link
Copy Markdown

Are there any new developments regarding dart-next? We are very and urgently in need of a new version. Thank you for the author's contributions.

@allComputableThings

Copy link
Copy Markdown

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

Some questions.
Is dart-next the same or different to dart-dio-next?
Does dart-next support polymorphism?
Does dart-next support outputting plain old Dart classes with simple (non-builder) constructors?

  1. it's a new generator that replaces all the existing dart generators
  2. yes, it supports allof, oneof,anyof
  3. yes, it outputs dart classes and their reflection

@allComputableThings

Copy link
Copy Markdown

Hi Ahmed,

Are you still maintaining this? I'm trying to get a working example of polymorphism. I tried cloning the latest branch from https://github.com/ahmednfwela/openapi-generator

With:

components:
schemas:
Store:
type: object
properties:
pet:
oneOf:
# - $ref: "#/components/schemas/Cat"
- $ref: "#/components/schemas/Dog"
discriminator:
propertyName: petType
mapping:
# Cat: "#/components/schemas/Cat"
Dog: "#/components/schemas/Dog"
Pet:
discriminator:
propertyName: petType
required:
- name
- petType # required for inheritance to work
properties:
name:
type: string
petType:
type: string
Dog:
allOf:
- $ref: '#/components/schemas/Pet' # Dog has all properties of a Pet
properties: # extra properties only for dogs. Should be parts of allOf?
packSize:
description: The size of the pack the dog is from
type: integer
openapi: 3.0.3
security: []
servers: []
paths: {}
info:
version: 1.0.0
title: Swagger Petstore

Produces

class Dog {...}

not

class Dog extends Pet {...}

Is the branch stale? Should continue from https://github.com/OpenAPITools/openapi-generator/ ?
AFAICT in the main branch of https://github.com/OpenAPITools/openapi-generator

  • -g dart doesn't support polymorphism (Dog does not extend Pet)
  • -g dart-dio has non-standard constructors for model objects. (BuiltValue)

dart-next has non-standard constructors for model objects.

Does anyone have a solution for dart polymorphism that produces plain old Dart objects (not BuiltValue, but having an ordinary constructor with parameters matching attribute names)?

@ahmednfwela

Copy link
Copy Markdown
ContributorAuthor

@allComputableThings i am maintaining this, it's just that I am completely overloaded with work that I just don't have time for open source that much

I am not sure how you generated your example, but have a look at this

https://github.com/ahmednfwela/openapi-generator/blob/feat%2Fdart-next/samples%2Fopenapi3%2Fclient%2Fpetstore%2Fdart%2Fnext%2Flib%2Fsrc%2Fmodels%2Fcat.dart#L13

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants

@ahmednfwela@bahag-chandrana@DmitrySboychakov@vasilich6107@cds803@allComputableThings