Files
Docwell/Phone-App/tool/generate_api.dart
T
tajniak81andClaude Opus 5.5 7968e82cc2 Add page-level permissions and guests
Pages can now be shared with people and groups beyond their space, and
restricted so that only those grants count. A grant covers the page and
everything under it. Space admins always keep access, and an editor who
restricts a page keeps editor through a grant of their own.

Sharing a page with someone from the organization who is outside the
workspace adds them as a guest. Anyone else gets a guest invite that
carries the page grant, which is made when they accept. Guests see a
"limited" space holding only the pages shared with them.

The page tree, breadcrumbs, search, favorites, recents, trash and import
all follow the page role. Public links skip restricted subtrees. Grants
are cleaned up when a member leaves or a group is deleted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 21:39:50 +01:00

306 lines
9.1 KiB
Dart

// SPDX-License-Identifier: AGPL-3.0-or-later
// Generates Dart models from the schemas in api/openapi.yaml.
//
// dart run tool/generate_api.dart (from Phone-App/)
//
// Handles what the contract uses: objects, string enums, $ref, arrays, maps
// (additionalProperties) and "object or null". Inline objects and enums become
// classes named after their parent and property (WorkspaceMember.user ->
// WorkspaceMemberUser).
import 'dart:io';
import 'package:yaml/yaml.dart';
const _specPath = '../api/openapi.yaml';
const _outPath = 'lib/api/generated/models.dart';
void main() {
final spec = loadYaml(File(_specPath).readAsStringSync()) as YamlMap;
final schemas = (spec['components'] as YamlMap)['schemas'] as YamlMap;
final gen = _Generator({
for (final e in schemas.entries)
if ((e.value as YamlMap)['enum'] != null) e.key as String,
});
for (final entry in schemas.entries) {
gen.schema(_className(entry.key as String), entry.value as YamlMap);
}
File(_outPath)
..createSync(recursive: true)
..writeAsStringSync(gen.render());
final fmt = Process.runSync('dart', ['format', _outPath], runInShell: true);
if (fmt.exitCode != 0) {
stderr.write(fmt.stderr);
exit(fmt.exitCode);
}
stdout.writeln('wrote $_outPath (${schemas.length} schemas)');
}
/// Schema names that would hide a dart:core type get an Api prefix (Error -> ApiError).
const _coreNames = {
'Error',
'Exception',
'Object',
'Type',
'List',
'Map',
'Set',
'Duration',
'Uri',
};
String _className(String schema) =>
_coreNames.contains(schema) ? 'Api$schema' : schema;
class _Field {
_Field(this.name, this.type, this.required, this.description);
final String name;
final _Type type;
final bool required;
final String? description;
}
/// A Dart type plus how to convert it from and to JSON.
class _Type {
_Type(this.dart, this.fromJson, this.toJson, {this.nullable = false});
final String dart;
final String Function(String v) fromJson;
final String Function(String v) toJson;
final bool nullable;
}
class _Generator {
_Generator(this.enumSchemas);
final Set<String> enumSchemas;
final _out = <String>[];
String render() => [
'// SPDX-License-Identifier: AGPL-3.0-or-later',
'',
'// Code generated by tool/generate_api.dart from api/openapi.yaml. DO NOT EDIT.',
'',
'// ignore_for_file: constant_identifier_names',
'',
..._out,
].join('\n');
void schema(String name, YamlMap s) {
if (s['enum'] != null) {
_enum(name, s);
} else if (s['type'] == 'object') {
_class(name, s);
} else {
throw UnsupportedError('schema $name: type ${s['type']}');
}
}
void _enum(String name, YamlMap s) {
final values = (s['enum'] as YamlList).cast<String>();
final b = StringBuffer();
_doc(b, s['description'] as String?, '');
b.writeln('enum $name {');
for (final v in values) {
// An empty value means "none" (e.g. SpaceCallerRole).
b.writeln(" ${v.isEmpty ? 'none' : _ident(v)}('$v'),");
}
b.writeln(' ;');
b.writeln();
b.writeln(' const $name(this.value);');
b.writeln(' final String value;');
b.writeln();
b.writeln(' static $name fromJson(String value) =>');
b.writeln(' values.firstWhere((e) => e.value == value,');
b.writeln(
" orElse: () => throw FormatException('unknown $name', value));",
);
b.writeln();
b.writeln(' String toJson() => value;');
b.writeln('}');
_out.add(b.toString());
}
void _class(String name, YamlMap s) {
final required = ((s['required'] as YamlList?) ?? YamlList())
.cast<String>();
final props = (s['properties'] as YamlMap?) ?? YamlMap();
final fields = <_Field>[];
for (final e in props.entries) {
final prop = e.key as String;
final ps = e.value as YamlMap;
fields.add(
_Field(
prop,
_type(name + _pascal(prop), ps),
required.contains(prop),
ps['description'] as String?,
),
);
}
final b = StringBuffer();
_doc(b, s['description'] as String?, '');
b.writeln('class $name {');
if (fields.isEmpty) {
b.writeln(' const $name();');
} else {
b.writeln(' const $name({');
for (final f in fields) {
b.writeln(
' ${f.required ? 'required ' : ''}this.${_ident(f.name)},',
);
}
b.writeln(' });');
}
b.writeln();
b.writeln(' factory $name.fromJson(Map<String, dynamic> json) => $name(');
for (final f in fields) {
final v = "json['${f.name}']";
final conv = f.required && !f.type.nullable
? f.type.fromJson(v)
: '$v == null ? null : ${f.type.fromJson(v)}';
b.writeln(' ${_ident(f.name)}: $conv,');
}
b.writeln(' );');
for (final f in fields) {
b.writeln();
_doc(b, f.description, ' ');
final opt = !f.required || f.type.nullable;
b.writeln(' final ${f.type.dart}${opt ? '?' : ''} ${_ident(f.name)};');
}
b.writeln();
b.writeln(' Map<String, dynamic> toJson() => {');
for (final f in fields) {
final id = _ident(f.name);
// `id?` short-circuits the conversion chain when the value is null.
final plain = f.type.toJson('x') == 'x';
final maybe = plain ? id : f.type.toJson('$id?');
if (f.required) {
b.writeln(
" '${f.name}': ${f.type.nullable ? maybe : f.type.toJson(id)},",
);
} else {
b.writeln(" '${f.name}': ?$maybe,");
}
}
b.writeln(' };');
b.writeln('}');
_out.add(b.toString());
}
_Type _type(String inlineName, YamlMap s) {
final ref = s[r'$ref'] as String?;
if (ref != null) {
final target = _className(ref.split('/').last);
return _Type(
target,
(v) =>
'$target.fromJson($v as ${_isEnumRef(s) ? 'String' : 'Map<String, dynamic>'})',
(v) => '$v.toJson()',
);
}
final oneOf = s['oneOf'] as YamlList?;
if (oneOf != null) {
final nonNull = oneOf
.cast<YamlMap>()
.where((o) => o['type'] != 'null')
.toList();
if (nonNull.length != 1 || nonNull.length == oneOf.length) {
throw UnsupportedError(
'$inlineName: only "T or null" oneOf is supported',
);
}
final t = _type(inlineName, nonNull.single);
return _Type(t.dart, t.fromJson, t.toJson, nullable: true);
}
if (s['enum'] != null) {
_enum(inlineName, s);
return _Type(
inlineName,
(v) => '$inlineName.fromJson($v as String)',
(v) => '$v.toJson()',
);
}
switch (s['type']) {
case 'string':
return _Type('String', (v) => '$v as String', (v) => v);
case 'integer':
return _Type('int', (v) => '($v as num).toInt()', (v) => v);
case 'number':
return _Type('double', (v) => '($v as num).toDouble()', (v) => v);
case 'boolean':
return _Type('bool', (v) => '$v as bool', (v) => v);
case 'array':
final item = _type(inlineName, s['items'] as YamlMap);
return _Type(
'List<${item.dart}>',
(v) => '($v as List).map((e) => ${item.fromJson('e')}).toList()',
(v) => '$v.map((e) => ${item.toJson('e')}).toList()',
);
case 'object':
final extra = s['additionalProperties'];
if (s['properties'] != null) {
_class(inlineName, s);
return _Type(
inlineName,
(v) => '$inlineName.fromJson($v as Map<String, dynamic>)',
(v) => '$v.toJson()',
);
}
if (extra is YamlMap) {
final val = _type(inlineName, extra);
final plain = val.toJson('e') == 'e';
return _Type(
'Map<String, ${val.dart}>',
(v) =>
'($v as Map<String, dynamic>).map((k, e) => MapEntry(k, ${val.fromJson('e')}))',
(v) =>
plain ? v : '$v.map((k, e) => MapEntry(k, ${val.toJson('e')}))',
);
}
return _Type(
'Map<String, dynamic>',
(v) => '$v as Map<String, dynamic>',
(v) => v,
);
}
throw UnsupportedError('$inlineName: type ${s['type']}');
}
// Enum schemas are referenced by name; the spec's enums are all strings.
bool _isEnumRef(YamlMap s) =>
enumSchemas.contains((s[r'$ref'] as String).split('/').last);
static void _doc(StringBuffer b, String? text, String indent) {
if (text == null) return;
for (final line in text.trim().split('\n')) {
// Angle brackets would read as HTML in dartdoc, so code-span them.
final doc = line.trim().replaceAllMapped(
RegExp(r'<[^<>\s]+>'),
(m) => '`${m[0]}`',
);
b.writeln('$indent/// $doc');
}
}
static String _pascal(String s) => s[0].toUpperCase() + s.substring(1);
static const _reserved = {
'default',
'enum',
'class',
'new',
'switch',
'in',
'is',
};
static String _ident(String s) {
final id = s.replaceAllMapped(
RegExp(r'[-_ ](\w)'),
(m) => m[1]!.toUpperCase(),
);
return _reserved.contains(id) ? '${id}_' : id;
}
}