generateModelSource function
Generates a self-contained (zero-import) immutable Dart model class for
schema's RemoteSchemaDef.current version — value-equal (==/
hashCode), fromJson/toJson, never-throwing field readers (a
wrong-typed field falls back to a type-appropriate default, same
tolerant-parsing contract lib/core/utils/safe_json.dart follows,
re-implemented inline here instead of imported so the output has no
dependency on this package at all).
Implementation
String generateModelSource(RemoteSchemaDef schema) {
final className = '${_upperFirst(schema.packName)}Content';
final fields = schema.current.fields;
final usedReaders = {for (final f in fields) f.type}.toList()
..sort((a, b) => a.index.compareTo(b.index));
final buffer = StringBuffer()
..writeln(
'// GENERATED BY tool/remote_schema_compiler.dart — DO NOT EDIT BY HAND.',
)
..writeln('// Schema: ${schema.packName} v${schema.current.version}')
..writeln()
..writeln('class $className {')
..writeln(' const $className({');
for (final f in fields) {
buffer.writeln(' required this.${f.name},');
}
buffer
..writeln(' });')
..writeln();
for (final f in fields) {
buffer.writeln(' final ${_dartTypeFor(f.type)} ${f.name};');
}
buffer
..writeln()
..writeln(
' factory $className.fromJson(Map<String, Object?> json) => $className(',
);
for (final f in fields) {
buffer.writeln(" ${f.name}: ${_readerFor(f.type)}(json['${f.name}']),");
}
buffer
..writeln(' );')
..writeln()
..writeln(' Map<String, Object?> toJson() => {');
for (final f in fields) {
buffer.writeln(" '${f.name}': ${f.name},");
}
buffer
..writeln(' };')
..writeln()
..writeln(' @override')
..writeln(' bool operator ==(Object other) =>')
..writeln(' other is $className &&');
buffer.writeln(
'${fields.map((f) => ' other.${f.name} == ${f.name}').join(' &&\n')};',
);
buffer
..writeln()
..writeln(' @override')
..writeln(' int get hashCode => Object.hashAll([')
..writeln(' ${fields.map((f) => f.name).join(', ')}')
..writeln(' ]);')
..writeln()
..writeln(' @override')
..writeln(
" String toString() => '$className(' "
"'${fields.map((f) => '${f.name}: \$${f.name}').join(', ')}' "
"')';",
)
..writeln('}');
for (final type in usedReaders) {
buffer
..writeln()
..writeln(_readerBody[type]);
}
return buffer.toString();
}