refactor(apps): 重构数据层目录结构并新增启动预热编排器
This commit is contained in:
@@ -1,149 +0,0 @@
|
||||
import 'dart:convert';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'api_exception.dart';
|
||||
import 'api_interceptor.dart';
|
||||
import 'i_api_client.dart';
|
||||
import '../storage/token_storage.dart';
|
||||
|
||||
class ApiClient implements IApiClient {
|
||||
final Dio _dio;
|
||||
final TokenStorage _tokenStorage;
|
||||
final ApiInterceptor _interceptor;
|
||||
|
||||
factory ApiClient({
|
||||
required String baseUrl,
|
||||
required TokenStorage tokenStorage,
|
||||
Dio? dio,
|
||||
}) {
|
||||
final effectiveDio =
|
||||
dio ??
|
||||
Dio(
|
||||
BaseOptions(
|
||||
baseUrl: baseUrl,
|
||||
connectTimeout: const Duration(seconds: 10),
|
||||
receiveTimeout: const Duration(seconds: 20),
|
||||
sendTimeout: const Duration(seconds: 20),
|
||||
),
|
||||
);
|
||||
final interceptor = ApiInterceptor(
|
||||
tokenStorage: tokenStorage,
|
||||
dio: effectiveDio,
|
||||
);
|
||||
effectiveDio.interceptors.add(interceptor);
|
||||
return ApiClient._(
|
||||
dio: effectiveDio,
|
||||
tokenStorage: tokenStorage,
|
||||
interceptor: interceptor,
|
||||
);
|
||||
}
|
||||
|
||||
ApiClient._({
|
||||
required Dio dio,
|
||||
required TokenStorage tokenStorage,
|
||||
required ApiInterceptor interceptor,
|
||||
}) : _dio = dio,
|
||||
_tokenStorage = tokenStorage,
|
||||
_interceptor = interceptor;
|
||||
|
||||
Dio get dio => _dio;
|
||||
|
||||
void resetInterceptor() {
|
||||
_interceptor.reset();
|
||||
}
|
||||
|
||||
void setRefreshCallback(Future<bool> Function(String) refresh) {
|
||||
_interceptor.onTokenRefresh = () async {
|
||||
final token = await _tokenStorage.getRefreshToken();
|
||||
if (token == null) return false;
|
||||
return refresh(token);
|
||||
};
|
||||
}
|
||||
|
||||
void setAuthFailureCallback(Future<void> Function() onAuthFailure) {
|
||||
_interceptor.onAuthFailure = onAuthFailure;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response<T>> get<T>(String path, {Options? options}) async {
|
||||
try {
|
||||
return await _dio.get<T>(path, options: options);
|
||||
} on DioException catch (e) {
|
||||
throw ApiException.fromDioError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response<T>> post<T>(
|
||||
String path, {
|
||||
dynamic data,
|
||||
Options? options,
|
||||
}) async {
|
||||
try {
|
||||
return await _dio.post<T>(path, data: data, options: options);
|
||||
} on DioException catch (e) {
|
||||
throw ApiException.fromDioError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response<T>> patch<T>(
|
||||
String path, {
|
||||
dynamic data,
|
||||
Options? options,
|
||||
}) async {
|
||||
try {
|
||||
return await _dio.patch<T>(path, data: data, options: options);
|
||||
} on DioException catch (e) {
|
||||
throw ApiException.fromDioError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response<T>> put<T>(
|
||||
String path, {
|
||||
dynamic data,
|
||||
Options? options,
|
||||
}) async {
|
||||
try {
|
||||
return await _dio.put<T>(path, data: data, options: options);
|
||||
} on DioException catch (e) {
|
||||
throw ApiException.fromDioError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Response<T>> delete<T>(
|
||||
String path, {
|
||||
dynamic data,
|
||||
Options? options,
|
||||
}) async {
|
||||
try {
|
||||
return await _dio.delete<T>(path, data: data, options: options);
|
||||
} on DioException catch (e) {
|
||||
throw ApiException.fromDioError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Stream<String>> getSseLines(
|
||||
String path, {
|
||||
Map<String, String>? headers,
|
||||
}) async {
|
||||
try {
|
||||
final response = await _dio.get<ResponseBody>(
|
||||
path,
|
||||
options: Options(responseType: ResponseType.stream, headers: headers),
|
||||
);
|
||||
final responseBody = response.data;
|
||||
if (responseBody == null) {
|
||||
return const Stream<String>.empty();
|
||||
}
|
||||
return responseBody.stream
|
||||
.cast<List<int>>()
|
||||
.transform(utf8.decoder)
|
||||
.transform(const LineSplitter());
|
||||
} on DioException catch (e) {
|
||||
throw ApiException.fromDioError(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import '../l10n/l10n.dart';
|
||||
import 'error_code_mapper.dart';
|
||||
|
||||
abstract class ApiException implements Exception {
|
||||
final String message;
|
||||
final int? statusCode;
|
||||
final String? errorCode;
|
||||
final Map<String, dynamic>? errorParams;
|
||||
|
||||
const ApiException(
|
||||
this.message, {
|
||||
this.statusCode,
|
||||
this.errorCode,
|
||||
this.errorParams,
|
||||
});
|
||||
|
||||
@override
|
||||
String toString() => message;
|
||||
|
||||
factory ApiException.fromDioError(Object error) {
|
||||
if (error is ApiException) return error;
|
||||
if (error is DioException) {
|
||||
final response = error.response;
|
||||
final statusCode = response?.statusCode;
|
||||
final data = response?.data;
|
||||
|
||||
String detail;
|
||||
String? errorCode;
|
||||
Map<String, dynamic>? errorParams;
|
||||
final decodedData = _normalizeErrorData(data);
|
||||
|
||||
if (decodedData is Map<String, dynamic>) {
|
||||
detail =
|
||||
(decodedData['detail'] ??
|
||||
decodedData['message'] ??
|
||||
decodedData['error'])
|
||||
?.toString() ??
|
||||
L10n.current.errorRequestFailed;
|
||||
final code = decodedData['code'];
|
||||
if (code is String && code.trim().isNotEmpty) {
|
||||
errorCode = code;
|
||||
}
|
||||
final params = decodedData['params'];
|
||||
if (params is Map<String, dynamic>) {
|
||||
errorParams = params;
|
||||
} else if (params is Map) {
|
||||
errorParams = params.map(
|
||||
(key, value) => MapEntry(key.toString(), value),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
detail = _networkErrorMessage(error);
|
||||
}
|
||||
|
||||
final localized = _localizeError(
|
||||
detail,
|
||||
statusCode,
|
||||
errorCode: errorCode,
|
||||
errorParams: errorParams,
|
||||
);
|
||||
|
||||
if (statusCode == 401) {
|
||||
return UnauthorizedException(message: localized, errorCode: errorCode);
|
||||
}
|
||||
if (statusCode == 422) {
|
||||
return ValidationException(
|
||||
localized,
|
||||
errors: data,
|
||||
statusCode: statusCode,
|
||||
errorCode: errorCode,
|
||||
errorParams: errorParams,
|
||||
);
|
||||
}
|
||||
return ServerException(
|
||||
localized,
|
||||
statusCode: statusCode,
|
||||
errorCode: errorCode,
|
||||
errorParams: errorParams,
|
||||
);
|
||||
}
|
||||
return ServerException(L10n.current.errorNetwork);
|
||||
}
|
||||
|
||||
static Map<String, dynamic>? _normalizeErrorData(dynamic data) {
|
||||
if (data is Map<String, dynamic>) {
|
||||
return data;
|
||||
}
|
||||
if (data is Map) {
|
||||
return data.map((key, value) => MapEntry(key.toString(), value));
|
||||
}
|
||||
if (data is String && data.trim().isNotEmpty) {
|
||||
try {
|
||||
final decoded = jsonDecode(data);
|
||||
if (decoded is Map<String, dynamic>) {
|
||||
return decoded;
|
||||
}
|
||||
if (decoded is Map) {
|
||||
return decoded.map((key, value) => MapEntry(key.toString(), value));
|
||||
}
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
static String _localizeError(
|
||||
String detail,
|
||||
int? statusCode, {
|
||||
String? errorCode,
|
||||
Map<String, dynamic>? errorParams,
|
||||
}) {
|
||||
final mapped = resolveErrorCodeMessage(errorCode, params: errorParams);
|
||||
if (mapped != null && mapped.isNotEmpty) {
|
||||
return mapped;
|
||||
}
|
||||
if (statusCode == 403) {
|
||||
return L10n.current.errorForbidden;
|
||||
}
|
||||
if (statusCode == 404) {
|
||||
return L10n.current.errorNotFound;
|
||||
}
|
||||
if (statusCode == 429) {
|
||||
return L10n.current.errorTooManyRequests;
|
||||
}
|
||||
if (statusCode != null && statusCode >= 500) {
|
||||
return L10n.current.errorServer;
|
||||
}
|
||||
return L10n.current.errorGenericSafe;
|
||||
}
|
||||
|
||||
static String _networkErrorMessage(DioException error) {
|
||||
if (error.type == DioExceptionType.connectionTimeout ||
|
||||
error.type == DioExceptionType.sendTimeout ||
|
||||
error.type == DioExceptionType.receiveTimeout) {
|
||||
return L10n.current.errorNetworkTimeout;
|
||||
}
|
||||
|
||||
if (error.type == DioExceptionType.connectionError ||
|
||||
error.type == DioExceptionType.unknown) {
|
||||
return L10n.current.errorNetworkUnavailable;
|
||||
}
|
||||
|
||||
return L10n.current.errorRequestFailed;
|
||||
}
|
||||
}
|
||||
|
||||
class ServerException extends ApiException {
|
||||
const ServerException(
|
||||
super.message, {
|
||||
super.statusCode,
|
||||
super.errorCode,
|
||||
super.errorParams,
|
||||
});
|
||||
}
|
||||
|
||||
class UnauthorizedException extends ApiException {
|
||||
UnauthorizedException({String? message, String? errorCode})
|
||||
: super(
|
||||
message ?? L10n.current.errorReLogin,
|
||||
statusCode: 401,
|
||||
errorCode: errorCode,
|
||||
);
|
||||
}
|
||||
|
||||
class ValidationException extends ApiException {
|
||||
final Map<String, dynamic>? errors;
|
||||
const ValidationException(
|
||||
super.message, {
|
||||
this.errors,
|
||||
super.statusCode,
|
||||
super.errorCode,
|
||||
super.errorParams,
|
||||
});
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import '../storage/token_storage.dart';
|
||||
|
||||
class ApiInterceptor extends Interceptor {
|
||||
final TokenStorage tokenStorage;
|
||||
final Dio dio;
|
||||
final Duration refreshFailureCooldown;
|
||||
Future<bool> Function()? onTokenRefresh;
|
||||
Future<void> Function()? onAuthFailure;
|
||||
Future<bool>? _refreshFuture;
|
||||
Future<void>? _authFailureFuture;
|
||||
DateTime? _refreshBlockedUntil;
|
||||
|
||||
static const _retriedRequestKey = '_auth_retry_once';
|
||||
static const _refreshPathSuffix = '/api/v1/auth/sessions/refresh';
|
||||
|
||||
ApiInterceptor({
|
||||
required this.tokenStorage,
|
||||
required this.dio,
|
||||
this.refreshFailureCooldown = const Duration(seconds: 5),
|
||||
this.onTokenRefresh,
|
||||
});
|
||||
|
||||
@override
|
||||
void onRequest(
|
||||
RequestOptions options,
|
||||
RequestInterceptorHandler handler,
|
||||
) async {
|
||||
final token = await tokenStorage.getAccessToken();
|
||||
if (token != null) {
|
||||
options.headers['Authorization'] = 'Bearer $token';
|
||||
}
|
||||
handler.next(options);
|
||||
}
|
||||
|
||||
@override
|
||||
void onError(DioException err, ErrorInterceptorHandler handler) async {
|
||||
final requestOptions = err.requestOptions;
|
||||
final isUnauthorized = err.response?.statusCode == 401;
|
||||
final shouldHandleUnauthorized =
|
||||
isUnauthorized && _isAuthenticatedRequest(requestOptions);
|
||||
|
||||
if (err.response?.statusCode == 401 &&
|
||||
onTokenRefresh != null &&
|
||||
!_shouldSkipRefresh(requestOptions)) {
|
||||
final refreshed = await _refreshTokenSingleflight();
|
||||
if (refreshed) {
|
||||
final token = await tokenStorage.getAccessToken();
|
||||
if (token != null) {
|
||||
final retryHeaders = Map<String, dynamic>.from(requestOptions.headers)
|
||||
..['Authorization'] = 'Bearer $token';
|
||||
final retryExtra = Map<String, dynamic>.from(requestOptions.extra)
|
||||
..[_retriedRequestKey] = true;
|
||||
final retryOptions = requestOptions.copyWith(
|
||||
headers: retryHeaders,
|
||||
extra: retryExtra,
|
||||
);
|
||||
try {
|
||||
final response = await dio.fetch(retryOptions);
|
||||
handler.resolve(response);
|
||||
return;
|
||||
} on DioException {
|
||||
// Retry failed, proceed with original error.
|
||||
}
|
||||
}
|
||||
} else if (shouldHandleUnauthorized) {
|
||||
await _notifyAuthFailureSingleflight();
|
||||
}
|
||||
} else if (shouldHandleUnauthorized && _shouldSkipRefresh(requestOptions)) {
|
||||
await _notifyAuthFailureSingleflight();
|
||||
}
|
||||
handler.next(err);
|
||||
}
|
||||
|
||||
bool _isAuthenticatedRequest(RequestOptions options) {
|
||||
return options.headers['Authorization'] != null;
|
||||
}
|
||||
|
||||
Future<void> _notifyAuthFailureSingleflight() {
|
||||
final existing = _authFailureFuture;
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
final callback = onAuthFailure;
|
||||
if (callback == null) {
|
||||
return Future<void>.value();
|
||||
}
|
||||
|
||||
final future = callback().whenComplete(() {
|
||||
_authFailureFuture = null;
|
||||
});
|
||||
_authFailureFuture = future;
|
||||
return future;
|
||||
}
|
||||
|
||||
bool _shouldSkipRefresh(RequestOptions options) {
|
||||
final blockedUntil = _refreshBlockedUntil;
|
||||
if (blockedUntil != null && DateTime.now().isBefore(blockedUntil)) {
|
||||
return true;
|
||||
}
|
||||
return _normalizePath(options.path) == _refreshPathSuffix ||
|
||||
options.extra[_retriedRequestKey] == true;
|
||||
}
|
||||
|
||||
String _normalizePath(String rawPath) {
|
||||
final parsed = Uri.tryParse(rawPath);
|
||||
if (parsed == null) {
|
||||
return rawPath.replaceFirst(RegExp(r'/+$'), '');
|
||||
}
|
||||
final normalized = parsed.path.replaceFirst(RegExp(r'/+$'), '');
|
||||
return normalized.isEmpty ? '/' : normalized;
|
||||
}
|
||||
|
||||
Future<bool> _refreshTokenSingleflight() {
|
||||
final inflight = _refreshFuture;
|
||||
if (inflight != null) {
|
||||
return inflight;
|
||||
}
|
||||
final future = onTokenRefresh!().catchError((_) => false).whenComplete(() {
|
||||
_refreshFuture = null;
|
||||
});
|
||||
_refreshFuture = future;
|
||||
return future.then((refreshed) {
|
||||
if (refreshed) {
|
||||
_refreshBlockedUntil = null;
|
||||
} else {
|
||||
_refreshBlockedUntil = DateTime.now().add(refreshFailureCooldown);
|
||||
}
|
||||
return refreshed;
|
||||
});
|
||||
}
|
||||
|
||||
void reset() {
|
||||
_refreshFuture = null;
|
||||
_authFailureFuture = null;
|
||||
_refreshBlockedUntil = null;
|
||||
}
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
import '../l10n/l10n.dart';
|
||||
|
||||
String? mapErrorCodeToL10nKey(
|
||||
String? errorCode, {
|
||||
Map<String, dynamic>? params,
|
||||
}) {
|
||||
if (errorCode == null || errorCode.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (errorCode) {
|
||||
case 'AGENT_RUN_INPUT_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_RUN_MESSAGES_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_INVALID_LAST_EVENT_ID':
|
||||
return 'errorAgentInvalidLastEventId';
|
||||
case 'AGENT_SSE_CONNECTION_LIMIT':
|
||||
return 'errorAgentSseConnectionLimit';
|
||||
case 'AGENT_ATTACHMENT_EMPTY':
|
||||
return 'errorAgentAttachmentEmpty';
|
||||
case 'AGENT_ATTACHMENT_TOO_LARGE':
|
||||
return 'errorAgentAttachmentTooLarge';
|
||||
case 'AGENT_AUDIO_UNSUPPORTED_FORMAT':
|
||||
return 'errorAgentAudioUnsupportedFormat';
|
||||
case 'AGENT_AUDIO_TOO_LARGE':
|
||||
return 'errorAgentAudioTooLarge';
|
||||
case 'AGENT_AUDIO_EMPTY':
|
||||
return 'errorAgentAudioEmpty';
|
||||
case 'AGENT_ASR_UNAVAILABLE':
|
||||
return 'errorAgentAsrUnavailable';
|
||||
case 'AGENT_FORBIDDEN':
|
||||
return 'errorForbidden';
|
||||
case 'AGENT_PAYLOAD_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_ATTACHMENTS_TOO_MANY':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_SIGNED_IMAGE_URL_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_ATTACHMENT_STORAGE_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'AGENT_ATTACHMENT_UNSUPPORTED_TYPE':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_ATTACHMENT_UPLOAD_FAILED':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_ATTACHMENT_BUCKET_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_ATTACHMENT_PATH_SCOPE_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_SIGNED_URL_GENERATION_FAILED':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_SESSION_ID_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'AGENT_SESSION_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'AGENT_USER_ID_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'INVALID_BINARY_URL_HOST':
|
||||
return 'errorAgentInvalidBinaryUrl';
|
||||
case 'INVALID_BINARY_URL_BUCKET':
|
||||
return 'errorAgentInvalidBinaryUrl';
|
||||
case 'INVALID_BINARY_URL_PATH_SCOPE':
|
||||
return 'errorAgentInvalidBinaryUrl';
|
||||
case 'AUTH_SERVICE_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'AUTH_TOO_MANY_REQUESTS':
|
||||
return 'errorTooManyRequests';
|
||||
case 'AUTH_VERIFICATION_CODE_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'AUTH_REFRESH_TOKEN_INVALID':
|
||||
return 'errorReLogin';
|
||||
case 'AUTH_REFRESH_TOKEN_MISSING':
|
||||
return 'errorReLogin';
|
||||
case 'AUTH_USER_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'AUTH_UNAUTHORIZED':
|
||||
return 'errorReLogin';
|
||||
case 'JWT_VERIFIER_NOT_CONFIGURED':
|
||||
return 'errorServer';
|
||||
case 'AUTOMATION_JOB_LIMIT_EXCEEDED':
|
||||
return 'errorGenericSafe';
|
||||
case 'AUTOMATION_SYSTEM_JOB_MODIFICATION_FORBIDDEN':
|
||||
return 'errorForbidden';
|
||||
case 'AUTOMATION_JOB_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'AUTOMATION_JOB_STORE_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'LOOKUP_FAILED':
|
||||
return 'errorServer';
|
||||
case 'INTERNAL_ERROR':
|
||||
return 'errorServer';
|
||||
case 'MISSING_RUNTIME_ARGS':
|
||||
return 'errorGenericSafe';
|
||||
case 'TOOL_PENDING_APPROVAL':
|
||||
return 'errorGenericSafe';
|
||||
case 'TOOL_REJECTED':
|
||||
return 'errorForbidden';
|
||||
case 'USER_STORE_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'USER_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'USER_UPDATE_FIELDS_EMPTY':
|
||||
return 'errorGenericSafe';
|
||||
case 'USER_AVATAR_UNSUPPORTED_TYPE':
|
||||
return 'errorGenericSafe';
|
||||
case 'USER_AVATAR_TOO_LARGE':
|
||||
return 'errorGenericSafe';
|
||||
case 'USER_AVATAR_EMPTY':
|
||||
return 'errorGenericSafe';
|
||||
case 'USER_AVATAR_UPLOAD_FAILED':
|
||||
return 'errorGenericSafe';
|
||||
case 'USER_AUTH_LOOKUP_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'TODO_SERVICE_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'TODO_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'TODO_ACCESS_FORBIDDEN':
|
||||
return 'errorForbidden';
|
||||
case 'TODO_REORDER_DUPLICATE_ID':
|
||||
return 'errorGenericSafe';
|
||||
case 'TODO_STATUS_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'TODO_PRIORITY_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_INVALID_TIME_RANGE':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_STORE_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'SCHEDULE_ITEM_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'SCHEDULE_ITEM_START_AT_TIMEZONE_REQUIRED':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_PAGE_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_PAGE_SIZE_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_SHARE_FORBIDDEN':
|
||||
return 'errorForbidden';
|
||||
case 'SCHEDULE_ITEM_SHARE_PERMISSION_EXCEEDED':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_SUBSCRIPTION_ALREADY_ACTIVE':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_INVITE_ALREADY_SUBSCRIBED':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_INVITE_ALREADY_PENDING':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_AUTH_LOOKUP_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'SCHEDULE_ITEM_PENDING_INVITE_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'SCHEDULE_ITEM_ACCEPT_SUBSCRIPTION_FAILED':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_REJECT_SUBSCRIPTION_FAILED':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_DATETIME_TIMEZONE_REQUIRED':
|
||||
return 'errorGenericSafe';
|
||||
case 'SCHEDULE_ITEM_DATETIME_REQUIRED':
|
||||
return 'errorGenericSafe';
|
||||
case 'INBOX_MESSAGE_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'INBOX_MESSAGE_STORE_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'MEMORIES_USER_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'MEMORIES_WORK_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'MEMORIES_SERVICE_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'FRIEND_REQUEST_SELF_NOT_ALLOWED':
|
||||
return 'errorGenericSafe';
|
||||
case 'FRIEND_ALREADY_ACCEPTED':
|
||||
return 'errorGenericSafe';
|
||||
case 'FRIEND_REQUEST_BLOCKED':
|
||||
return 'errorGenericSafe';
|
||||
case 'FRIEND_REQUEST_ALREADY_SENT':
|
||||
return 'errorGenericSafe';
|
||||
case 'FRIENDSHIP_SERVICE_UNAVAILABLE':
|
||||
return 'errorServer';
|
||||
case 'FRIEND_REQUEST_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'FRIEND_REQUEST_FORBIDDEN':
|
||||
return 'errorForbidden';
|
||||
case 'FRIEND_REQUEST_NOT_PENDING':
|
||||
return 'errorGenericSafe';
|
||||
case 'FRIEND_INBOX_MESSAGE_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'FRIENDSHIP_DATA_INVALID':
|
||||
return 'errorGenericSafe';
|
||||
case 'FRIENDSHIP_NOT_FOUND':
|
||||
return 'errorNotFound';
|
||||
case 'FRIENDSHIP_REMOVE_REQUIRES_ACCEPTED':
|
||||
return 'errorGenericSafe';
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
String? resolveErrorCodeMessage(
|
||||
String? errorCode, {
|
||||
Map<String, dynamic>? params,
|
||||
}) {
|
||||
final key = mapErrorCodeToL10nKey(errorCode, params: params);
|
||||
if (key == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (key) {
|
||||
case 'errorAgentSseConnectionLimit':
|
||||
return L10n.current.errorAgentSseConnectionLimit;
|
||||
case 'errorAgentAttachmentEmpty':
|
||||
return L10n.current.errorAgentAttachmentEmpty;
|
||||
case 'errorAgentAttachmentTooLarge':
|
||||
return L10n.current.errorAgentAttachmentTooLarge;
|
||||
case 'errorAgentAudioEmpty':
|
||||
return L10n.current.errorAgentAudioEmpty;
|
||||
case 'errorAgentAudioTooLarge':
|
||||
return L10n.current.errorAgentAudioTooLarge;
|
||||
case 'errorAgentAudioUnsupportedFormat':
|
||||
return L10n.current.errorAgentAudioUnsupportedFormat;
|
||||
case 'errorAgentAsrUnavailable':
|
||||
return L10n.current.errorAgentAsrUnavailable;
|
||||
case 'errorAgentInvalidLastEventId':
|
||||
return L10n.current.errorAgentInvalidLastEventId;
|
||||
case 'errorAgentInvalidBinaryUrl':
|
||||
return L10n.current.errorAgentInvalidBinaryUrl;
|
||||
case 'errorForbidden':
|
||||
return L10n.current.errorForbidden;
|
||||
case 'errorNotFound':
|
||||
return L10n.current.errorNotFound;
|
||||
case 'errorTooManyRequests':
|
||||
return L10n.current.errorTooManyRequests;
|
||||
case 'errorServer':
|
||||
return L10n.current.errorServer;
|
||||
case 'errorGenericSafe':
|
||||
return L10n.current.errorGenericSafe;
|
||||
case 'errorReLogin':
|
||||
return L10n.current.errorReLogin;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
abstract class IApiClient {
|
||||
Future<Response<T>> get<T>(String path, {Options? options});
|
||||
Future<Response<T>> post<T>(String path, {dynamic data, Options? options});
|
||||
Future<Response<T>> put<T>(String path, {dynamic data, Options? options});
|
||||
Future<Response<T>> patch<T>(String path, {dynamic data, Options? options});
|
||||
Future<Response<T>> delete<T>(String path, {dynamic data, Options? options});
|
||||
Future<Stream<String>> getSseLines(
|
||||
String path, {
|
||||
Map<String, String>? headers,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
class ReminderPayload {
|
||||
final String eventId;
|
||||
final String title;
|
||||
final DateTime startAt;
|
||||
final DateTime? endAt;
|
||||
final String timezone;
|
||||
final String? location;
|
||||
final String? notes;
|
||||
final String? color;
|
||||
final ReminderPayloadMode mode;
|
||||
final List<String> aggregateIds;
|
||||
final int? fireTimeBucket;
|
||||
final int version;
|
||||
|
||||
const ReminderPayload({
|
||||
required this.eventId,
|
||||
required this.title,
|
||||
required this.startAt,
|
||||
required this.timezone,
|
||||
this.endAt,
|
||||
this.location,
|
||||
this.notes,
|
||||
this.color,
|
||||
this.mode = ReminderPayloadMode.single,
|
||||
this.aggregateIds = const [],
|
||||
this.fireTimeBucket,
|
||||
this.version = 1,
|
||||
});
|
||||
|
||||
ReminderPayload copyWith({
|
||||
String? eventId,
|
||||
String? title,
|
||||
DateTime? startAt,
|
||||
DateTime? endAt,
|
||||
String? timezone,
|
||||
String? location,
|
||||
String? notes,
|
||||
String? color,
|
||||
ReminderPayloadMode? mode,
|
||||
List<String>? aggregateIds,
|
||||
int? fireTimeBucket,
|
||||
int? version,
|
||||
}) {
|
||||
return ReminderPayload(
|
||||
eventId: eventId ?? this.eventId,
|
||||
title: title ?? this.title,
|
||||
startAt: startAt ?? this.startAt,
|
||||
endAt: endAt ?? this.endAt,
|
||||
timezone: timezone ?? this.timezone,
|
||||
location: location ?? this.location,
|
||||
notes: notes ?? this.notes,
|
||||
color: color ?? this.color,
|
||||
mode: mode ?? this.mode,
|
||||
aggregateIds: aggregateIds ?? this.aggregateIds,
|
||||
fireTimeBucket: fireTimeBucket ?? this.fireTimeBucket,
|
||||
version: version ?? this.version,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'eventId': eventId,
|
||||
'title': title,
|
||||
'startAt': startAt.toIso8601String(),
|
||||
'endAt': endAt?.toIso8601String(),
|
||||
'timezone': timezone,
|
||||
'location': location,
|
||||
'notes': notes,
|
||||
'color': color,
|
||||
'mode': mode.value,
|
||||
'aggregateIds': aggregateIds,
|
||||
'fireTimeBucket': fireTimeBucket,
|
||||
'version': version,
|
||||
};
|
||||
}
|
||||
|
||||
factory ReminderPayload.fromJson(Map<String, dynamic> json) {
|
||||
final eventId = (json['eventId'] as String?) ?? '';
|
||||
if (eventId.isEmpty) {
|
||||
throw const FormatException('eventId is required');
|
||||
}
|
||||
|
||||
final startAtRaw = json['startAt'] as String?;
|
||||
if (startAtRaw == null || startAtRaw.isEmpty) {
|
||||
throw const FormatException('startAt is required');
|
||||
}
|
||||
final parsedStartAt = DateTime.parse(startAtRaw);
|
||||
|
||||
final mode = ReminderPayloadMode.fromValue(
|
||||
(json['mode'] as String?) ?? 'single',
|
||||
);
|
||||
final aggregateIds = (json['aggregateIds'] as List<dynamic>? ?? const [])
|
||||
.map((item) => item.toString())
|
||||
.toList();
|
||||
if (mode == ReminderPayloadMode.aggregate && aggregateIds.length < 2) {
|
||||
throw const FormatException('aggregateIds must contain at least 2 items');
|
||||
}
|
||||
|
||||
return ReminderPayload(
|
||||
eventId: eventId,
|
||||
title: (json['title'] as String?) ?? '',
|
||||
startAt: parsedStartAt,
|
||||
endAt: json['endAt'] != null
|
||||
? DateTime.parse(json['endAt'] as String)
|
||||
: null,
|
||||
timezone: (json['timezone'] as String?) ?? 'UTC',
|
||||
location: json['location'] as String?,
|
||||
notes: json['notes'] as String?,
|
||||
color: json['color'] as String?,
|
||||
mode: mode,
|
||||
aggregateIds: aggregateIds,
|
||||
fireTimeBucket: json['fireTimeBucket'] as int?,
|
||||
version: (json['version'] as int?) ?? 1,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) {
|
||||
return true;
|
||||
}
|
||||
return other is ReminderPayload &&
|
||||
other.eventId == eventId &&
|
||||
other.title == title &&
|
||||
other.startAt == startAt &&
|
||||
other.endAt == endAt &&
|
||||
other.timezone == timezone &&
|
||||
other.location == location &&
|
||||
other.notes == notes &&
|
||||
other.color == color &&
|
||||
other.mode == mode &&
|
||||
_listEquals(other.aggregateIds, aggregateIds) &&
|
||||
other.fireTimeBucket == fireTimeBucket &&
|
||||
other.version == version;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
eventId,
|
||||
title,
|
||||
startAt,
|
||||
endAt,
|
||||
timezone,
|
||||
location,
|
||||
notes,
|
||||
color,
|
||||
mode,
|
||||
Object.hashAll(aggregateIds),
|
||||
fireTimeBucket,
|
||||
version,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum ReminderPayloadMode {
|
||||
single('single'),
|
||||
aggregate('aggregate');
|
||||
|
||||
const ReminderPayloadMode(this.value);
|
||||
|
||||
final String value;
|
||||
|
||||
static ReminderPayloadMode fromValue(String raw) {
|
||||
return ReminderPayloadMode.values.firstWhere(
|
||||
(item) => item.value == raw,
|
||||
orElse: () => ReminderPayloadMode.single,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bool _listEquals(List<String> left, List<String> right) {
|
||||
if (left.length != right.length) {
|
||||
return false;
|
||||
}
|
||||
for (var i = 0; i < left.length; i++) {
|
||||
if (left[i] != right[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import '../models/reminder_payload.dart';
|
||||
|
||||
class ReminderQueueManager {
|
||||
ReminderPayload? _currentPayload;
|
||||
final List<ReminderPayload> _pending = [];
|
||||
|
||||
void enqueueFromClick(ReminderPayload payload) {
|
||||
_currentPayload = payload;
|
||||
}
|
||||
|
||||
void enqueuePending(List<ReminderPayload> payloads) {
|
||||
payloads.sort((a, b) => a.startAt.compareTo(b.startAt));
|
||||
_pending.addAll(payloads);
|
||||
}
|
||||
|
||||
ReminderPayload? get currentPayload => _currentPayload;
|
||||
|
||||
bool get isEmpty => _currentPayload == null && _pending.isEmpty;
|
||||
|
||||
void dequeueCurrent() {
|
||||
_currentPayload = null;
|
||||
if (_pending.isNotEmpty) {
|
||||
_currentPayload = _pending.removeAt(0);
|
||||
}
|
||||
}
|
||||
|
||||
void clear() {
|
||||
_currentPayload = null;
|
||||
_pending.clear();
|
||||
}
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import '../../data/models/reminder_payload.dart';
|
||||
|
||||
class AppPreferences {
|
||||
static const String _pendingNotificationsKey =
|
||||
'calendar_reminder_pending_notification_responses_v1';
|
||||
static const String _pendingNotificationPayloadKey =
|
||||
'pending_notification_payload';
|
||||
|
||||
final SharedPreferences _prefs;
|
||||
|
||||
AppPreferences(this._prefs);
|
||||
|
||||
List<PendingNotificationResponse> get pendingNotifications {
|
||||
final list = _prefs.getStringList(_pendingNotificationsKey) ?? [];
|
||||
return list
|
||||
.map(_decodePendingNotification)
|
||||
.whereType<PendingNotificationResponse>()
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<void> setPendingNotifications(
|
||||
List<PendingNotificationResponse> value,
|
||||
) {
|
||||
return _prefs.setStringList(
|
||||
_pendingNotificationsKey,
|
||||
value.map(_encodePendingNotification).toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> clearPendingNotifications() {
|
||||
return _prefs.remove(_pendingNotificationsKey);
|
||||
}
|
||||
|
||||
ReminderPayload? get pendingNotificationPayload {
|
||||
final raw = _prefs.getString(_pendingNotificationPayloadKey);
|
||||
if (raw == null || raw.isEmpty) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
final json = Map<String, dynamic>.from(jsonDecode(raw) as Map);
|
||||
return ReminderPayload.fromJson(json);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> setPendingNotificationPayload(ReminderPayload payload) {
|
||||
return _prefs.setString(
|
||||
_pendingNotificationPayloadKey,
|
||||
jsonEncode(payload.toJson()),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> clearPendingNotificationPayload() {
|
||||
return _prefs.remove(_pendingNotificationPayloadKey);
|
||||
}
|
||||
|
||||
static String _encodePendingNotification(
|
||||
PendingNotificationResponse response,
|
||||
) {
|
||||
return jsonEncode({
|
||||
'id': response.id,
|
||||
'actionId': response.actionId,
|
||||
'payload': response.payload,
|
||||
'type': response.notificationResponseType.index,
|
||||
'input': response.input,
|
||||
});
|
||||
}
|
||||
|
||||
static PendingNotificationResponse? _decodePendingNotification(String raw) {
|
||||
try {
|
||||
final parsed = Map<String, dynamic>.from(jsonDecode(raw) as Map);
|
||||
final id = parsed['id'] as int?;
|
||||
final actionId = parsed['actionId'] as String?;
|
||||
final payload = parsed['payload'] as String?;
|
||||
final typeIndex = (parsed['type'] as int?) ?? 0;
|
||||
final input = parsed['input'] as String?;
|
||||
final type = NotificationResponseType.values[typeIndex.clamp(0, 1)];
|
||||
return NotificationResponse(
|
||||
id: id,
|
||||
actionId: actionId,
|
||||
payload: payload,
|
||||
input: input,
|
||||
notificationResponseType: type,
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
typedef PendingNotificationResponse = NotificationResponse;
|
||||
@@ -1,40 +0,0 @@
|
||||
abstract class TokenStorage {
|
||||
Future<String?> getAccessToken();
|
||||
Future<String?> getRefreshToken();
|
||||
Future<void> saveTokens({required String access, required String refresh});
|
||||
Future<void> clear();
|
||||
}
|
||||
|
||||
class SecureTokenStorage implements TokenStorage {
|
||||
static const _accessTokenKey = 'access_token';
|
||||
static const _refreshTokenKey = 'refresh_token';
|
||||
|
||||
final dynamic _storage;
|
||||
|
||||
SecureTokenStorage([this._storage]);
|
||||
|
||||
@override
|
||||
Future<String?> getAccessToken() async {
|
||||
return _storage?.read(key: _accessTokenKey);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> getRefreshToken() async {
|
||||
return _storage?.read(key: _refreshTokenKey);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> saveTokens({
|
||||
required String access,
|
||||
required String refresh,
|
||||
}) async {
|
||||
await _storage?.write(key: _accessTokenKey, value: access);
|
||||
await _storage?.write(key: _refreshTokenKey, value: refresh);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clear() async {
|
||||
await _storage?.delete(key: _accessTokenKey);
|
||||
await _storage?.delete(key: _refreshTokenKey);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
part of 'ui_schema.dart';
|
||||
|
||||
abstract class ActionSpec {
|
||||
String get type;
|
||||
Map<String, dynamic> toJson();
|
||||
}
|
||||
|
||||
class NavigateAction implements ActionSpec {
|
||||
final String path;
|
||||
final Map<String, dynamic>? params;
|
||||
|
||||
const NavigateAction({required this.path, this.params});
|
||||
|
||||
@override
|
||||
String get type => 'navigation';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {'type': type, 'path': path, if (params != null) 'params': params};
|
||||
}
|
||||
}
|
||||
|
||||
class LinkAction implements ActionSpec {
|
||||
final String url;
|
||||
final String? target;
|
||||
|
||||
const LinkAction({required this.url, this.target});
|
||||
|
||||
@override
|
||||
String get type => 'url';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {'type': type, 'url': url, if (target != null) 'target': target};
|
||||
}
|
||||
}
|
||||
|
||||
class EventAction implements ActionSpec {
|
||||
final String event;
|
||||
final Map<String, dynamic>? payload;
|
||||
|
||||
const EventAction({required this.event, this.payload});
|
||||
|
||||
@override
|
||||
String get type => 'event';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'event': event,
|
||||
if (payload != null) 'payload': payload,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class ToolAction implements ActionSpec {
|
||||
final String toolId;
|
||||
final Map<String, dynamic>? params;
|
||||
|
||||
const ToolAction({required this.toolId, this.params});
|
||||
|
||||
@override
|
||||
String get type => 'tool';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'toolId': toolId,
|
||||
if (params != null) 'params': params,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class CopyAction implements ActionSpec {
|
||||
final String content;
|
||||
final String? successMessage;
|
||||
|
||||
const CopyAction({required this.content, this.successMessage});
|
||||
|
||||
@override
|
||||
String get type => 'copy';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'content': content,
|
||||
if (successMessage != null) 'successMessage': successMessage,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class PayloadAction implements ActionSpec {
|
||||
final Map<String, dynamic> payload;
|
||||
final String? submitTo;
|
||||
|
||||
const PayloadAction({required this.payload, this.submitTo});
|
||||
|
||||
@override
|
||||
String get type => 'payload';
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'type': type,
|
||||
'payload': payload,
|
||||
if (submitTo != null) 'submitTo': submitTo,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
ActionSpec actionSpecFromJson(Map<String, dynamic> json) {
|
||||
final type = json['type'] as String? ?? '';
|
||||
switch (type) {
|
||||
case 'navigation':
|
||||
return NavigateAction(
|
||||
path: json['path'] as String? ?? '',
|
||||
params: json['params'] as Map<String, dynamic>?,
|
||||
);
|
||||
case 'url':
|
||||
return LinkAction(
|
||||
url: json['url'] as String? ?? '',
|
||||
target: json['target'] as String?,
|
||||
);
|
||||
case 'event':
|
||||
return EventAction(
|
||||
event: json['event'] as String? ?? '',
|
||||
payload: json['payload'] as Map<String, dynamic>?,
|
||||
);
|
||||
case 'tool':
|
||||
return ToolAction(
|
||||
toolId: json['toolId'] as String? ?? '',
|
||||
params: json['params'] as Map<String, dynamic>?,
|
||||
);
|
||||
case 'copy':
|
||||
return CopyAction(
|
||||
content: json['content'] as String? ?? '',
|
||||
successMessage: json['successMessage'] as String?,
|
||||
);
|
||||
case 'payload':
|
||||
return PayloadAction(
|
||||
payload: json['payload'] as Map<String, dynamic>? ?? {},
|
||||
submitTo: json['submitTo'] as String?,
|
||||
);
|
||||
default:
|
||||
return EventAction(event: 'unknown');
|
||||
}
|
||||
}
|
||||
|
||||
class UiAction {
|
||||
final String id;
|
||||
final String label;
|
||||
final UiIcon? icon;
|
||||
final ActionStyle? style;
|
||||
final bool disabled;
|
||||
final ActionSpec action;
|
||||
final ActionConfirm? confirm;
|
||||
|
||||
const UiAction({
|
||||
required this.id,
|
||||
required this.label,
|
||||
this.icon,
|
||||
this.style,
|
||||
this.disabled = false,
|
||||
required this.action,
|
||||
this.confirm,
|
||||
});
|
||||
|
||||
factory UiAction.fromJson(Map<String, dynamic> json) {
|
||||
return UiAction(
|
||||
id: json['id'] as String? ?? '',
|
||||
label: json['label'] as String? ?? '',
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
style: json['style'] != null
|
||||
? ActionStyle.values.firstWhere(
|
||||
(e) => e.value == json['style'],
|
||||
orElse: () => ActionStyle.primary,
|
||||
)
|
||||
: null,
|
||||
disabled: json['disabled'] as bool? ?? false,
|
||||
action: actionSpecFromJson(
|
||||
json['action'] as Map<String, dynamic>? ?? {'type': 'event'},
|
||||
),
|
||||
confirm: json['confirm'] != null
|
||||
? ActionConfirm.fromJson(json['confirm'] as Map<String, dynamic>)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'label': label,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (style != null) 'style': style!.value,
|
||||
'disabled': disabled,
|
||||
'action': action.toJson(),
|
||||
if (confirm != null) 'confirm': confirm!.toJson(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
part of 'ui_schema.dart';
|
||||
|
||||
UiSchemaDocument buildSuccessDocument(
|
||||
List<UiNode> nodes, {
|
||||
String version = '1.0',
|
||||
SchemaType schemaType = SchemaType.toolResult,
|
||||
String? docId,
|
||||
String? timestamp,
|
||||
String locale = 'zh-CN',
|
||||
RendererConfig? renderer,
|
||||
DocumentMeta? meta,
|
||||
}) {
|
||||
return UiSchemaDocument(
|
||||
version: version,
|
||||
schemaType: schemaType,
|
||||
docId: docId,
|
||||
timestamp: timestamp,
|
||||
locale: locale,
|
||||
status: UiStatus.success,
|
||||
renderer: renderer,
|
||||
meta: meta,
|
||||
nodes: nodes,
|
||||
);
|
||||
}
|
||||
|
||||
UiSchemaDocument buildErrorDocument(
|
||||
List<UiNode> nodes, {
|
||||
String version = '1.0',
|
||||
SchemaType schemaType = SchemaType.toolResult,
|
||||
String? docId,
|
||||
String? timestamp,
|
||||
String locale = 'zh-CN',
|
||||
RendererConfig? renderer,
|
||||
DocumentMeta? meta,
|
||||
}) {
|
||||
return UiSchemaDocument(
|
||||
version: version,
|
||||
schemaType: schemaType,
|
||||
docId: docId,
|
||||
timestamp: timestamp,
|
||||
locale: locale,
|
||||
status: UiStatus.error,
|
||||
renderer: renderer,
|
||||
meta: meta,
|
||||
nodes: nodes,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
part of 'ui_schema.dart';
|
||||
|
||||
class UiIcon {
|
||||
final IconSource source;
|
||||
final String value;
|
||||
final String? color;
|
||||
final int? size;
|
||||
|
||||
const UiIcon({
|
||||
required this.source,
|
||||
required this.value,
|
||||
this.color,
|
||||
this.size,
|
||||
});
|
||||
|
||||
factory UiIcon.fromJson(Map<String, dynamic> json) {
|
||||
return UiIcon(
|
||||
source: IconSource.values.firstWhere(
|
||||
(e) => e.value == json['source'],
|
||||
orElse: () => IconSource.icon,
|
||||
),
|
||||
value: json['value'] as String? ?? '',
|
||||
color: json['color'] as String?,
|
||||
size: json['size'] as int?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'source': source.value,
|
||||
'value': value,
|
||||
if (color != null) 'color': color,
|
||||
if (size != null) 'size': size,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiBadge {
|
||||
final String label;
|
||||
final BadgeVariant variant;
|
||||
|
||||
const UiBadge({required this.label, this.variant = BadgeVariant.def});
|
||||
|
||||
factory UiBadge.fromJson(Map<String, dynamic> json) {
|
||||
return UiBadge(
|
||||
label: json['label'] as String? ?? '',
|
||||
variant: BadgeVariant.values.firstWhere(
|
||||
(e) => e.value == json['variant'],
|
||||
orElse: () => BadgeVariant.def,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {'label': label, 'variant': variant.value};
|
||||
}
|
||||
}
|
||||
|
||||
class Pagination {
|
||||
final int page;
|
||||
final int pageSize;
|
||||
final int total;
|
||||
final bool hasMore;
|
||||
|
||||
const Pagination({
|
||||
required this.page,
|
||||
required this.pageSize,
|
||||
required this.total,
|
||||
required this.hasMore,
|
||||
});
|
||||
|
||||
factory Pagination.fromJson(Map<String, dynamic> json) {
|
||||
return Pagination(
|
||||
page: json['page'] as int? ?? 1,
|
||||
pageSize: json['pageSize'] as int? ?? 20,
|
||||
total: json['total'] as int? ?? 0,
|
||||
hasMore: json['hasMore'] as bool? ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'page': page,
|
||||
'pageSize': pageSize,
|
||||
'total': total,
|
||||
'hasMore': hasMore,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class ActionConfirm {
|
||||
final String? title;
|
||||
final String? message;
|
||||
final String? confirmLabel;
|
||||
final String? cancelLabel;
|
||||
|
||||
const ActionConfirm({
|
||||
this.title,
|
||||
this.message,
|
||||
this.confirmLabel,
|
||||
this.cancelLabel,
|
||||
});
|
||||
|
||||
factory ActionConfirm.fromJson(Map<String, dynamic> json) {
|
||||
return ActionConfirm(
|
||||
title: json['title'] as String?,
|
||||
message: json['message'] as String?,
|
||||
confirmLabel: json['confirmLabel'] as String?,
|
||||
cancelLabel: json['cancelLabel'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
if (title != null) 'title': title,
|
||||
if (message != null) 'message': message,
|
||||
if (confirmLabel != null) 'confirmLabel': confirmLabel,
|
||||
if (cancelLabel != null) 'cancelLabel': cancelLabel,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class KeyValuePair {
|
||||
final String key;
|
||||
final String? label;
|
||||
final dynamic value;
|
||||
final bool? copyable;
|
||||
|
||||
const KeyValuePair({
|
||||
required this.key,
|
||||
this.label,
|
||||
required this.value,
|
||||
this.copyable,
|
||||
});
|
||||
|
||||
factory KeyValuePair.fromJson(Map<String, dynamic> json) {
|
||||
return KeyValuePair(
|
||||
key: json['key'] as String? ?? '',
|
||||
label: json['label'] as String?,
|
||||
value: json['value'],
|
||||
copyable: json['copyable'] as bool?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'key': key,
|
||||
if (label != null) 'label': label,
|
||||
'value': value,
|
||||
if (copyable != null) 'copyable': copyable,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class TableColumn {
|
||||
final String key;
|
||||
final String label;
|
||||
final String? width;
|
||||
final String? align;
|
||||
|
||||
const TableColumn({
|
||||
required this.key,
|
||||
required this.label,
|
||||
this.width,
|
||||
this.align,
|
||||
});
|
||||
|
||||
factory TableColumn.fromJson(Map<String, dynamic> json) {
|
||||
return TableColumn(
|
||||
key: json['key'] as String? ?? '',
|
||||
label: json['label'] as String? ?? '',
|
||||
width: json['width'] as String?,
|
||||
align: json['align'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'key': key,
|
||||
'label': label,
|
||||
if (width != null) 'width': width,
|
||||
if (align != null) 'align': align,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class TableRow {
|
||||
final String id;
|
||||
final Map<String, dynamic> cells;
|
||||
final Map<String, dynamic>? metadata;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const TableRow({
|
||||
required this.id,
|
||||
required this.cells,
|
||||
this.metadata,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory TableRow.fromJson(Map<String, dynamic> json) {
|
||||
return TableRow(
|
||||
id: json['id'] as String? ?? '',
|
||||
cells: json['cells'] as Map<String, dynamic>? ?? {},
|
||||
metadata: json['metadata'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'cells': cells,
|
||||
if (metadata != null) 'metadata': metadata,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class ListItem {
|
||||
final String id;
|
||||
final String title;
|
||||
final String? subtitle;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiBadge? badge;
|
||||
final Map<String, dynamic>? metadata;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const ListItem({
|
||||
required this.id,
|
||||
required this.title,
|
||||
this.subtitle,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.badge,
|
||||
this.metadata,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory ListItem.fromJson(Map<String, dynamic> json) {
|
||||
return ListItem(
|
||||
id: json['id'] as String? ?? '',
|
||||
title: json['title'] as String? ?? '',
|
||||
subtitle: json['subtitle'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
badge: json['badge'] != null
|
||||
? UiBadge.fromJson(json['badge'] as Map<String, dynamic>)
|
||||
: null,
|
||||
metadata: json['metadata'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'title': title,
|
||||
if (subtitle != null) 'subtitle': subtitle,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (badge != null) 'badge': badge!.toJson(),
|
||||
if (metadata != null) 'metadata': metadata,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
part of 'ui_schema.dart';
|
||||
|
||||
class RendererConfig {
|
||||
final String? renderer;
|
||||
final RendererTheme? theme;
|
||||
|
||||
const RendererConfig({this.renderer, this.theme});
|
||||
|
||||
factory RendererConfig.fromJson(Map<String, dynamic> json) {
|
||||
return RendererConfig(
|
||||
renderer: json['renderer'] as String?,
|
||||
theme: json['theme'] != null
|
||||
? RendererTheme.values.firstWhere(
|
||||
(e) => e.value == json['theme'],
|
||||
orElse: () => RendererTheme.def,
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
if (renderer != null) 'renderer': renderer,
|
||||
if (theme != null) 'theme': theme!.value,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class DocumentMeta {
|
||||
final String? requestId;
|
||||
final String? toolId;
|
||||
final String? traceId;
|
||||
final String? userId;
|
||||
final Map<String, dynamic>? extra;
|
||||
|
||||
const DocumentMeta({
|
||||
this.requestId,
|
||||
this.toolId,
|
||||
this.traceId,
|
||||
this.userId,
|
||||
this.extra,
|
||||
});
|
||||
|
||||
factory DocumentMeta.fromJson(Map<String, dynamic> json) {
|
||||
return DocumentMeta(
|
||||
requestId: json['requestId'] as String?,
|
||||
toolId: json['toolId'] as String?,
|
||||
traceId: json['traceId'] as String?,
|
||||
userId: json['userId'] as String?,
|
||||
extra: json,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
if (requestId != null) 'requestId': requestId,
|
||||
if (toolId != null) 'toolId': toolId,
|
||||
if (traceId != null) 'traceId': traceId,
|
||||
if (userId != null) 'userId': userId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiSchemaDocument {
|
||||
final String version;
|
||||
final SchemaType schemaType;
|
||||
final String? docId;
|
||||
final String? timestamp;
|
||||
final String? locale;
|
||||
final UiStatus status;
|
||||
final RendererConfig? renderer;
|
||||
final DocumentMeta? meta;
|
||||
final List<UiNode> nodes;
|
||||
|
||||
const UiSchemaDocument({
|
||||
required this.version,
|
||||
required this.schemaType,
|
||||
this.docId,
|
||||
this.timestamp,
|
||||
this.locale,
|
||||
required this.status,
|
||||
this.renderer,
|
||||
this.meta,
|
||||
required this.nodes,
|
||||
});
|
||||
|
||||
factory UiSchemaDocument.fromJson(Map<String, dynamic> json) {
|
||||
return UiSchemaDocument(
|
||||
version: json['version'] as String? ?? '1.0',
|
||||
schemaType: SchemaType.values.firstWhere(
|
||||
(e) => e.value == json['schemaType'],
|
||||
orElse: () => SchemaType.toolResult,
|
||||
),
|
||||
docId: json['docId'] as String?,
|
||||
timestamp: json['timestamp'] as String?,
|
||||
locale: json['locale'] as String?,
|
||||
status: UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
),
|
||||
renderer: json['renderer'] != null
|
||||
? RendererConfig.fromJson(json['renderer'] as Map<String, dynamic>)
|
||||
: null,
|
||||
meta: json['meta'] != null
|
||||
? DocumentMeta.fromJson(json['meta'] as Map<String, dynamic>)
|
||||
: null,
|
||||
nodes:
|
||||
(json['nodes'] as List<dynamic>?)
|
||||
?.map((e) => UiNode.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'version': version,
|
||||
'schemaType': schemaType.value,
|
||||
if (docId != null) 'docId': docId,
|
||||
if (timestamp != null) 'timestamp': timestamp,
|
||||
if (locale != null) 'locale': locale,
|
||||
'status': status.value,
|
||||
if (renderer != null) 'renderer': renderer!.toJson(),
|
||||
if (meta != null) 'meta': meta!.toJson(),
|
||||
'nodes': nodes.map((e) => (e as dynamic).toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
part of 'ui_schema.dart';
|
||||
|
||||
enum SchemaType {
|
||||
toolResult('tool_result'),
|
||||
agentResponse('agent_response'),
|
||||
notification('notification');
|
||||
|
||||
final String value;
|
||||
const SchemaType(this.value);
|
||||
}
|
||||
|
||||
enum UiStatus {
|
||||
info('info'),
|
||||
success('success'),
|
||||
warning('warning'),
|
||||
error('error'),
|
||||
pending('pending');
|
||||
|
||||
final String value;
|
||||
const UiStatus(this.value);
|
||||
}
|
||||
|
||||
enum IconSource {
|
||||
icon('icon'),
|
||||
emoji('emoji'),
|
||||
url('url');
|
||||
|
||||
final String value;
|
||||
const IconSource(this.value);
|
||||
}
|
||||
|
||||
enum OperationType {
|
||||
create('create'),
|
||||
update('update'),
|
||||
delete('delete'),
|
||||
execute('execute');
|
||||
|
||||
final String value;
|
||||
const OperationType(this.value);
|
||||
}
|
||||
|
||||
enum OperationResult {
|
||||
success('success'),
|
||||
failure('failure'),
|
||||
partial('partial');
|
||||
|
||||
final String value;
|
||||
const OperationResult(this.value);
|
||||
}
|
||||
|
||||
enum ContainerDirection {
|
||||
vertical('vertical'),
|
||||
horizontal('horizontal');
|
||||
|
||||
final String value;
|
||||
const ContainerDirection(this.value);
|
||||
}
|
||||
|
||||
enum TextFormat {
|
||||
plain('plain'),
|
||||
markdown('markdown');
|
||||
|
||||
final String value;
|
||||
const TextFormat(this.value);
|
||||
}
|
||||
|
||||
enum KvLayout {
|
||||
vertical('vertical'),
|
||||
horizontal('horizontal'),
|
||||
grid('grid');
|
||||
|
||||
final String value;
|
||||
const KvLayout(this.value);
|
||||
}
|
||||
|
||||
enum BadgeVariant {
|
||||
def('default'),
|
||||
success('success'),
|
||||
warning('warning'),
|
||||
error('error'),
|
||||
info('info');
|
||||
|
||||
final String value;
|
||||
const BadgeVariant(this.value);
|
||||
}
|
||||
|
||||
enum ActionStyle {
|
||||
primary('primary'),
|
||||
secondary('secondary'),
|
||||
ghost('ghost'),
|
||||
danger('danger');
|
||||
|
||||
final String value;
|
||||
const ActionStyle(this.value);
|
||||
}
|
||||
|
||||
enum RendererTheme {
|
||||
def('default'),
|
||||
dark('dark'),
|
||||
light('light');
|
||||
|
||||
final String value;
|
||||
const RendererTheme(this.value);
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
part of 'ui_schema.dart';
|
||||
|
||||
abstract class UiNode {
|
||||
String get type;
|
||||
String? get id;
|
||||
|
||||
factory UiNode.fromJson(Map<String, dynamic> json) {
|
||||
final type = json['type'] as String? ?? '';
|
||||
switch (type) {
|
||||
case 'text':
|
||||
return UiTextNode.fromJson(json);
|
||||
case 'card':
|
||||
return UiCardNode.fromJson(json);
|
||||
case 'list':
|
||||
return UiListNode.fromJson(json);
|
||||
case 'table':
|
||||
return UiTableNode.fromJson(json);
|
||||
case 'kv':
|
||||
return UiKvNode.fromJson(json);
|
||||
case 'operation':
|
||||
return UiOperationNode.fromJson(json);
|
||||
case 'error':
|
||||
return UiErrorNode.fromJson(json);
|
||||
case 'container':
|
||||
return UiContainerNode.fromJson(json);
|
||||
default:
|
||||
return UiTextNode(content: 'Unknown node type: $type');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class UiTextNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'text';
|
||||
final String content;
|
||||
final TextFormat format;
|
||||
final UiIcon? icon;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiTextNode({
|
||||
this.id,
|
||||
required this.content,
|
||||
this.format = TextFormat.plain,
|
||||
this.icon,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiTextNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiTextNode(
|
||||
id: json['id'] as String?,
|
||||
content: json['content'] as String? ?? '',
|
||||
format: TextFormat.values.firstWhere(
|
||||
(e) => e.value == json['format'],
|
||||
orElse: () => TextFormat.plain,
|
||||
),
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
'content': content,
|
||||
'format': format.value,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiCardNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'card';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final String? timestamp;
|
||||
final List<UiNode>? children;
|
||||
final UiTextNode? footer;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiCardNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
this.timestamp,
|
||||
this.children,
|
||||
this.footer,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiCardNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiCardNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
timestamp: json['timestamp'] as String?,
|
||||
children: (json['children'] as List<dynamic>?)
|
||||
?.map((e) => UiNode.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
footer: json['footer'] != null
|
||||
? UiTextNode.fromJson(json['footer'] as Map<String, dynamic>)
|
||||
: null,
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
if (timestamp != null) 'timestamp': timestamp,
|
||||
if (children != null)
|
||||
'children': children!.map((e) => (e as dynamic).toJson()).toList(),
|
||||
if (footer != null) 'footer': footer!.toJson(),
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiListNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'list';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final List<ListItem> items;
|
||||
final Pagination? pagination;
|
||||
final String? emptyText;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiListNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
required this.items,
|
||||
this.pagination,
|
||||
this.emptyText,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiListNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiListNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
items:
|
||||
(json['items'] as List<dynamic>?)
|
||||
?.map((e) => ListItem.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
pagination: json['pagination'] != null
|
||||
? Pagination.fromJson(json['pagination'] as Map<String, dynamic>)
|
||||
: null,
|
||||
emptyText: json['emptyText'] as String?,
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
'items': items.map((e) => e.toJson()).toList(),
|
||||
if (pagination != null) 'pagination': pagination!.toJson(),
|
||||
if (emptyText != null) 'emptyText': emptyText,
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiTableNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'table';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final List<TableColumn> columns;
|
||||
final List<TableRow> rows;
|
||||
final Pagination? pagination;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiTableNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
required this.columns,
|
||||
required this.rows,
|
||||
this.pagination,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiTableNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiTableNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
columns:
|
||||
(json['columns'] as List<dynamic>?)
|
||||
?.map((e) => TableColumn.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
rows:
|
||||
(json['rows'] as List<dynamic>?)
|
||||
?.map((e) => TableRow.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
pagination: json['pagination'] != null
|
||||
? Pagination.fromJson(json['pagination'] as Map<String, dynamic>)
|
||||
: null,
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
'columns': columns.map((e) => e.toJson()).toList(),
|
||||
'rows': rows.map((e) => e.toJson()).toList(),
|
||||
if (pagination != null) 'pagination': pagination!.toJson(),
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiKvNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'kv';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final List<KeyValuePair> pairs;
|
||||
final KvLayout layout;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiKvNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
required this.pairs,
|
||||
this.layout = KvLayout.vertical,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiKvNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiKvNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
pairs:
|
||||
(json['pairs'] as List<dynamic>?)
|
||||
?.map((e) => KeyValuePair.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
layout: KvLayout.values.firstWhere(
|
||||
(e) => e.value == json['layout'],
|
||||
orElse: () => KvLayout.vertical,
|
||||
),
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
'pairs': pairs.map((e) => e.toJson()).toList(),
|
||||
'layout': layout.value,
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiOperationNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'operation';
|
||||
final String? title;
|
||||
final String? description;
|
||||
final UiIcon? icon;
|
||||
final UiStatus? status;
|
||||
final OperationType operation;
|
||||
final OperationResult result;
|
||||
final String? message;
|
||||
final int? affectedCount;
|
||||
final UiNode? details;
|
||||
final UiAction? rollback;
|
||||
final Map<String, dynamic>? extensions;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiOperationNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.description,
|
||||
this.icon,
|
||||
this.status,
|
||||
required this.operation,
|
||||
required this.result,
|
||||
this.message,
|
||||
this.affectedCount,
|
||||
this.details,
|
||||
this.rollback,
|
||||
this.extensions,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiOperationNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiOperationNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
description: json['description'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
status: json['status'] != null
|
||||
? UiStatus.values.firstWhere(
|
||||
(e) => e.value == json['status'],
|
||||
orElse: () => UiStatus.info,
|
||||
)
|
||||
: null,
|
||||
operation: OperationType.values.firstWhere(
|
||||
(e) => e.value == json['operation'],
|
||||
orElse: () => OperationType.execute,
|
||||
),
|
||||
result: OperationResult.values.firstWhere(
|
||||
(e) => e.value == json['result'],
|
||||
orElse: () => OperationResult.failure,
|
||||
),
|
||||
message: json['message'] as String?,
|
||||
affectedCount: json['affectedCount'] as int?,
|
||||
details: json['details'] != null
|
||||
? UiNode.fromJson(json['details'] as Map<String, dynamic>)
|
||||
: null,
|
||||
rollback: json['rollback'] != null
|
||||
? UiAction.fromJson(json['rollback'] as Map<String, dynamic>)
|
||||
: null,
|
||||
extensions: json['extensions'] as Map<String, dynamic>?,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (description != null) 'description': description,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
if (status != null) 'status': status!.value,
|
||||
'operation': operation.value,
|
||||
'result': result.value,
|
||||
if (message != null) 'message': message,
|
||||
if (affectedCount != null) 'affectedCount': affectedCount,
|
||||
if (details != null) 'details': (details as dynamic).toJson(),
|
||||
if (rollback != null) 'rollback': rollback!.toJson(),
|
||||
if (extensions != null) 'extensions': extensions,
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiErrorNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'error';
|
||||
final String? title;
|
||||
final UiIcon? icon;
|
||||
final String errorCode;
|
||||
final String message;
|
||||
final String? details;
|
||||
final String? stack;
|
||||
final bool retryable;
|
||||
final List<String>? suggestions;
|
||||
final UiAction? retry;
|
||||
final UiAction? support;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiErrorNode({
|
||||
this.id,
|
||||
this.title,
|
||||
this.icon,
|
||||
required this.errorCode,
|
||||
required this.message,
|
||||
this.details,
|
||||
this.stack,
|
||||
this.retryable = false,
|
||||
this.suggestions,
|
||||
this.retry,
|
||||
this.support,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiErrorNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiErrorNode(
|
||||
id: json['id'] as String?,
|
||||
title: json['title'] as String?,
|
||||
icon: json['icon'] != null
|
||||
? UiIcon.fromJson(json['icon'] as Map<String, dynamic>)
|
||||
: null,
|
||||
errorCode: json['errorCode'] as String? ?? 'UNKNOWN',
|
||||
message: json['message'] as String? ?? 'An error occurred',
|
||||
details: json['details'] as String?,
|
||||
stack: json['stack'] as String?,
|
||||
retryable: json['retryable'] as bool? ?? false,
|
||||
suggestions: (json['suggestions'] as List<dynamic>?)
|
||||
?.map((e) => e as String)
|
||||
.toList(),
|
||||
retry: json['retry'] != null
|
||||
? UiAction.fromJson(json['retry'] as Map<String, dynamic>)
|
||||
: null,
|
||||
support: json['support'] != null
|
||||
? UiAction.fromJson(json['support'] as Map<String, dynamic>)
|
||||
: null,
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
if (title != null) 'title': title,
|
||||
if (icon != null) 'icon': icon!.toJson(),
|
||||
'errorCode': errorCode,
|
||||
'message': message,
|
||||
if (details != null) 'details': details,
|
||||
if (stack != null) 'stack': stack,
|
||||
'retryable': retryable,
|
||||
if (suggestions != null) 'suggestions': suggestions,
|
||||
if (retry != null) 'retry': retry!.toJson(),
|
||||
if (support != null) 'support': support!.toJson(),
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
class UiContainerNode implements UiNode {
|
||||
@override
|
||||
final String? id;
|
||||
@override
|
||||
String get type => 'container';
|
||||
final ContainerDirection direction;
|
||||
final int? gap;
|
||||
final List<UiNode> children;
|
||||
final List<UiAction>? actions;
|
||||
|
||||
const UiContainerNode({
|
||||
this.id,
|
||||
this.direction = ContainerDirection.vertical,
|
||||
this.gap,
|
||||
required this.children,
|
||||
this.actions,
|
||||
});
|
||||
|
||||
factory UiContainerNode.fromJson(Map<String, dynamic> json) {
|
||||
return UiContainerNode(
|
||||
id: json['id'] as String?,
|
||||
direction: ContainerDirection.values.firstWhere(
|
||||
(e) => e.value == json['direction'],
|
||||
orElse: () => ContainerDirection.vertical,
|
||||
),
|
||||
gap: json['gap'] as int?,
|
||||
children:
|
||||
(json['children'] as List<dynamic>?)
|
||||
?.map((e) => UiNode.fromJson(e as Map<String, dynamic>))
|
||||
.toList() ??
|
||||
[],
|
||||
actions: (json['actions'] as List<dynamic>?)
|
||||
?.map((e) => UiAction.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'type': type,
|
||||
'direction': direction.value,
|
||||
if (gap != null) 'gap': gap,
|
||||
'children': children.map((e) => (e as dynamic).toJson()).toList(),
|
||||
if (actions != null) 'actions': actions!.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// UI Schema Protocol Implementation.
|
||||
///
|
||||
/// This file is the single source of truth for UI Schema.
|
||||
/// All implementations must follow docs/protocols/ui-schema.md.
|
||||
///
|
||||
/// Version: 1.0
|
||||
library;
|
||||
|
||||
part 'enums.dart';
|
||||
part 'common_types.dart';
|
||||
part 'actions.dart';
|
||||
part 'nodes.dart';
|
||||
part 'document.dart';
|
||||
part 'builders.dart';
|
||||
@@ -0,0 +1,35 @@
|
||||
bool isValidInternalNavigationPath(String path) {
|
||||
if (path.isEmpty || !path.startsWith('/')) {
|
||||
return false;
|
||||
}
|
||||
return !path.startsWith('//') &&
|
||||
!path.contains('://') &&
|
||||
!path.contains('?') &&
|
||||
!path.contains('#') &&
|
||||
!path.contains(':');
|
||||
}
|
||||
|
||||
String buildUiSchemaNavigationTarget({
|
||||
required String path,
|
||||
Map<String, dynamic>? params,
|
||||
}) {
|
||||
final baseUri = Uri.parse(path);
|
||||
final queryParams = <String, String>{};
|
||||
|
||||
if (params != null) {
|
||||
for (final entry in params.entries) {
|
||||
final value = entry.value;
|
||||
if (value is String && value.isNotEmpty) {
|
||||
queryParams[entry.key] = value;
|
||||
} else if (value is num || value is bool) {
|
||||
queryParams[entry.key] = value.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final mergedQueryParams = {...baseUri.queryParameters, ...queryParams};
|
||||
final targetUri = baseUri.replace(
|
||||
queryParameters: mergedQueryParams.isEmpty ? null : mergedQueryParams,
|
||||
);
|
||||
return targetUri.toString();
|
||||
}
|
||||
Reference in New Issue
Block a user