:drunk: Werid miniapp runtime

This commit is contained in:
2026-01-18 13:31:45 +08:00
parent fa0051b606
commit 639417e952
33 changed files with 6437 additions and 3 deletions

View File

@@ -85,7 +85,7 @@ final class AppSettingsNotifierProvider
}
String _$appSettingsNotifierHash() =>
r'0a7f75bd95850b0c564b29c57912ec8fcac53f09';
r'fc474771ced89ec8637c0f773a9c6bc392f0df60';
abstract class _$AppSettingsNotifier extends $Notifier<AppSettings> {
AppSettings build();

View File

@@ -0,0 +1,440 @@
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:island/modular/interface.dart';
import 'package:island/modular/registry.dart';
import 'package:island/pods/config.dart';
import 'package:island/talker.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'plugin_registry.freezed.dart';
part 'plugin_registry.g.dart';
const kMiniAppsRegistryKey = 'mini_apps_registry';
const kMiniAppsLastSyncKey = 'mini_apps_last_sync';
const kRawPluginsRegistryKey = 'raw_plugins_registry';
@freezed
sealed class MiniAppSyncResult with _$MiniAppSyncResult {
const factory MiniAppSyncResult({
required bool success,
List<String>? added,
List<String>? updated,
List<String>? removed,
String? error,
}) = _MiniAppSyncResult;
}
@Riverpod(keepAlive: true)
class PluginRegistryNotifier extends _$PluginRegistryNotifier {
late final PluginRegistry _registry;
late final Dio _dio;
@override
PluginRegistry build() {
_registry = PluginRegistry();
_dio = Dio();
ref.onDispose(() {
_registry.dispose();
});
_loadFromPrefs();
return _registry;
}
Future<void> _loadFromPrefs() async {
try {
final prefs = ref.read(sharedPreferencesProvider);
final registryJson = prefs.getString(kMiniAppsRegistryKey);
if (registryJson != null) {
final List<dynamic> decoded = jsonDecode(registryJson);
for (final item in decoded) {
final metadata = MiniAppMetadata.fromJson(
item as Map<String, dynamic>,
);
if (metadata.isEnabled && metadata.localCachePath != null) {
await _registry.loadMiniApp(metadata);
}
}
}
talker.info('[PluginRegistry] Loaded registry from preferences');
} catch (e, stackTrace) {
talker.error(
'[PluginRegistry] Failed to load from preferences',
e,
stackTrace,
);
}
}
Future<void> _saveToPrefs() async {
try {
final prefs = ref.read(sharedPreferencesProvider);
final miniAppsData = _registry.miniApps.values
.map((app) => (app as EvaluatedMiniApp).appMetadata.toJson())
.toList();
await prefs.setString(kMiniAppsRegistryKey, jsonEncode(miniAppsData));
talker.info('[PluginRegistry] Saved registry to preferences');
} catch (e, stackTrace) {
talker.error(
'[PluginRegistry] Failed to save to preferences',
e,
stackTrace,
);
}
}
void registerRawPlugin(RawPlugin plugin) {
_registry.registerRawPlugin(plugin);
}
void unregisterRawPlugin(String id) {
_registry.unregisterRawPlugin(id);
}
Future<MiniAppSyncResult> syncMiniAppsFromServer(String apiEndpoint) async {
try {
talker.info(
'[PluginRegistry] Syncing mini-apps from server: $apiEndpoint',
);
final response = await _dio.get(apiEndpoint);
if (response.statusCode != 200) {
throw Exception('Failed to fetch mini-apps: ${response.statusCode}');
}
final List<dynamic> data = response.data['mini_apps'] ?? [];
final serverApps = data
.map(
(item) => MiniAppServerInfo.fromJson(item as Map<String, dynamic>),
)
.toList();
final currentApps = _registry.miniApps;
final added = <String>[];
final updated = <String>[];
for (final serverApp in serverApps) {
final existingApp = currentApps[serverApp.id];
if (existingApp == null) {
added.add(serverApp.id);
talker.info('[PluginRegistry] Found new mini-app: ${serverApp.name}');
} else {
final currentMetadata = (existingApp as EvaluatedMiniApp).appMetadata;
if (currentMetadata.version != serverApp.version) {
updated.add(serverApp.id);
talker.info(
'[PluginRegistry] Found update for mini-app: ${serverApp.name}',
);
}
}
}
final prefs = ref.read(sharedPreferencesProvider);
await prefs.setString(
kMiniAppsLastSyncKey,
DateTime.now().toIso8601String(),
);
final syncResult = MiniAppSyncResult(
success: true,
added: added,
updated: updated,
);
await _saveToPrefs();
return syncResult;
} catch (e, stackTrace) {
talker.error('[PluginRegistry] Failed to sync mini-apps', e, stackTrace);
return MiniAppSyncResult(success: false, error: e.toString());
}
}
Future<bool> downloadMiniApp(
String id,
String downloadUrl, {
ProgressCallback? onProgress,
}) async {
try {
talker.info(
'[PluginRegistry] Downloading mini-app: $id from $downloadUrl',
);
final cacheDirPath = await _registry.getMiniAppCacheDirectory();
final cachePath = '$cacheDirPath/${_registry.getMiniAppCachePath(id)}';
await _dio.download(
downloadUrl,
cachePath,
onReceiveProgress: (received, total) {
if (total != -1 && onProgress != null) {
final progress = received / total;
onProgress(
progress,
'Downloading... ${((progress * 100).toStringAsFixed(0))}%',
);
}
},
);
talker.info('[PluginRegistry] Downloaded mini-app: $id to $cachePath');
final metadata = MiniAppMetadata(
id: id,
name: id,
version: '1.0.0',
description: 'Downloaded mini-app',
downloadUrl: downloadUrl,
localCachePath: cachePath,
lastUpdated: DateTime.now(),
isEnabled: true,
);
final result = await _registry.loadMiniApp(
metadata,
onProgress: onProgress,
);
if (result == PluginLoadResult.success) {
await _saveToPrefs();
return true;
}
return false;
} catch (e, stackTrace) {
talker.error(
'[PluginRegistry] Failed to download mini-app: $id',
e,
stackTrace,
);
return false;
}
}
Future<bool> updateMiniApp(String id, {ProgressCallback? onProgress}) async {
try {
final miniApp = _registry.getMiniApp(id);
if (miniApp == null) {
talker.warning('[PluginRegistry] Mini-app not found for update: $id');
return false;
}
final appMetadata = (miniApp as EvaluatedMiniApp).appMetadata;
_registry.unloadMiniApp(id);
if (onProgress != null) {
onProgress(0.0, 'Downloading update...');
}
final success = await downloadMiniApp(
id,
appMetadata.downloadUrl,
onProgress: onProgress,
);
if (success) {
talker.info('[PluginRegistry] Successfully updated mini-app: $id');
return true;
}
return false;
} catch (e, stackTrace) {
talker.error(
'[PluginRegistry] Failed to update mini-app: $id',
e,
stackTrace,
);
return false;
}
}
Future<void> enableMiniApp(String id, bool enabled) async {
final miniApp = _registry.getMiniApp(id);
if (miniApp != null) {
final appMetadata = (miniApp as EvaluatedMiniApp).appMetadata;
if (enabled && appMetadata.isEnabled == false) {
await _registry.loadMiniApp(appMetadata.copyWith(isEnabled: true));
} else if (!enabled && appMetadata.isEnabled == true) {
_registry.unloadMiniApp(id);
final updatedMetadata = appMetadata.copyWith(isEnabled: false);
final evaluatedMiniApp = miniApp as EvaluatedMiniApp;
final updatedMiniApp = EvaluatedMiniApp(
appMetadata: updatedMetadata,
entryFunction: evaluatedMiniApp.entryFunction,
runtime: evaluatedMiniApp.runtime,
);
_registry.miniApps[id] = updatedMiniApp;
}
await _saveToPrefs();
}
}
Future<void> deleteMiniApp(String id, {bool deleteCache = true}) async {
try {
_registry.unloadMiniApp(id);
if (deleteCache) {
final cacheDirPath = await _registry.getMiniAppCacheDirectory();
final cachePath = '$cacheDirPath/${_registry.getMiniAppCachePath(id)}';
final file = File(cachePath);
if (await file.exists()) {
await file.delete();
talker.info('[PluginRegistry] Deleted cache for mini-app: $id');
}
}
await _saveToPrefs();
} catch (e, stackTrace) {
talker.error(
'[PluginRegistry] Failed to delete mini-app: $id',
e,
stackTrace,
);
}
}
Future<void> clearMiniAppCache() async {
await _registry.clearMiniAppCache();
}
List<MiniApp> getAvailableMiniApps() {
return _registry.miniApps.values.toList();
}
Map<String, RawPlugin> getAvailableRawPlugins() {
return _registry.rawPlugins;
}
Future<MiniApp?> getMiniApp(String id) async {
return _registry.getMiniApp(id);
}
Future<DateTime?> getLastSyncTime() async {
final prefs = ref.read(sharedPreferencesProvider);
final lastSyncStr = prefs.getString(kMiniAppsLastSyncKey);
if (lastSyncStr != null) {
return DateTime.tryParse(lastSyncStr);
}
return null;
}
Future<String> getMiniAppCacheDirectory() async {
return _registry.getMiniAppCacheDirectory();
}
Future<bool> loadMiniappFromCache(
MiniAppMetadata metadata, {
ProgressCallback? onProgress,
}) async {
try {
final result = await _registry.loadMiniApp(
metadata,
onProgress: onProgress,
);
if (result == PluginLoadResult.success) {
await _saveToPrefs();
return true;
}
return false;
} catch (e, stackTrace) {
talker.error(
'[PluginRegistry] Failed to load miniapp from cache',
e,
stackTrace,
);
return false;
}
}
Future<bool> loadMiniappFromUrl(
String url, {
ProgressCallback? onProgress,
}) async {
try {
final appId = generateAppIdFromUrl(url);
final cacheDirPath = await _registry.getMiniAppCacheDirectory();
final cachePath = '$cacheDirPath/${_registry.getMiniAppCachePath(appId)}';
await _dio.download(
url,
cachePath,
onReceiveProgress: (received, total) {
if (total != -1 && onProgress != null) {
final progress = received / total;
onProgress(
progress,
'Downloading... ${((progress * 100).toStringAsFixed(0))}%',
);
}
},
);
talker.info('[PluginRegistry] Downloaded mini-app: $appId to $cachePath');
final metadata = MiniAppMetadata(
id: appId,
name: appId,
version: '1.0.0',
description: 'Loaded from URL',
downloadUrl: url,
localCachePath: cachePath,
lastUpdated: DateTime.now(),
isEnabled: true,
);
final result = await _registry.loadMiniApp(
metadata,
onProgress: onProgress,
);
if (result == PluginLoadResult.success) {
await _saveToPrefs();
return true;
}
return false;
} catch (e, stackTrace) {
talker.error(
'[PluginRegistry] Failed to load miniapp from URL',
e,
stackTrace,
);
return false;
}
}
String generateAppIdFromUrl(String url) {
final uri = Uri.tryParse(url);
if (uri == null) {
return 'dev_miniapp_${DateTime.now().millisecondsSinceEpoch}';
}
final path = uri.pathSegments.lastWhere(
(s) => s.isNotEmpty,
orElse: () => 'miniapp',
);
final baseName = path
.replaceAll('.evc', '')
.replaceAll(RegExp(r'[^\w-]'), '_');
return 'dev_$baseName';
}
}
final miniAppsProvider = Provider.autoDispose((ref) {
final registry = ref.watch(pluginRegistryProvider);
return registry.miniApps.values.toList();
});
final rawPluginsProvider = Provider.autoDispose((ref) {
final registry = ref.watch(pluginRegistryProvider);
return registry.rawPlugins;
});
typedef ProgressCallback = void Function(double progress, String message);

View File

@@ -0,0 +1,301 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'plugin_registry.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$MiniAppSyncResult {
bool get success; List<String>? get added; List<String>? get updated; List<String>? get removed; String? get error;
/// Create a copy of MiniAppSyncResult
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$MiniAppSyncResultCopyWith<MiniAppSyncResult> get copyWith => _$MiniAppSyncResultCopyWithImpl<MiniAppSyncResult>(this as MiniAppSyncResult, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is MiniAppSyncResult&&(identical(other.success, success) || other.success == success)&&const DeepCollectionEquality().equals(other.added, added)&&const DeepCollectionEquality().equals(other.updated, updated)&&const DeepCollectionEquality().equals(other.removed, removed)&&(identical(other.error, error) || other.error == error));
}
@override
int get hashCode => Object.hash(runtimeType,success,const DeepCollectionEquality().hash(added),const DeepCollectionEquality().hash(updated),const DeepCollectionEquality().hash(removed),error);
@override
String toString() {
return 'MiniAppSyncResult(success: $success, added: $added, updated: $updated, removed: $removed, error: $error)';
}
}
/// @nodoc
abstract mixin class $MiniAppSyncResultCopyWith<$Res> {
factory $MiniAppSyncResultCopyWith(MiniAppSyncResult value, $Res Function(MiniAppSyncResult) _then) = _$MiniAppSyncResultCopyWithImpl;
@useResult
$Res call({
bool success, List<String>? added, List<String>? updated, List<String>? removed, String? error
});
}
/// @nodoc
class _$MiniAppSyncResultCopyWithImpl<$Res>
implements $MiniAppSyncResultCopyWith<$Res> {
_$MiniAppSyncResultCopyWithImpl(this._self, this._then);
final MiniAppSyncResult _self;
final $Res Function(MiniAppSyncResult) _then;
/// Create a copy of MiniAppSyncResult
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? success = null,Object? added = freezed,Object? updated = freezed,Object? removed = freezed,Object? error = freezed,}) {
return _then(_self.copyWith(
success: null == success ? _self.success : success // ignore: cast_nullable_to_non_nullable
as bool,added: freezed == added ? _self.added : added // ignore: cast_nullable_to_non_nullable
as List<String>?,updated: freezed == updated ? _self.updated : updated // ignore: cast_nullable_to_non_nullable
as List<String>?,removed: freezed == removed ? _self.removed : removed // ignore: cast_nullable_to_non_nullable
as List<String>?,error: freezed == error ? _self.error : error // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// Adds pattern-matching-related methods to [MiniAppSyncResult].
extension MiniAppSyncResultPatterns on MiniAppSyncResult {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _MiniAppSyncResult value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _MiniAppSyncResult() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _MiniAppSyncResult value) $default,){
final _that = this;
switch (_that) {
case _MiniAppSyncResult():
return $default(_that);}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _MiniAppSyncResult value)? $default,){
final _that = this;
switch (_that) {
case _MiniAppSyncResult() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( bool success, List<String>? added, List<String>? updated, List<String>? removed, String? error)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _MiniAppSyncResult() when $default != null:
return $default(_that.success,_that.added,_that.updated,_that.removed,_that.error);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( bool success, List<String>? added, List<String>? updated, List<String>? removed, String? error) $default,) {final _that = this;
switch (_that) {
case _MiniAppSyncResult():
return $default(_that.success,_that.added,_that.updated,_that.removed,_that.error);}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( bool success, List<String>? added, List<String>? updated, List<String>? removed, String? error)? $default,) {final _that = this;
switch (_that) {
case _MiniAppSyncResult() when $default != null:
return $default(_that.success,_that.added,_that.updated,_that.removed,_that.error);case _:
return null;
}
}
}
/// @nodoc
class _MiniAppSyncResult implements MiniAppSyncResult {
const _MiniAppSyncResult({required this.success, final List<String>? added, final List<String>? updated, final List<String>? removed, this.error}): _added = added,_updated = updated,_removed = removed;
@override final bool success;
final List<String>? _added;
@override List<String>? get added {
final value = _added;
if (value == null) return null;
if (_added is EqualUnmodifiableListView) return _added;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(value);
}
final List<String>? _updated;
@override List<String>? get updated {
final value = _updated;
if (value == null) return null;
if (_updated is EqualUnmodifiableListView) return _updated;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(value);
}
final List<String>? _removed;
@override List<String>? get removed {
final value = _removed;
if (value == null) return null;
if (_removed is EqualUnmodifiableListView) return _removed;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(value);
}
@override final String? error;
/// Create a copy of MiniAppSyncResult
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$MiniAppSyncResultCopyWith<_MiniAppSyncResult> get copyWith => __$MiniAppSyncResultCopyWithImpl<_MiniAppSyncResult>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _MiniAppSyncResult&&(identical(other.success, success) || other.success == success)&&const DeepCollectionEquality().equals(other._added, _added)&&const DeepCollectionEquality().equals(other._updated, _updated)&&const DeepCollectionEquality().equals(other._removed, _removed)&&(identical(other.error, error) || other.error == error));
}
@override
int get hashCode => Object.hash(runtimeType,success,const DeepCollectionEquality().hash(_added),const DeepCollectionEquality().hash(_updated),const DeepCollectionEquality().hash(_removed),error);
@override
String toString() {
return 'MiniAppSyncResult(success: $success, added: $added, updated: $updated, removed: $removed, error: $error)';
}
}
/// @nodoc
abstract mixin class _$MiniAppSyncResultCopyWith<$Res> implements $MiniAppSyncResultCopyWith<$Res> {
factory _$MiniAppSyncResultCopyWith(_MiniAppSyncResult value, $Res Function(_MiniAppSyncResult) _then) = __$MiniAppSyncResultCopyWithImpl;
@override @useResult
$Res call({
bool success, List<String>? added, List<String>? updated, List<String>? removed, String? error
});
}
/// @nodoc
class __$MiniAppSyncResultCopyWithImpl<$Res>
implements _$MiniAppSyncResultCopyWith<$Res> {
__$MiniAppSyncResultCopyWithImpl(this._self, this._then);
final _MiniAppSyncResult _self;
final $Res Function(_MiniAppSyncResult) _then;
/// Create a copy of MiniAppSyncResult
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? success = null,Object? added = freezed,Object? updated = freezed,Object? removed = freezed,Object? error = freezed,}) {
return _then(_MiniAppSyncResult(
success: null == success ? _self.success : success // ignore: cast_nullable_to_non_nullable
as bool,added: freezed == added ? _self._added : added // ignore: cast_nullable_to_non_nullable
as List<String>?,updated: freezed == updated ? _self._updated : updated // ignore: cast_nullable_to_non_nullable
as List<String>?,removed: freezed == removed ? _self._removed : removed // ignore: cast_nullable_to_non_nullable
as List<String>?,error: freezed == error ? _self.error : error // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
// dart format on

View File

@@ -0,0 +1,63 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'plugin_registry.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(PluginRegistryNotifier)
final pluginRegistryProvider = PluginRegistryNotifierProvider._();
final class PluginRegistryNotifierProvider
extends $NotifierProvider<PluginRegistryNotifier, PluginRegistry> {
PluginRegistryNotifierProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'pluginRegistryProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$pluginRegistryNotifierHash();
@$internal
@override
PluginRegistryNotifier create() => PluginRegistryNotifier();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(PluginRegistry value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<PluginRegistry>(value),
);
}
}
String _$pluginRegistryNotifierHash() =>
r'287b3a9e5598b279b80293dd37fe5a825395c8e3';
abstract class _$PluginRegistryNotifier extends $Notifier<PluginRegistry> {
PluginRegistry build();
@$mustCallSuper
@override
void runBuild() {
final ref = this.ref as $Ref<PluginRegistry, PluginRegistry>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<PluginRegistry, PluginRegistry>,
PluginRegistry,
Object?,
Object?
>;
element.handleCreate(ref, build);
}
}