V- Modal AI: Visual Video / Image Search - Flutter Video SDK
Dart android-sdkflutterflutter-appflutter-packageflutter-sdkflutter-videoflutter-video-editingflutter-video-playerflutter-video-sdkflutter-videosflutter-videosdkmobile-videomobile-video-editor-sdkmobile-video-sdkvideo-editingvideo-sdkvideo-searchvideo-search-enginevideo-streaming
import 'dart:convert';
import 'api_key_provider.dart';
import 'errors.dart';
/// @nodoc
const String publicGatewayUrlHash =
'aHR0cHM6Ly9zZWFyY2hhcGktdGVzdC52LW1vZGFsLmNvbQ==';
/// @nodoc
final String publicGatewayUrl = utf8.decode(base64Decode(publicGatewayUrlHash));
/// @nodoc
const String devGatewayUrlHash = 'aHR0cDovLzEyNy4wLjAuMTozMDk5';
/// @nodoc
final String devGatewayUrl = utf8.decode(base64Decode(devGatewayUrlHash));
const String _gatewayProxyPathHash = 'L2FwaS92MS9wcm94eS9zZWFyY2hfYXBp';
final String _gatewayProxyPath = utf8.decode(
base64Decode(_gatewayProxyPathHash),
);
/// Immutable client configuration and credential-provider binding.
///
/// The constructor validates timeout, retry, mode, and base-address values.
/// Supply either [token] or an [apiKeyProvider]; a provider is preferred when
/// credentials can rotate during a mobile session.
class SdkConfig {
/// Creates and validates configuration with mobile-safe defaults.
SdkConfig({
String? baseUrl,
this.userId = '',
this.tenantId = '',
this.email = '',
this.token = '',
this.timeout = const Duration(seconds: 30),
Duration? idleTimeout,
this.mode = 'gateway',
this.maxRetries = 1,
this.apiKeyProvider,
}) : baseUrl = baseUrl ?? publicGatewayUrl,
idleTimeout = idleTimeout ?? timeout {
if (timeout <= Duration.zero) {
throw const ValidationException('timeout must be positive');
}
if (maxRetries < 0) {
throw const ValidationException('max_retries must not be negative');
}
if (this.idleTimeout <= Duration.zero) {
throw const ValidationException('idle_timeout must be positive');
}
if (!const <String>{'gateway', 'direct'}.contains(normalizedMode)) {
throw const ValidationException('mode must be gateway or direct');
}
_validateBase(normalizedBaseUrl);
}
/// Configured service origin. It is normalized internally before use.
final String baseUrl;
/// Optional known user identifier.
final String userId;
/// Optional tenant identifier supplied with direct integrations.
final String tenantId;
/// Optional user email supplied with direct integrations.
final String email;
/// Static API key used when [apiKeyProvider] is absent.
final String token;
/// Maximum duration for establishing an SDK request or upload phase.
final Duration timeout;
/// Maximum silence allowed while consuming a response body.
///
/// Defaults to [timeout] when omitted.
final Duration idleTimeout;
/// Connection mode, either `gateway` or `direct`.
final String mode;
/// Number of retries allowed for retryable SDK operations.
final int maxRetries;
/// Optional rotating credential source.
final ApiKeyProvider? apiKeyProvider;
String get normalizedMode {
final value = mode.trim().toLowerCase();
return value.isEmpty ? 'gateway' : value;
}
String get normalizedBaseUrl => strGatewayBaseUrl(baseUrl, normalizedMode);
String get normalizedUserId => userId.trim();
String get normalizedTenantId => tenantId.trim();
String get normalizedEmail => email.trim();
int get normalizedMaxRetries => maxRetries;
/// Returns the current validated API key without storing provider output.
String currentApiKey() {
final value = apiKeyProvider?.current() ?? token;
return value.trim().isEmpty ? '' : strApiKey(value);
}
/// Returns a new validated configuration with selected values replaced.
SdkConfig copyWith({
String? baseUrl,
String? userId,
String? tenantId,
String? email,
String? token,
Duration? timeout,
Duration? idleTimeout,
String? mode,
int? maxRetries,
ApiKeyProvider? apiKeyProvider,
}) => SdkConfig(
baseUrl: baseUrl ?? this.baseUrl,
userId: userId ?? this.userId,
tenantId: tenantId ?? this.tenantId,
email: email ?? this.email,
token: token ?? this.token,
timeout: timeout ?? this.timeout,
idleTimeout: idleTimeout ?? this.idleTimeout,
mode: mode ?? this.mode,
maxRetries: maxRetries ?? this.maxRetries,
apiKeyProvider: apiKeyProvider ?? this.apiKeyProvider,
);
/// Builds configuration from the supported environment keys and overrides.
///
/// A missing credential throws [ValidationException] unless
/// [apiKeyProvider] is supplied.
factory SdkConfig.fromEnvironment(
Map<String, String> env, {
String? baseUrl,
String? userId,
String? tenantId,
String? email,
String? token,
Duration? timeout,
Duration? idleTimeout,
String? mode,
int? maxRetries,
ApiKeyProvider? apiKeyProvider,
}) {
final envName = (env['VMODAL_ENV'] ?? 'prd').trim().toLowerCase();
if (!const <String>{'dev', 'prd'}.contains(envName)) {
throw const ValidationException('VMODAL_ENV must be dev or prd');
}
final fallback = envName == 'dev' ? devGatewayUrl : publicGatewayUrl;
final rawBase =
baseUrl ??
_first(<String?>[
env['VMODAL_BASE_URL'],
env['TEST_CLIENT_SERVER_API_URL'],
fallback,
]);
final rawToken =
token ??
_first(<String?>[
env['VMODAL_API_KEY'],
env['VMODAL_API_TOKEN'],
env['TEST_CLIENT_CLERK_USER_API_TOKEN'],
env['TEST_CLIENT_USER_TOKEN'],
]);
if (rawToken.isEmpty && apiKeyProvider == null) {
throw const ValidationException('VMODAL_API_KEY is required');
}
final seconds = double.tryParse(env['VMODAL_TIMEOUT'] ?? '');
return SdkConfig(
baseUrl: rawBase,
userId: userId ?? env['VMODAL_USER_ID'] ?? '',
tenantId: tenantId ?? env['VMODAL_TENANT_ID'] ?? '',
email: email ?? env['VMODAL_USER_EMAIL'] ?? '',
token: rawToken,
timeout:
timeout ??
(seconds == null
? const Duration(seconds: 30)
: Duration(milliseconds: (seconds * 1000).round())),
idleTimeout: idleTimeout,
mode: mode ?? 'gateway',
maxRetries:
maxRetries ?? int.tryParse(env['VMODAL_MAX_RETRIES'] ?? '') ?? 1,
apiKeyProvider: apiKeyProvider,
);
}
@override
String toString() =>
'SdkConfig('
'baseUrlConfigured=${baseUrl.isNotEmpty}, '
'userIdConfigured=${userId.isNotEmpty}, '
'tenantIdConfigured=${tenantId.isNotEmpty}, '
'emailConfigured=${email.isNotEmpty}, '
'tokenConfigured=${token.isNotEmpty}, '
'timeoutMs=${timeout.inMilliseconds}, '
'idleTimeoutMs=${idleTimeout.inMilliseconds}, '
'mode=$normalizedMode, '
'maxRetries=$maxRetries, '
'apiKeyProviderConfigured=${apiKeyProvider != null})';
}
/// @nodoc
String strGatewayBaseUrl(String baseUrl, [String mode = '']) {
final base = baseUrl.trim().replaceFirst(RegExp(r'/+$'), '');
if (base.isEmpty || mode.trim().toLowerCase() != 'gateway') return base;
final suffix = _gatewayProxyPath;
return base.endsWith(suffix) ? base : '$base$suffix';
}
/// @nodoc
String strUsersBaseUrl(String baseUrl) {
final base = baseUrl.trim().replaceFirst(RegExp(r'/+$'), '');
final suffix = _gatewayProxyPath;
return base.endsWith(suffix)
? base.substring(0, base.length - suffix.length)
: base;
}
String _first(List<String?> values) {
for (final value in values) {
if (value != null && value.trim().isNotEmpty) return value;
}
return '';
}
void _validateBase(String value) {
final uri = Uri.tryParse(value);
if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
throw const ValidationException('invalid HTTP URL');
}
if (uri.scheme != 'http' && uri.scheme != 'https') {
throw const ValidationException('HTTP or HTTPS URL is required');
}
if (uri.userInfo.isNotEmpty) {
throw const ValidationException('URL user information is not allowed');
}
if (uri.scheme == 'http' && !_loopback(uri.host)) {
throw const ValidationException('HTTPS is required for non-local URLs');
}
}
bool _loopback(String host) => const <String>{
'localhost',
'127.0.0.1',
'::1',
'0:0:0:0:0:0:0:1',
}.contains(host.toLowerCase());