@thorprovider/create-thor-app 4.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +31 -68
  2. package/dist/index.js +158 -629
  3. package/package.json +1 -1
  4. package/templates/default/.agents/AGENTS.md +27 -0
  5. package/templates/default/.env.example +12 -33
  6. package/templates/default/.eslintrc.json +20 -27
  7. package/templates/default/README.md +60 -119
  8. package/templates/default/ai-validator.json +47 -29
  9. package/templates/default/app/api/revalidate/route.ts +27 -36
  10. package/templates/default/app/backend-unavailable/page.tsx +3 -7
  11. package/templates/default/app/error.tsx +1 -2
  12. package/templates/default/app/global-error.tsx +3 -3
  13. package/templates/default/app/globals.css +1 -71
  14. package/templates/default/app/layout.tsx +16 -38
  15. package/templates/default/app/not-found.tsx +1 -1
  16. package/templates/default/app/page.tsx +45 -113
  17. package/templates/default/components/providers/app-providers.tsx +19 -68
  18. package/templates/default/components/providers/cart-provider.tsx +155 -0
  19. package/templates/default/components/providers/commerce-provider.tsx +34 -0
  20. package/templates/default/components/providers/region-provider.tsx +115 -0
  21. package/templates/default/docs/README.md +52 -37
  22. package/templates/default/docs/commerce-api.md +58 -125
  23. package/templates/default/docs/patterns.md +128 -67
  24. package/templates/default/docs/project-structure.md +58 -50
  25. package/templates/default/docs/rules.md +44 -42
  26. package/templates/default/docs/types.md +105 -1024
  27. package/templates/default/lib/commerce.ts +52 -135
  28. package/templates/default/lib/env.ts +68 -94
  29. package/templates/default/lib/utils.ts +18 -0
  30. package/templates/default/next.config.ts +7 -0
  31. package/templates/default/package.json +2 -8
  32. package/templates/default/registry.json +6 -0
  33. package/templates/default/styles/tokens.css +81 -0
  34. package/templates/default/components/providers/navigation-provider.tsx +0 -37
  35. package/templates/default/config/site.config.ts +0 -156
  36. package/templates/default/docs/components.md +0 -282
  37. package/templates/default/docs/dependencies.md +0 -61
  38. package/templates/default/lib/auth-context.tsx +0 -213
  39. package/templates/default/lib/cart-provider.tsx +0 -53
  40. package/templates/default/lib/commerce-provider.tsx +0 -48
  41. package/templates/default/lib/region-detection.ts +0 -73
  42. package/templates/default/lib/region-provider.tsx +0 -53
  43. package/templates/default/lib/regions-config.ts +0 -48
  44. package/templates/default/lib/storefront-config.ts +0 -54
  45. package/templates/default/next.config.mjs +0 -51
  46. package/templates/default/proxy.ts +0 -155
  47. package/templates/default/scripts/generate-regions-config.ts +0 -498
@@ -1,155 +0,0 @@
1
- /**
2
- * @thorprovider/core — Next.js 16 Proxy (proxy.ts)
3
- *
4
- * Next.js 16 renamed middleware.ts → proxy.ts.
5
- * Export must be a named `proxy` function (not `export default`).
6
- *
7
- * Responsibilities:
8
- * 1. Backend health check — redirects to /backend-unavailable when unreachable
9
- *
10
- * Out of scope for @thorprovider/core (add in your starter):
11
- * - Admin JWT route protection
12
- * - Custom route guards per business domain
13
- */
14
-
15
- import { NextResponse } from 'next/server';
16
- import type { NextRequest } from 'next/server';
17
-
18
- // ---------------------------------------------------------------------------
19
- // Routes that bypass the backend health check
20
- // ---------------------------------------------------------------------------
21
-
22
- const BYPASS_ROUTES = [
23
- '/backend-unavailable',
24
- '/_next',
25
- '/_vercel',
26
- '/api/health',
27
- '/favicon.ico',
28
- '/robots.txt',
29
- '/sitemap.xml',
30
- ];
31
-
32
- // ---------------------------------------------------------------------------
33
- // Lightweight Edge Circuit Breaker
34
- // ---------------------------------------------------------------------------
35
-
36
- class LightweightCircuitBreaker {
37
- private failures = 0;
38
- private lastFailTime = 0;
39
- private readonly FAILURE_THRESHOLD = 5;
40
- private readonly RESET_TIMEOUT = 60000; // 1 minute auto-reset
41
-
42
- get isOpen(): boolean {
43
- if (this.failures >= this.FAILURE_THRESHOLD) {
44
- if (Date.now() - this.lastFailTime > this.RESET_TIMEOUT) {
45
- this.reset();
46
- return false;
47
- }
48
- return true;
49
- }
50
- return false;
51
- }
52
-
53
- recordSuccess(): void { this.reset(); }
54
- recordFailure(): void { this.failures++; this.lastFailTime = Date.now(); }
55
- private reset(): void { this.failures = 0; this.lastFailTime = 0; }
56
- }
57
-
58
- const healthCircuit = new LightweightCircuitBreaker();
59
- let healthCheckCache: { result: boolean; timestamp: number } | null = null;
60
- const HEALTH_CHECK_CACHE_TTL = 30000; // 30 seconds
61
- const HEALTH_CHECK_TIMEOUT_MS = 3000;
62
-
63
- function sleep(ms: number): Promise<void> {
64
- return new Promise((resolve) => setTimeout(resolve, ms));
65
- }
66
-
67
- /**
68
- * Lightweight backend health check for edge middleware.
69
- *
70
- * - Skipped in development (edge fetch to external HTTPS has known local issues)
71
- * - Fail-open: when circuit opens, ALLOW access rather than blocking users
72
- * - Health endpoint: NEXT_PUBLIC_COMMERCE_API_URL + HEALTH_CHECK_PATH
73
- * (default HEALTH_CHECK_PATH = /store/regions for Medusa; adjust for other providers)
74
- * Starters can override HEALTH_CHECK_PATH with any endpoint that returns 200
75
- */
76
- async function quickHealthCheck(): Promise<boolean> {
77
- if (process.env.NODE_ENV === 'development') return true;
78
- if (healthCircuit.isOpen) return healthCheckCache?.result ?? true;
79
- if (healthCheckCache && Date.now() - healthCheckCache.timestamp < HEALTH_CHECK_CACHE_TTL) {
80
- return healthCheckCache.result;
81
- }
82
-
83
- const backendUrl = process.env.NEXT_PUBLIC_COMMERCE_API_URL?.replace(/\/+$/, '');
84
- const apiKey = process.env.NEXT_PUBLIC_COMMERCE_API_KEY;
85
- const healthPath = process.env.HEALTH_CHECK_PATH || '/store/regions';
86
-
87
- if (!backendUrl || !apiKey) {
88
- healthCircuit.recordFailure();
89
- healthCheckCache = { result: false, timestamp: Date.now() };
90
- return false;
91
- }
92
-
93
- for (let attempt = 0; attempt <= 1; attempt++) {
94
- try {
95
- const controller = new AbortController();
96
- const timeoutId = setTimeout(() => controller.abort(), HEALTH_CHECK_TIMEOUT_MS);
97
- const response = await fetch(`${backendUrl}${healthPath}`, {
98
- signal: controller.signal,
99
- headers: { 'x-publishable-api-key': apiKey },
100
- });
101
- clearTimeout(timeoutId);
102
- if (response.ok) {
103
- healthCircuit.recordSuccess();
104
- healthCheckCache = { result: true, timestamp: Date.now() };
105
- return true;
106
- }
107
- if (attempt < 1) await sleep(300 * Math.pow(2, attempt));
108
- } catch {
109
- if (attempt < 1) await sleep(300 * Math.pow(2, attempt));
110
- }
111
- }
112
-
113
- healthCircuit.recordFailure();
114
- healthCheckCache = { result: false, timestamp: Date.now() };
115
- return false;
116
- }
117
-
118
- function shouldBypassHealthCheck(pathname: string): boolean {
119
- return BYPASS_ROUTES.some((r) => pathname.startsWith(r));
120
- }
121
-
122
- // ---------------------------------------------------------------------------
123
- // Proxy Function (Next.js 16 named export — replaces `export default middleware`)
124
- // ---------------------------------------------------------------------------
125
-
126
- export async function proxy(request: NextRequest) {
127
- const { pathname } = request.nextUrl;
128
-
129
- // Pass static files + API routes immediately — no processing needed
130
- if (
131
- pathname.startsWith('/_next') ||
132
- pathname.startsWith('/api') ||
133
- pathname.includes('.')
134
- ) {
135
- return NextResponse.next();
136
- }
137
-
138
- // Backend health check → redirect to /backend-unavailable on failure
139
- if (!shouldBypassHealthCheck(pathname)) {
140
- const isHealthy = await quickHealthCheck();
141
- if (!isHealthy) {
142
- const unavailableUrl = new URL('/backend-unavailable', request.url);
143
- unavailableUrl.searchParams.set('returnTo', pathname);
144
- return NextResponse.redirect(unavailableUrl);
145
- }
146
- }
147
-
148
- // No i18n — just pass through
149
- return NextResponse.next();
150
- }
151
-
152
- export const config = {
153
- // Match all pathnames except Next.js internals, API routes, and static files
154
- matcher: '/((?!api|_next|_vercel|.*\\..*).*)' ,
155
- };
@@ -1,498 +0,0 @@
1
- #!/usr/bin/env tsx
2
- /**
3
- * Generate Regions Configuration
4
- *
5
- * This script queries the commerce backend (database) to fetch all available regions
6
- * and generates a TypeScript configuration file that maps locales to actual regions.
7
- *
8
- * This eliminates hardcoded region mappings and ensures the app only redirects
9
- * to regions that actually exist in the database.
10
- *
11
- * RESILIENCE STRATEGY:
12
- * - Missing backend credentials (during package publishing): Generates English-only fallback config (no error)
13
- * - Transient network failures: Implements exponential backoff retry logic (3 attempts)
14
- * - Backend temporarily unavailable: Generates English-only fallback config (no error)
15
- * This ensures builds never fail due to backend unavailability or missing credentials.
16
- *
17
- * CONFIGURATION (Environment Variables):
18
- * - REGIONS_SCRIPT_MAX_RETRIES: Maximum retry attempts (default: 3)
19
- * - REGIONS_SCRIPT_RETRY_DELAY: Initial delay in ms (default: 1000)
20
- * - REGIONS_SCRIPT_RETRY_MAX_DELAY: Maximum delay in ms (default: 10000)
21
- * - REGIONS_SCRIPT_RETRY_BACKOFF: Backoff multiplier (default: 2)
22
- *
23
- * Run before build/dev to ensure configuration is up to date:
24
- * - yarn prebuild (automatic)
25
- * - yarn predev (automatic)
26
- * - yarn generate:regions (manual)
27
- *
28
- * @see packages/core/lib/regions-config.ts (output)
29
- */
30
-
31
- import { resolve, dirname } from 'path';
32
- import { writeFileSync, mkdirSync, readFileSync } from 'fs';
33
- import { fileURLToPath } from 'url';
34
-
35
- // ESM __dirname equivalent
36
- const __filename = fileURLToPath(import.meta.url);
37
- const __dirname = dirname(__filename);
38
-
39
- // ---------------------------------------------------------------------------
40
- // CLI Arguments Resolution
41
- // ---------------------------------------------------------------------------
42
- // Accepts CLI args:
43
- // - --package-dir=<path> : Package directory (relative to monorepo root, env var PACKAGE_DIR as fallback)
44
- // - --base-url=<url> : Commerce backend URL (e.g., http://localhost:9000)
45
- // - --api-key=<key> : Commerce API key (e.g., pk_live_xxx)
46
- //
47
- // If --base-url or --api-key are missing, generates English-only fallback (no error).
48
- // This enables publishing packages without requiring backend credentials.
49
- // ---------------------------------------------------------------------------
50
- function resolveCliArg(name: string): string | undefined {
51
- const argFlag = process.argv.find((a) => a.startsWith(`--${name}=`));
52
- return argFlag ? argFlag.split('=')[1] : undefined;
53
- }
54
-
55
- function resolvePackageDir(): string {
56
- return resolveCliArg('package-dir') || process.env.PACKAGE_DIR || 'packages/core';
57
- }
58
-
59
- const PACKAGE_DIR = resolvePackageDir();
60
- const MONOREPO_ROOT = resolve(__dirname, '..');
61
-
62
- // Credentials are now passed as CLI args (dependency injection)
63
- // This keeps the script agnóstic of env var naming conventions
64
- const CLI_BASE_URL = resolveCliArg('base-url');
65
- const CLI_API_KEY = resolveCliArg('api-key');
66
-
67
- // Load environment variables from target package .env file (fallback for CLI args)
68
- function loadEnvFile() {
69
- const envPath = resolve(MONOREPO_ROOT, PACKAGE_DIR, '.env');
70
- try {
71
- const envContent = readFileSync(envPath, 'utf-8');
72
- const lines = envContent.split('\n');
73
-
74
- lines.forEach(line => {
75
- const trimmed = line.trim();
76
- // Skip comments and empty lines
77
- if (!trimmed || trimmed.startsWith('#')) return;
78
-
79
- const equalIndex = trimmed.indexOf('=');
80
- if (equalIndex === -1) return;
81
-
82
- const key = trimmed.substring(0, equalIndex).trim();
83
- const value = trimmed.substring(equalIndex + 1).trim();
84
-
85
- // Only set from file if not already set via CLI args or process.env
86
- if (key && value && !process.env[key]) {
87
- process.env[key] = value;
88
- }
89
- });
90
- } catch (error) {
91
- // .env file not found, continue with existing env vars
92
- }
93
- }
94
-
95
- // Load .env before anything else
96
- loadEnvFile();
97
-
98
- // Color logging utilities
99
- const colors = {
100
- reset: '\x1b[0m',
101
- bright: '\x1b[1m',
102
- green: '\x1b[32m',
103
- yellow: '\x1b[33m',
104
- red: '\x1b[31m',
105
- cyan: '\x1b[36m',
106
- };
107
-
108
- function log(message: string, color = colors.reset) {
109
- console.log(`${color}${message}${colors.reset}`);
110
- }
111
-
112
- // Retry configuration from environment variables
113
- const RETRY_CONFIG = {
114
- maxAttempts: parseInt(process.env.REGIONS_SCRIPT_MAX_RETRIES || '3', 10),
115
- initialDelayMs: parseInt(process.env.REGIONS_SCRIPT_RETRY_DELAY || '1000', 10),
116
- maxDelayMs: parseInt(process.env.REGIONS_SCRIPT_RETRY_MAX_DELAY || '10000', 10),
117
- backoffMultiplier: parseFloat(process.env.REGIONS_SCRIPT_RETRY_BACKOFF || '2'),
118
- };
119
-
120
- /**
121
- * Sleep utility for retry delays
122
- */
123
- function sleep(ms: number): Promise<void> {
124
- return new Promise(resolve => setTimeout(resolve, ms));
125
- }
126
-
127
- /**
128
- * Retry wrapper with exponential backoff
129
- * Wraps any async function and retries it on failure
130
- */
131
- async function withRetry<T>(
132
- operation: () => Promise<T>,
133
- operationName: string,
134
- attempt: number = 1
135
- ): Promise<T> {
136
- try {
137
- return await operation();
138
- } catch (error) {
139
- // If we've exhausted all attempts, throw the error
140
- if (attempt >= RETRY_CONFIG.maxAttempts) {
141
- log(`\n❌ Failed after ${attempt} attempt(s): ${operationName}`, colors.red);
142
- throw error;
143
- }
144
-
145
- // Calculate delay with exponential backoff
146
- const baseDelay = RETRY_CONFIG.initialDelayMs * Math.pow(RETRY_CONFIG.backoffMultiplier, attempt - 1);
147
- const delay = Math.min(baseDelay, RETRY_CONFIG.maxDelayMs);
148
- const nextAttempt = attempt + 1;
149
-
150
- log(`\n⚠️ Attempt ${attempt}/${RETRY_CONFIG.maxAttempts} failed: ${operationName}`, colors.yellow);
151
- log(` Error: ${error instanceof Error ? error.message : String(error)}`, colors.yellow);
152
- log(` Retrying in ${delay}ms... (attempt ${nextAttempt}/${RETRY_CONFIG.maxAttempts})`, colors.cyan);
153
-
154
- await sleep(delay);
155
-
156
- // Recursive retry
157
- return withRetry(operation, operationName, nextAttempt);
158
- }
159
- }
160
-
161
- // ISO country code to locale mappings
162
- // This determines which locales we support based on which countries exist in regions
163
- const COUNTRY_TO_LOCALE_MAP: Record<string, string[]> = {
164
- // English-speaking countries
165
- 'US': ['en'],
166
- 'GB': ['en'],
167
- 'CA': ['en', 'fr'], // Canada supports both English and French
168
- 'AU': ['en'],
169
- 'NZ': ['en'],
170
- 'IE': ['en'],
171
-
172
- // Spanish-speaking countries
173
- 'ES': ['es'],
174
- 'MX': ['es'],
175
- 'AR': ['es'],
176
- 'CL': ['es'],
177
- 'CO': ['es'],
178
- 'PE': ['es'],
179
- 'VE': ['es'],
180
-
181
- // French-speaking countries
182
- 'FR': ['fr'],
183
- 'BE': ['fr', 'nl'], // Belgium supports French and Dutch
184
- 'CH': ['fr', 'de', 'it'], // Switzerland supports multiple languages
185
- 'LU': ['fr', 'de'],
186
-
187
- // German-speaking countries
188
- 'DE': ['de'],
189
- 'AT': ['de'],
190
-
191
- // Add more mappings as needed
192
- };
193
-
194
- // Fallback: if a country isn't in the map, use English
195
- const FALLBACK_LOCALE = 'en';
196
-
197
- interface RegionData {
198
- id: string;
199
- name: string;
200
- currency_code: string;
201
- countries?: Array<{
202
- id: string;
203
- iso_2: string;
204
- name: string;
205
- }>;
206
- }
207
-
208
- /**
209
- * Determine which locales a region supports based on its countries
210
- */
211
- function getLocalesForRegion(region: RegionData): string[] {
212
- if (!region.countries || region.countries.length === 0) {
213
- // Region has no countries defined, default to English
214
- return [FALLBACK_LOCALE];
215
- }
216
-
217
- const localesSet = new Set<string>();
218
-
219
- for (const country of region.countries) {
220
- const countryCode = country.iso_2.toUpperCase();
221
- const locales = COUNTRY_TO_LOCALE_MAP[countryCode] || [FALLBACK_LOCALE];
222
- locales.forEach(locale => localesSet.add(locale));
223
- }
224
-
225
- return Array.from(localesSet);
226
- }
227
-
228
- /**
229
- * Build locale to region mapping
230
- * If multiple regions support the same locale, prefer the first one found
231
- */
232
- function buildLocaleToRegionMap(regions: RegionData[]): Record<string, string> {
233
- const localeMap: Record<string, string> = {};
234
-
235
- for (const region of regions) {
236
- const locales = getLocalesForRegion(region);
237
-
238
- for (const locale of locales) {
239
- // Only set if not already mapped (first region wins)
240
- if (!localeMap[locale]) {
241
- localeMap[locale] = region.id;
242
- }
243
- }
244
- }
245
-
246
- return localeMap;
247
- }
248
-
249
- /**
250
- * Main script execution
251
- */
252
- async function generateRegionsConfig() {
253
- log('\n🔧 Generating Regions Configuration from Database...', colors.bright);
254
- log(` Max retries: ${RETRY_CONFIG.maxAttempts}`, colors.cyan);
255
- log(` Initial delay: ${RETRY_CONFIG.initialDelayMs}ms`, colors.cyan);
256
- log(` Backoff multiplier: ${RETRY_CONFIG.backoffMultiplier}x`, colors.cyan);
257
-
258
- try {
259
- await generateRegionsConfigWithRetry();
260
- } catch (error) {
261
- log('\n❌ All retry attempts exhausted. Generating safe fallback configuration...', colors.red);
262
- log(` Error: ${error instanceof Error ? error.message : String(error)}`, colors.red);
263
-
264
- // Generate fallback configuration to prevent build failures
265
- const fallbackConfig = generateConfigFile(
266
- ['en'],
267
- 'en',
268
- {},
269
- undefined,
270
- true
271
- );
272
-
273
- writeConfigFile(fallbackConfig);
274
-
275
- log('\n⚠️ Generated fallback configuration (English only)', colors.yellow);
276
- log(' Your build will continue, but regions functionality will be limited.', colors.yellow);
277
- log(' Please check your backend connectivity and configuration.', colors.yellow);
278
-
279
- // Exit with success to allow build to continue
280
- // The app will work with fallback config
281
- process.exit(0);
282
- }
283
- }
284
-
285
- /**
286
- * Core logic wrapped with retry capability
287
- */
288
- async function generateRegionsConfigWithRetry() {
289
- // 1. EARLY CHECK: Validate credentials (from CLI args or env vars)
290
- // Credentials come from CLI args (--base-url, --api-key) or .env file as fallback.
291
- // If missing, generate fallback immediately (no need to retry)
292
- const backendUrl = (CLI_BASE_URL || process.env.NEXT_PUBLIC_COMMERCE_API_URL)?.trim().replace(/\/+$/, '');
293
- const apiKey = CLI_API_KEY || process.env.NEXT_PUBLIC_COMMERCE_API_KEY;
294
-
295
- if (!backendUrl || !apiKey) {
296
- log('\n⏭️ Missing backend credentials, generating fallback configuration...', colors.yellow);
297
- if (!backendUrl) log(' - Base URL not provided (--base-url or NEXT_PUBLIC_COMMERCE_API_URL)', colors.reset);
298
- if (!apiKey) log(' - API Key not provided (--api-key or NEXT_PUBLIC_COMMERCE_API_KEY)', colors.reset);
299
- log(' (This is normal during package publishing - regions will be English-only)', colors.reset);
300
-
301
- // Generate fallback configuration immediately without retries
302
- const fallbackConfig = generateConfigFile(
303
- ['en'],
304
- 'en',
305
- {},
306
- undefined,
307
- true
308
- );
309
-
310
- writeConfigFile(fallbackConfig);
311
- log('\n✅ Generated fallback configuration', colors.green);
312
- return; // Exit early (successful fallback, not an error)
313
- }
314
-
315
- // 2. Credentials exist, proceed with retry logic
316
- await withRetry(async () => {
317
- // 0. Dynamically import createProvider (needs compiled package)
318
- const { createProvider } = await import('@thorprovider/adapters');
319
-
320
- // Backend credentials are guaranteed to exist here
321
-
322
- log(`\n Backend URL: ${backendUrl}`, colors.cyan);
323
- log(` API Key: ${apiKey.substring(0, 10)}...`, colors.cyan);
324
-
325
- // 2. Initialize commerce provider (credentials already validated above)
326
- log('\n📡 Connecting to commerce backend...', colors.cyan);
327
- const commerce = createProvider({
328
- provider: 'medusa',
329
- config: {
330
- baseUrl: backendUrl,
331
- publishableKey: apiKey,
332
- debug: false,
333
- retry: {
334
- maxRetries: 3,
335
- timeoutMs: 10000,
336
- initialDelayMs: 300,
337
- backoffMultiplier: 2,
338
- maxDelayMs: 5000,
339
- },
340
- },
341
- });
342
-
343
- // 3. Fetch regions from database
344
- if (!commerce.getRegions) {
345
- throw new Error('Commerce provider does not support getRegions()');
346
- }
347
-
348
- log(' Fetching regions from database...', colors.cyan);
349
- const regions = await commerce.getRegions();
350
-
351
- if (!regions || regions.length === 0) {
352
- log('\n⚠️ No regions found in database!', colors.yellow);
353
- log(' Creating default English-only configuration...', colors.yellow);
354
-
355
- // Fallback configuration when no regions exist
356
- const fallbackConfig = generateConfigFile(
357
- ['en'],
358
- 'en',
359
- {},
360
- undefined,
361
- true
362
- );
363
-
364
- writeConfigFile(fallbackConfig);
365
- log('\n✅ Generated fallback configuration (English only)', colors.green);
366
- return; // Successfully completed (with fallback)
367
- }
368
-
369
- log(` Found ${regions.length} region(s)`, colors.green);
370
-
371
- // 4. Display regions information
372
- log('\n📊 Regions Analysis:', colors.bright);
373
- regions.forEach((region, index) => {
374
- const countryCount = region.countries?.length || 0;
375
- const countryCodes = region.countries?.map(c => c.iso_2).join(', ') || 'none';
376
- log(` ${index + 1}. ${region.name} (${region.id})`, colors.cyan);
377
- log(` Currency: ${region.currency_code}`, colors.reset);
378
- log(` Countries: ${countryCodes} (${countryCount} total)`, colors.reset);
379
- });
380
-
381
- // 5. Build locale mappings
382
- const localeToRegionMap = buildLocaleToRegionMap(regions);
383
- const supportedLocales = Object.keys(localeToRegionMap).sort();
384
-
385
- // Default locale: prefer 'en' if available, otherwise use first alphabetically
386
- const defaultLocale = supportedLocales.includes('en') ? 'en' : supportedLocales[0];
387
-
388
- // Fallback region: prefer the region mapped to default locale, or first region
389
- const fallbackRegionId = localeToRegionMap[defaultLocale] || regions[0].id;
390
-
391
- // 6. Display mapping information
392
- log('\n🗺️ Locale → Region Mapping:', colors.bright);
393
- supportedLocales.forEach(locale => {
394
- const regionId = localeToRegionMap[locale];
395
- const region = regions.find(r => r.id === regionId);
396
- log(` ${locale} → ${regionId} (${region?.name})`, colors.cyan);
397
- });
398
-
399
- log(`\n📍 Default Locale: ${defaultLocale}`, colors.green);
400
- log(`📍 Fallback Region: ${fallbackRegionId}`, colors.green);
401
-
402
- // 7. Generate TypeScript configuration file
403
- const configContent = generateConfigFile(
404
- supportedLocales,
405
- defaultLocale,
406
- localeToRegionMap,
407
- fallbackRegionId,
408
- false
409
- );
410
-
411
- // 8. Write to file
412
- writeConfigFile(configContent);
413
-
414
- log('\n✅ Successfully generated regions configuration!', colors.green);
415
- log(` Output: ${PACKAGE_DIR}/lib/regions-config.ts`, colors.cyan);
416
- log('\n💡 This file has been generated automatically from your database.', colors.yellow);
417
- log(' It will be updated before each build/dev run.', colors.yellow);
418
- }, 'Generate Regions Configuration');
419
- }
420
-
421
- /**
422
- * Generate the TypeScript configuration file content
423
- */
424
- function generateConfigFile(
425
- supportedLocales: string[],
426
- defaultLocale: string,
427
- localeToRegionMap: Record<string, string>,
428
- fallbackRegionId: string | undefined,
429
- isFallback: boolean
430
- ): string {
431
- const timestamp = new Date().toISOString();
432
- const warningComment = isFallback
433
- ? ' * ⚠️ FALLBACK CONFIG: No regions found in database!\n' +
434
- ' * This is a minimal configuration using English only.\n' +
435
- ' * Please ensure your backend has regions configured.\n'
436
- : '';
437
-
438
- return `/**
439
- * Auto-generated Regions Configuration
440
- *
441
- * This file is automatically generated by scripts/generate-regions-config.ts
442
- * DO NOT EDIT MANUALLY - Your changes will be overwritten!
443
- *
444
- ${warningComment} * Generated: ${timestamp}
445
- *
446
- * To regenerate:
447
- * - Run: yarn generate:regions (from the package directory)
448
- * - Or: Build/dev will regenerate automatically (prebuild/predev hooks)
449
- *
450
- * This configuration maps locales to actual regions from your database,
451
- * ensuring users are only redirected to regions that actually exist.
452
- */
453
-
454
- /**
455
- * List of all supported locales
456
- * Determined by analyzing countries in each region
457
- */
458
- export const supportedLocales = ${JSON.stringify(supportedLocales, null, 2)} as const;
459
-
460
- /**
461
- * Default locale to use when no match is found
462
- */
463
- export const defaultLocale = ${JSON.stringify(defaultLocale)} as const;
464
-
465
- /**
466
- * Mapping from locale to region ID
467
- * This ensures locale-based routing maps to real database regions
468
- */
469
- export const localeToRegionMap: Record<string, string> = ${JSON.stringify(localeToRegionMap, null, 2)};
470
-
471
- /**
472
- * Fallback region ID when no region is detected
473
- * Used as last resort if locale mapping fails
474
- */
475
- export const fallbackRegionId = ${fallbackRegionId ? JSON.stringify(fallbackRegionId) : 'undefined'};
476
-
477
- /**
478
- * Type helper for supported locales
479
- */
480
- export type SupportedLocale = typeof supportedLocales[number];
481
- `;
482
- }
483
-
484
- /**
485
- * Write configuration file to disk
486
- */
487
- function writeConfigFile(content: string) {
488
- const outputPath = resolve(MONOREPO_ROOT, PACKAGE_DIR, 'lib/regions-config.ts');
489
-
490
- // Ensure directory exists
491
- mkdirSync(dirname(outputPath), { recursive: true });
492
-
493
- // Write file
494
- writeFileSync(outputPath, content, 'utf-8');
495
- }
496
-
497
- // Execute script
498
- generateRegionsConfig();