After configuring captcha

This commit is contained in:
Your Name 2026-11-15 19:48:21 +02:00
parent 69c8d29b53
commit 7459263fb4
17 changed files with 10479 additions and 65 deletions

View File

@ -4,7 +4,8 @@ export const loginBodySchema = z.object({
email: z.string().trim().min(1, 'Email is required').max(255).email(),
password: z.string().min(1, 'Password is required').max(256),
totpCode: z.string().trim().max(32).optional(),
captchaToken: z.string().trim().max(2048).optional(),
// Turnstile tokens are often ~1k chars; keep headroom for future formats.
captchaToken: z.string().trim().max(4096).optional(),
});
export const registerBodySchema = z.object({

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -57,6 +57,22 @@ class AppException implements Exception {
'Le service est temporairement indisponible. Veuillez réessayer plus tard.',
);
/// Prediction / candle market bootstrap (state + chart).
static String get marketDataLoadFailedMessage => _t(
'Failed to load market data. Please try again.',
'Impossible de charger les données de marché. Veuillez réessayer.',
);
static String get marketChartLoadFailedMessage => _t(
'Failed to load market chart. Please try again.',
'Impossible de charger le graphique de marché. Veuillez réessayer.',
);
static String get predictionHistoryLoadFailedMessage => _t(
'Failed to load prediction history. Please try again.',
'Impossible de charger l’historique des prédictions. Veuillez réessayer.',
);
static final RegExp _technicalLeak = RegExp(
r'https?://|API_BASE|VITE_|localhost|\b\d{1,3}(?:\.\d{1,3}){3}\b|10\.0\.2\.2|cleartext|INITIAL_SETUP|Bearer\s',
caseSensitive: false,

View File

@ -98,7 +98,10 @@ class PredictionRepositoryImpl implements PredictionRepository {
}
return data;
} on DioException catch (e) {
throw AppException.fromDio(e, fallback: 'Failed to load game state');
throw AppException.fromDio(
e,
fallback: AppException.marketDataLoadFailedMessage,
);
}
}
@ -119,7 +122,10 @@ class PredictionRepositoryImpl implements PredictionRepository {
);
return CandlesPageModel.fromJson(res.data ?? const {});
} on DioException catch (e) {
throw AppException.fromDio(e, fallback: 'Failed to load chart');
throw AppException.fromDio(
e,
fallback: AppException.marketChartLoadFailedMessage,
);
}
}
@ -209,7 +215,10 @@ class PredictionRepositoryImpl implements PredictionRepository {
);
return PredictionsPageModel.fromJson(res.data!);
} on DioException catch (e) {
throw AppException.fromDio(e, fallback: 'Failed to load predictions');
throw AppException.fromDio(
e,
fallback: AppException.predictionHistoryLoadFailedMessage,
);
}
}

View File

@ -13,6 +13,7 @@ import '../../../shared/widgets/pred_card.dart';
import '../../../shared/widgets/pred_text_field.dart';
import '../../../shared/widgets/prediqo_logo.dart';
import '../../../shared/widgets/tloto_gradient_app_bar.dart';
import '../../../shared/widgets/turnstile_captcha.dart';
import '../../welcome/utils/welcome_navigation.dart';
import '../bloc/auth_bloc.dart';
@ -38,8 +39,12 @@ class _LoginScreenState extends State<LoginScreen> {
/// Local captcha UI state (survives AuthClearFeedback).
bool _captchaRequired = false;
String? _captchaProvider; // 'math' | 'turnstile'
String? _mathPrompt;
String? _mathChallengeToken;
String? _turnstileSiteKey;
String? _turnstileToken;
int _turnstileRemountKey = 0;
@override
void initState() {
@ -66,23 +71,51 @@ class _LoginScreenState extends State<LoginScreen> {
context.read<AuthBloc>().add(const AuthClearFeedback());
}
void _clearCaptchaUi({required bool remountTurnstile}) {
_mathPrompt = null;
_mathChallengeToken = null;
_mathAnswerController.clear();
_turnstileToken = null;
if (remountTurnstile) {
_turnstileRemountKey++;
}
}
void _applyCaptchaChallenge(Map<String, dynamic>? captcha) {
final provider = captcha?['provider']?.toString();
final prompt = captcha?['prompt']?.toString();
final token = captcha?['challengeToken']?.toString();
final siteKey = captcha?['siteKey']?.toString();
setState(() {
_captchaRequired = true;
_mathAnswerController.clear();
if (provider == 'math' && prompt != null && token != null && token.isNotEmpty) {
_clearCaptchaUi(remountTurnstile: provider == 'turnstile');
if (provider == 'turnstile') {
_captchaProvider = 'turnstile';
_turnstileSiteKey =
(siteKey != null && siteKey.isNotEmpty) ? siteKey : null;
return;
}
if (provider == 'math' &&
prompt != null &&
token != null &&
token.isNotEmpty) {
_captchaProvider = 'math';
_turnstileSiteKey = null;
_mathPrompt = prompt;
_mathChallengeToken = token;
return;
}
// Keep any existing math challenge when the error has no captcha payload.
// Keep any existing challenge when the error has no captcha payload.
});
}
String? _buildCaptchaToken() {
if (!_captchaRequired) return null;
if (_captchaProvider == 'turnstile') {
final token = _turnstileToken?.trim();
if (token == null || token.isEmpty) return null;
return token;
}
final token = _mathChallengeToken;
final answer = _mathAnswerController.text.trim();
if (token == null || token.isEmpty || answer.isEmpty) return null;
@ -92,10 +125,16 @@ class _LoginScreenState extends State<LoginScreen> {
void _submitLogin() {
final bloc = context.read<AuthBloc>();
if (bloc.state.isSubmitting) return;
final s = context.strings;
final email = _emailController.text.trim();
final password = _passwordController.text;
if (email.isEmpty || password.isEmpty) {
showErrorSnackBar(context, context.strings.loginFieldsRequired);
showErrorSnackBar(context, s.loginFieldsRequired);
return;
}
final captchaToken = _buildCaptchaToken();
if (_captchaRequired && (captchaToken == null || captchaToken.isEmpty)) {
showErrorSnackBar(context, s.captchaTurnstileHelper);
return;
}
setState(() => _verifyBanner = null);
@ -103,7 +142,7 @@ class _LoginScreenState extends State<LoginScreen> {
email: email,
password: password,
totpCode: _totpController.text.isEmpty ? null : _totpController.text,
captchaToken: _buildCaptchaToken(),
captchaToken: captchaToken,
));
}
@ -148,9 +187,9 @@ class _LoginScreenState extends State<LoginScreen> {
setState(() {
_verifyBanner = null;
_captchaRequired = false;
_mathPrompt = null;
_mathChallengeToken = null;
_mathAnswerController.clear();
_captchaProvider = null;
_turnstileSiteKey = null;
_clearCaptchaUi(remountTurnstile: false);
});
_consumeFeedback();
context.go('/home');
@ -357,6 +396,43 @@ class _LoginScreenState extends State<LoginScreen> {
loading ? null : (_) => _submitLogin(),
),
if (_captchaRequired &&
_captchaProvider == 'turnstile') ...[
const SizedBox(height: 14),
Text(
s.captchaTurnstileHelper,
style: Theme.of(context)
.textTheme
.bodySmall,
),
const SizedBox(height: 8),
if (_turnstileSiteKey != null)
TurnstileCaptcha(
key: ValueKey(
'login_turnstile_$_turnstileRemountKey',
),
siteKey: _turnstileSiteKey!,
onToken: (token) {
if (!mounted) return;
setState(
() => _turnstileToken = token,
);
},
)
else
Text(
s.captchaTurnstileUnavailable,
style: Theme.of(context)
.textTheme
.bodySmall
?.copyWith(
color: Theme.of(context)
.colorScheme
.error,
),
),
],
if (_captchaRequired &&
_captchaProvider == 'math' &&
_mathPrompt != null) ...[
const SizedBox(height: 14),
PredTextField(

View File

@ -221,7 +221,11 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
children: [
if (bootError) ...[
SectionError(
message: state.errorMessage ?? s.error,
message: _formatPredictionError(
s,
(state.errorMessage ?? s.error)
.replaceFirst('Exception: ', ''),
),
onRetry: () => context
.read<PredictionBloc>()
.add(const PredictionLoadRequested()),
@ -277,7 +281,11 @@ class _PredictionScreenState extends State<PredictionScreen> with WidgetsBinding
const SizedBox(height: 16),
if (state.candlesError != null && state.candles.isEmpty)
SectionError(
message: state.candlesError!,
message: _formatPredictionError(
s,
state.candlesError!
.replaceFirst('Exception: ', ''),
),
retrying: state.isLoadingOlderCandles,
onRetry: () => context
.read<PredictionBloc>()
@ -1015,5 +1023,11 @@ String _formatPredictionError(AppStrings s, String raw) {
if (lower.contains('readonly') || lower.contains('read only replica')) {
return s.predictionDbReadonly;
}
// Legacy English fallbacks from older app builds / repositories.
if (lower.contains('failed to load game state') ||
lower.contains('failed to load candle predict') ||
lower == 'failed to load chart') {
return s.marketDataLoadFailed;
}
return raw;
}

View File

@ -188,6 +188,14 @@ class AppStrings {
'Enter the result to continue after several failed attempts.',
'Saisissez le résultat pour continuer après plusieurs échecs.',
);
String get captchaTurnstileHelper => t(
'Complete the security check below, then try again.',
'Complétez la vérification de sécurité ci-dessous, puis réessayez.',
);
String get captchaTurnstileUnavailable => t(
'Security check could not be loaded. Pull to refresh or reinstall the app.',
'La vérification de sécurité n’a pas pu être chargée. Réessayez ou réinstallez l’application.',
);
String get logout => t('Log out', 'Déconnexion');
String get forgotPassword => t('Forgot password?', 'Mot de passe oublié ?');
String get forgotPasswordHint => t(
@ -491,7 +499,11 @@ class AppStrings {
String get walletMain => t('Main', 'Principal');
String get walletBonus => t('Bonus', 'Bonus');
String get walletTest => t('Test', 'Test');
String get chartNoData => t('No chart data', 'Pas de données de graphique');
String get chartNoData => t('No market data', 'Pas de données de marché');
String get marketDataLoadFailed => t(
'Failed to load market data. Please try again.',
'Impossible de charger les données de marché. Veuillez réessayer.',
);
String get refreshCandles => t('Refresh candles', 'Actualiser les bougies');
String get chartScrollHint => t(
'Swipe horizontally to browse candle history',

View File

@ -0,0 +1,144 @@
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../core/config/app_config.dart';
import '../../core/di/injection.dart';
/// Cloudflare Turnstile widget for native login (WebView + explicit render).
class TurnstileCaptcha extends StatefulWidget {
const TurnstileCaptcha({
super.key,
required this.siteKey,
required this.onToken,
});
final String siteKey;
final ValueChanged<String?> onToken;
@override
State<TurnstileCaptcha> createState() => _TurnstileCaptchaState();
}
class _TurnstileCaptchaState extends State<TurnstileCaptcha> {
late final WebViewController _controller;
var _ready = false;
@override
void initState() {
super.initState();
_controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(Colors.transparent)
..addJavaScriptChannel(
'TurnstileBridge',
onMessageReceived: (message) {
final raw = message.message.trim();
if (raw.isEmpty || raw == 'expired' || raw == 'error') {
widget.onToken(null);
return;
}
widget.onToken(raw);
},
)
..setNavigationDelegate(
NavigationDelegate(
onPageFinished: (_) {
if (mounted) setState(() => _ready = true);
},
),
);
_load();
}
String get _baseUrl {
final api = Uri.tryParse(sl<AppConfig>().apiBaseUrl);
if (api != null &&
api.hasScheme &&
api.host.isNotEmpty &&
api.host != 'localhost' &&
api.host != '127.0.0.1' &&
!api.host.startsWith('10.0.2.2')) {
return '${api.scheme}://${api.host}/';
}
return '${AppConfig.defaultProductionApiBaseUrl}/';
}
String _html(String siteKey) {
final escaped = siteKey.replaceAll("'", r"\'");
return '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit" async defer></script>
<style>
html, body {
margin: 0;
padding: 0;
background: transparent;
overflow: hidden;
}
#cf-turnstile { display: flex; justify-content: center; }
</style>
</head>
<body>
<div id="cf-turnstile"></div>
<script>
function notify(msg) {
try { TurnstileBridge.postMessage(String(msg)); } catch (e) {}
}
function renderWhenReady() {
if (!window.turnstile) {
setTimeout(renderWhenReady, 50);
return;
}
window.turnstile.render('#cf-turnstile', {
sitekey: '$escaped',
theme: 'auto',
callback: function (token) { notify(token); },
'expired-callback': function () { notify('expired'); },
'error-callback': function () { notify('error'); }
});
}
renderWhenReady();
</script>
</body>
</html>
''';
}
Future<void> _load() async {
widget.onToken(null);
await _controller.loadHtmlString(_html(widget.siteKey), baseUrl: _baseUrl);
}
@override
void didUpdateWidget(covariant TurnstileCaptcha oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.siteKey != widget.siteKey) {
setState(() => _ready = false);
_load();
}
}
@override
Widget build(BuildContext context) {
return SizedBox(
height: 72,
width: double.infinity,
child: Stack(
alignment: Alignment.center,
children: [
WebViewWidget(controller: _controller),
if (!_ready)
const SizedBox(
width: 22,
height: 22,
child: CircularProgressIndicator(strokeWidth: 2),
),
],
),
);
}
}

View File

@ -1097,6 +1097,38 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.0"
webview_flutter:
dependency: "direct main"
description:
name: webview_flutter
sha256: a3da219916aba44947d3a5478b1927876a09781174b5a2b67fa5be0555154bf9
url: "https://pub.dev"
source: hosted
version: "4.13.1"
webview_flutter_android:
dependency: transitive
description:
name: webview_flutter_android
sha256: ad5182eff9a550925330cb9f0cb038eddfdd5712aba8b77aa0f0400e50f6e688
url: "https://pub.dev"
source: hosted
version: "4.12.0"
webview_flutter_platform_interface:
dependency: transitive
description:
name: webview_flutter_platform_interface
sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04"
url: "https://pub.dev"
source: hosted
version: "2.15.1"
webview_flutter_wkwebview:
dependency: transitive
description:
name: webview_flutter_wkwebview
sha256: e50cd97ad28e888f6a4f862a05eab917a635417f9b134df64c3abb78250c6446
url: "https://pub.dev"
source: hosted
version: "3.25.0"
win32:
dependency: transitive
description:

View File

@ -35,6 +35,7 @@ dependencies:
crypto: ^3.0.8
open_filex: ^5.0.0
native_dio_adapter: ^1.8.0
webview_flutter: ^4.13.1
dev_dependencies:
flutter_test:

View File

@ -80,6 +80,8 @@ export function LoginPage() {
const [captchaRequired, setCaptchaRequired] = useState(false);
const [mathChallenge, setMathChallenge] = useState<CaptchaChallenge | null>(null);
const [mathAnswer, setMathAnswer] = useState('');
const [turnstileSiteKey, setTurnstileSiteKey] = useState<string | null>(null);
const [turnstileMountKey, setTurnstileMountKey] = useState(0);
const from = loc.state?.from ?? '/home';
const verifyHint = loc.state?.verifyEmail === true;
@ -92,32 +94,55 @@ export function LoginPage() {
},
});
const refreshTurnstile = useCallback((siteKey?: string | null) => {
const key = (siteKey || captchaQ.data?.siteKey || '').trim();
setTurnstileSiteKey(key || null);
setCaptchaToken(null);
setTurnstileMountKey((k) => k + 1);
}, [captchaQ.data?.siteKey]);
const applyCaptchaChallenge = useCallback((challenge?: CaptchaChallenge | null) => {
setCaptchaRequired(true);
setCaptchaToken(null);
setMathAnswer('');
if (challenge?.provider === 'math' && challenge.challengeToken && challenge.prompt) {
setMathChallenge(challenge);
setTurnstileSiteKey(null);
return;
}
if (challenge?.provider === 'turnstile') {
if (challenge?.provider === 'turnstile' || captchaQ.data?.provider === 'turnstile') {
setMathChallenge(null);
refreshTurnstile(challenge?.siteKey ?? captchaQ.data?.siteKey);
return;
}
// Fallback: fetch a fresh math challenge when provider is math.
void api
.get<CaptchaChallenge>('/api/v1/auth/captcha-challenge')
.then((res) => {
if (res.data.provider === 'math') setMathChallenge(res.data);
if (res.data.provider === 'math') {
setMathChallenge(res.data);
setTurnstileSiteKey(null);
return;
}
if (res.data.provider === 'turnstile') {
setMathChallenge(null);
refreshTurnstile(res.data.siteKey);
}
})
.catch(() => {
/* ignore */
});
}, []);
}, [captchaQ.data?.provider, captchaQ.data?.siteKey, refreshTurnstile]);
const onCaptchaToken = useCallback((token: string | null) => {
setCaptchaToken(token);
}, []);
if (token) {
// Clear a prior CAPTCHA_REQUIRED banner once the widget succeeds.
setError((prev) =>
prev === t('auth.captchaRequired') || prev === t('auth.captchaInvalid') ? null : prev
);
}
}, [t]);
const setupQ = useQuery({
queryKey: ['setup-status'],
@ -163,17 +188,29 @@ export function LoginPage() {
setError(t('auth.emailPasswordRequired'));
return;
}
let tokenToSend = captchaToken;
if (
captchaRequired &&
mathChallenge?.provider === 'math' &&
mathChallenge.challengeToken &&
mathAnswer.trim()
) {
tokenToSend = `math:${mathChallenge.challengeToken}:${mathAnswer.trim()}`;
}
if (captchaRequired && !tokenToSend?.trim()) {
setError(t('auth.captchaRequired'));
if (turnstileSiteKey || captchaQ.data?.provider === 'turnstile') {
refreshTurnstile(turnstileSiteKey || captchaQ.data?.siteKey);
} else {
applyCaptchaChallenge(mathChallenge);
}
return;
}
setLoading(true);
try {
let tokenToSend = captchaToken;
if (
captchaRequired &&
mathChallenge?.provider === 'math' &&
mathChallenge.challengeToken &&
mathAnswer.trim()
) {
tokenToSend = `math:${mathChallenge.challengeToken}:${mathAnswer.trim()}`;
}
const res = await api.post<LoginResponse>('/api/v1/auth/login', {
email: email.trim(),
password,
@ -208,10 +245,8 @@ export function LoginPage() {
: apiErrorMessage(e, t('auth.loginFailed'));
setError(String(msg));
setEmailNotVerified(code === 'EMAIL_NOT_VERIFIED');
if (code === 'CAPTCHA_REQUIRED' || code === 'CAPTCHA_INVALID') {
applyCaptchaChallenge(challenge);
} else if (captchaRequired) {
// Refresh challenge after any failed attempt once captcha is active.
// Turnstile tokens are single-use: always remount after a failed attempt.
if (code === 'CAPTCHA_REQUIRED' || code === 'CAPTCHA_INVALID' || captchaRequired) {
applyCaptchaChallenge(challenge ?? null);
}
} finally {
@ -336,14 +371,19 @@ export function LoginPage() {
slotProps={{ htmlInput: { inputMode: 'numeric', pattern: '[0-9]*' } as any }}
fullWidth
/>
{(captchaRequired &&
(captchaQ.data?.provider === 'turnstile' || mathChallenge?.provider === 'turnstile') &&
(captchaQ.data?.siteKey || mathChallenge?.siteKey)) && (
<TurnstileWidget
siteKey={(mathChallenge?.siteKey || captchaQ.data?.siteKey)!}
onToken={onCaptchaToken}
/>
)}
{captchaRequired &&
(turnstileSiteKey ||
captchaQ.data?.provider === 'turnstile' ||
mathChallenge?.provider === 'turnstile') &&
(turnstileSiteKey || captchaQ.data?.siteKey || mathChallenge?.siteKey) && (
<TurnstileWidget
key={turnstileMountKey}
siteKey={
(turnstileSiteKey || mathChallenge?.siteKey || captchaQ.data?.siteKey)!
}
onToken={onCaptchaToken}
/>
)}
{captchaRequired && mathChallenge?.provider === 'math' && mathChallenge.prompt && (
<TextField
label={t('auth.captchaMathLabel', { prompt: mathChallenge.prompt })}

View File

@ -9,8 +9,10 @@ declare global {
sitekey: string;
callback: (token: string) => void;
'expired-callback'?: () => void;
'error-callback'?: () => void;
}
) => string;
remove?: (widgetId: string) => void;
};
}
}
@ -23,43 +25,58 @@ type Props = {
/** Cloudflare Turnstile widget (loaded on demand). */
export function TurnstileWidget({ siteKey, onToken }: Props) {
const containerRef = useRef<HTMLDivElement>(null);
const onTokenRef = useRef(onToken);
onTokenRef.current = onToken;
useEffect(() => {
if (!siteKey || !containerRef.current) return;
let widgetId: string | null = null;
let cancelled = false;
const emit = (token: string | null) => {
if (!cancelled) onTokenRef.current(token);
};
const renderWidget = () => {
if (!containerRef.current || !window.turnstile) return;
if (cancelled || !containerRef.current || !window.turnstile) return;
containerRef.current.innerHTML = '';
window.turnstile.render(containerRef.current, {
widgetId = window.turnstile.render(containerRef.current, {
sitekey: siteKey,
callback: (token) => onToken(token),
'expired-callback': () => onToken(null),
callback: (token) => emit(token),
'expired-callback': () => emit(null),
'error-callback': () => emit(null),
});
};
if (window.turnstile) {
renderWidget();
return () => onToken(null);
} else {
const existing = document.querySelector('script[data-turnstile]');
if (existing) {
existing.addEventListener('load', renderWidget);
} else {
const script = document.createElement('script');
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
script.async = true;
script.dataset.turnstile = 'true';
script.onload = renderWidget;
document.head.appendChild(script);
}
}
const existing = document.querySelector('script[data-turnstile]');
if (existing) {
existing.addEventListener('load', renderWidget);
return () => {
existing.removeEventListener('load', renderWidget);
onToken(null);
};
}
const script = document.createElement('script');
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit';
script.async = true;
script.dataset.turnstile = 'true';
script.onload = renderWidget;
document.head.appendChild(script);
return () => onToken(null);
}, [siteKey, onToken]);
return () => {
cancelled = true;
emit(null);
if (widgetId && window.turnstile?.remove) {
try {
window.turnstile.remove(widgetId);
} catch {
/* ignore */
}
}
};
}, [siteKey]);
return <div ref={containerRef} />;
}

View File

@ -723,7 +723,7 @@ export const en = {
'Predict whether the next candle will be bearish (<strong>Short ↓</strong>) or bullish (<strong>Long ↑</strong>), then wait for the round result.',
refreshGame: 'Refresh game',
backToHome: 'Back to home',
loadError: 'Failed to load Candle Predict.',
loadError: 'Failed to load market data. Please try again.',
rateLimitHint: 'Too many API requests — wait a minute or restart the backend.',
apiHint: 'Run database migrations and ensure the API is running.',
singleCandle: 'Single candle',

View File

@ -733,7 +733,7 @@ export const fr = {
'Prédisez si la prochaine bougie sera baissière (<strong>Short ↓</strong>) ou haussière (<strong>Long ↑</strong>), puis attendez le résultat de la manche.',
refreshGame: 'Actualiser le jeu',
backToHome: 'Retour à l’accueil',
loadError: 'Impossible de charger Candle Predict.',
loadError: 'Impossible de charger les données de marché. Veuillez réessayer.',
rateLimitHint:
'Trop de requêtes API — attendez une minute ou redémarrez le backend.',
apiHint: 'Exécutez les migrations et vérifiez que l’API est active.',

142
scripts/export-user-i18n.js Normal file
View File

@ -0,0 +1,142 @@
/**
* Exhaustive export of user-facing i18n keys (web EN/FR + mobile app_strings).
* Excludes web admin.* namespace.
*/
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const root = path.resolve(__dirname, '..');
const outDir = path.join(root, 'docs', 'exports');
fs.mkdirSync(outDir, { recursive: true });
function flatten(obj, prefix = '', out = []) {
if (obj === null || obj === undefined) return out;
if (typeof obj !== 'object' || Array.isArray(obj)) {
out.push({ key: prefix, value: String(obj) });
return out;
}
for (const [k, v] of Object.entries(obj)) {
const next = prefix ? `${prefix}.${k}` : k;
if (v !== null && typeof v === 'object' && !Array.isArray(v)) flatten(v, next, out);
else out.push({ key: next, value: v == null ? '' : String(v) });
}
return out;
}
function isAdminKey(key) {
return key === 'admin' || key.startsWith('admin.');
}
function loadLocaleTs(file) {
let src = fs.readFileSync(file, 'utf8');
src = src.replace(/^import[^\n]*\n/gm, '');
// Drop trailing type-only exports.
src = src.replace(/\nexport\s+type[\s\S]*$/m, '\n');
src = src.replace(/export\s+const\s+(\w+)\s*=\s*/, 'var __locale = ');
src = src.replace(/\s+as\s+const\s*;?\s*$/m, '');
src = src.replace(/:\s*Record<[^>]+>/g, '');
src = src.replace(/\s+satisfies\s+[^=;\n]+/g, '');
// admin.reports.catalog references reportCatalogEn/Fr — stub (filtered out via admin.*).
src = `var reportCatalogEn = {};\nvar reportCatalogFr = {};\n` + src;
src += '\n;module.exports = __locale;';
const sandbox = { module: { exports: {} }, exports: {} };
vm.runInNewContext(src, sandbox, { filename: file });
return sandbox.module.exports;
}
function unescapeJsString(s) {
return s
.replace(/\\'/g, "'")
.replace(/\\"/g, '"')
.replace(/\\n/g, '\n')
.replace(/\\\\/g, '\\');
}
function extractMobileStrings(dartPath) {
const dart = fs.readFileSync(dartPath, 'utf8');
const rows = [];
const seen = new Set();
// Multiline-safe: String get name => t('en', 'fr');
// and String name(...) => t('en', 'fr');
const re =
/String\s+(?:get\s+)?(\w+)\s*(?:\([^;{]*\))?\s*=>\s*t\(\s*((?:'(?:\\'|[^'])*'|"(?:\\"|[^"])*")\s*,\s*(?:'(?:\\'|[^'])*'|"(?:\\"|[^"])*"))\s*\)/gs;
let m;
while ((m = re.exec(dart))) {
const key = m[1];
if (seen.has(key)) continue;
const pair = m[2];
const parts = pair.match(/'(?:\\'|[^'])*'|"(?:\\"|[^"])*"/g);
if (!parts || parts.length < 2) continue;
const en = unescapeJsString(parts[0].slice(1, -1));
const fr = unescapeJsString(parts[1].slice(1, -1));
seen.add(key);
rows.push({
platform: 'mobile',
feature: 'app_strings',
key,
en,
fr,
});
}
// Fallback: localizeReferralReason style maps with t() inside switch — skip for key dump
return rows;
}
function csvEscape(s) {
const v = String(s ?? '');
if (/[",\n\r]/.test(v)) return `"${v.replace(/"/g, '""')}"`;
return v;
}
const en = loadLocaleTs(path.join(root, 'prediqo_web/src/shared/i18n/locales/en.ts'));
const fr = loadLocaleTs(path.join(root, 'prediqo_web/src/shared/i18n/locales/fr.ts'));
const enFlat = flatten(en).filter((x) => !isAdminKey(x.key));
const frMap = Object.fromEntries(flatten(fr).map((x) => [x.key, x.value]));
const webRows = enFlat.map((x) => ({
platform: 'web',
feature: x.key.split('.')[0] || '',
key: x.key,
en: x.value,
fr: frMap[x.key] ?? '',
}));
const mobileRows = extractMobileStrings(
path.join(root, 'prediqo_mobile/lib/l10n/app_strings.dart')
);
const missingFr = webRows.filter((r) => !r.fr).map((r) => r.key);
const all = [...webRows, ...mobileRows];
const payload = {
generatedAt: new Date().toISOString(),
scope:
'Exhaustive user-facing i18n keys. Web excludes admin.*. Mobile from app_strings.dart getters/methods using t(en, fr).',
counts: {
total: all.length,
web: webRows.length,
mobile: mobileRows.length,
webMissingFr: missingFr.length,
},
webMissingFr: missingFr,
items: all,
};
const header = ['platform', 'feature', 'key', 'en', 'fr'];
const csv = [header.join(',')]
.concat(all.map((r) => header.map((h) => csvEscape(r[h])).join(',')))
.join('\n');
const jsonPath = path.join(outDir, 'user-i18n-keys.json');
const csvPath = path.join(outDir, 'user-i18n-keys.csv');
fs.writeFileSync(jsonPath, JSON.stringify(payload, null, 2), 'utf8');
fs.writeFileSync(csvPath, `\uFEFF${csv}\n`, 'utf8'); // BOM for Excel
console.log(JSON.stringify(payload.counts, null, 2));
console.log('JSON:', jsonPath);
console.log('CSV:', csvPath);