UNPKG

@gulibs/react-autoroutes-client

Version:

Client-side utilities for React auto routes

2,841 lines 103 kB
'use strict';

var React = require('react');
var reactRouter = require('react-router');
var _ = require('lodash');
var jsxRuntime = require('react/jsx-runtime');
var reactStorage = require('@gulibs/react-storage');

/**
 * 定义路由句柄
 */
function defineHandle(options) {
    return options;
}
// ============= 中间件定义 =============
/**
 * 定义中间件
 */
function defineMiddleware(options) {
    return {
        name: options.name || 'anonymous',
        priority: options.priority || 50,
        devOnly: options.devOnly || false,
        handler: options.handler
    };
}
// ============= 守卫定义 =============
/**
 * 定义路由守卫
 */
function defineGuard(options) {
    return {
        name: options.name || 'anonymous',
        type: options.type || 'custom',
        redirectTo: options.redirectTo || '/403',
        errorMessage: options.errorMessage,
        condition: options.condition
    };
}
// ============= 认证定义 =============
/**
 * 定义认证守卫
 */
function defineAuth(options = {}) {
    const defaultCheck = (context) => {
        // 基本认证检查:用户是否存在
        if (!context.user) {
            return false;
        }
        // 角色检查
        if (options.roles && options.roles.length > 0) {
            if (!context.roles || !context.roles.some(role => options.roles.includes(role))) {
                return false;
            }
        }
        // 权限检查
        if (options.permissions && options.permissions.length > 0) {
            if (!context.permissions || !context.permissions.some(perm => options.permissions.includes(perm))) {
                return false;
            }
        }
        return true;
    };
    return {
        name: options.name || 'auth',
        redirectTo: options.redirectTo || '/login',
        errorMessage: options.errorMessage || 'Authentication required',
        check: options.check || defaultCheck,
        roles: options.roles,
        permissions: options.permissions
    };
}
// ============= 便捷的守卫工厂 =============
/**
 * 创建角色守卫
 */
function defineRoleGuard(roles, redirectTo) {
    return defineAuth({
        name: 'role-guard',
        roles,
        redirectTo: redirectTo || '/403',
        errorMessage: `Access denied. Required roles: ${roles.join(', ')}`
    });
}
/**
 * 创建权限守卫
 */
function definePermissionGuard(permissions, redirectTo) {
    return defineAuth({
        name: 'permission-guard',
        permissions,
        redirectTo: redirectTo || '/403',
        errorMessage: `Access denied. Required permissions: ${permissions.join(', ')}`
    });
}
/**
 * 创建自定义守卫
 */
function defineCustomGuard(name, condition, redirectTo) {
    return defineGuard({
        name,
        type: 'custom',
        condition,
        redirectTo: redirectTo || '/403',
        errorMessage: `Access denied by custom guard: ${name}`
    });
}

/******************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */


function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
    var e = new Error(message);
    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};

/**
 * 客户端性能优化模块
 * 提供缓存管理、并行处理、内存优化等功能
 */
class PerformanceCache {
    constructor(maxSize = 100) {
        this.cache = new Map();
        this.accessTimes = new Map();
        this.maxSize = maxSize;
    }
    get(key) {
        const value = this.cache.get(key);
        if (value !== undefined) {
            this.accessTimes.set(key, Date.now());
        }
        return value;
    }
    set(key, value) {
        // 如果缓存已满,删除最久未访问的条目
        if (this.cache.size >= this.maxSize && !this.cache.has(key)) {
            this.evictLRU();
        }
        this.cache.set(key, value);
        this.accessTimes.set(key, Date.now());
    }
    has(key) {
        return this.cache.has(key);
    }
    delete(key) {
        this.accessTimes.delete(key);
        return this.cache.delete(key);
    }
    clear() {
        this.cache.clear();
        this.accessTimes.clear();
    }
    size() {
        return this.cache.size;
    }
    evictLRU() {
        let oldestKey;
        let oldestTime = Date.now();
        for (const [key, time] of this.accessTimes) {
            if (time < oldestTime) {
                oldestTime = time;
                oldestKey = key;
            }
        }
        if (oldestKey !== undefined) {
            this.delete(oldestKey);
        }
    }
}
class PerformanceTracker {
    constructor() {
        this.timers = new Map();
        this.counters = new Map();
    }
    startTimer(name) {
        this.timers.set(name, Date.now());
    }
    endTimer(name) {
        const startTime = this.timers.get(name);
        if (startTime === undefined) {
            return 0;
        }
        const duration = Date.now() - startTime;
        this.timers.delete(name);
        return duration;
    }
    increment(name) {
        const current = this.counters.get(name) || 0;
        this.counters.set(name, current + 1);
    }
    getCounter(name) {
        return this.counters.get(name) || 0;
    }
    reset() {
        this.timers.clear();
        this.counters.clear();
    }
    getStats() {
        return {
            counters: Object.fromEntries(this.counters),
            activeTimers: Array.from(this.timers.keys())
        };
    }
}
class BatchProcessor {
    constructor(batchSize = 10, delay = 50) {
        this.batchSize = batchSize;
        this.delay = delay;
    }
    processBatch(items, processor) {
        return __awaiter(this, void 0, void 0, function* () {
            const results = [];
            for (let i = 0; i < items.length; i += this.batchSize) {
                const batch = items.slice(i, i + this.batchSize);
                const batchResults = yield Promise.all(batch.map(processor));
                results.push(...batchResults);
                // 添加小延迟防止阻塞事件循环
                if (i + this.batchSize < items.length) {
                    yield new Promise(resolve => setTimeout(resolve, this.delay));
                }
            }
            return results;
        });
    }
}
class Debouncer {
    constructor() {
        this.timers = new Map();
    }
    debounce(key, fn, delay) {
        const existingTimer = this.timers.get(key);
        if (existingTimer) {
            clearTimeout(existingTimer);
        }
        const timer = setTimeout(() => {
            fn();
            this.timers.delete(key);
        }, delay); // Type assertion for browser compatibility
        this.timers.set(key, timer);
    }
    cancel(key) {
        const timer = this.timers.get(key);
        if (timer) {
            clearTimeout(timer);
            this.timers.delete(key);
        }
    }
    cancelAll() {
        for (const timer of this.timers.values()) {
            clearTimeout(timer);
        }
        this.timers.clear();
    }
}
class MemoryOptimizer {
    constructor() {
        this.cleanupTasks = [];
        this.intervalId = null;
    }
    static getInstance() {
        if (!MemoryOptimizer.instance) {
            MemoryOptimizer.instance = new MemoryOptimizer();
        }
        return MemoryOptimizer.instance;
    }
    addCleanupTask(task) {
        this.cleanupTasks.push(task);
    }
    startPeriodicCleanup(intervalMs = 60000) {
        if (this.intervalId) {
            clearInterval(this.intervalId);
        }
        this.intervalId = setInterval(() => {
            this.runCleanup();
        }, intervalMs); // Type assertion for browser compatibility
    }
    runCleanup() {
        this.cleanupTasks.forEach(task => {
            try {
                task();
            }
            catch (error) {
                console.warn('Cleanup task failed:', error);
            }
        });
    }
    dispose() {
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
        }
        this.runCleanup();
        this.cleanupTasks = [];
    }
}
// 全局性能实例
const globalPerformanceTracker = new PerformanceTracker();
const globalMemoryOptimizer = MemoryOptimizer.getInstance();
// 工具函数
function measureAsync(name, fn) {
    return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
        const startTime = Date.now();
        try {
            const result = yield fn();
            const duration = Date.now() - startTime;
            resolve(Object.assign(result, { duration }));
        }
        catch (error) {
            reject(error);
        }
    }));
}

/**
 * 将对象转换为格式化的JSON字符串
 * 支持Map类型的自动转换
 */
function toJSON(obj) {
    return JSON.stringify(_.isMap(obj) ? mapToArray(obj) : obj, null, 2);
}
/**
 * 将Map对象转换为数组
 */
function mapToArray(map) {
    return Array.from(map.values());
}
/**
 * 检查对象是否为记录类型
 */
const isRecord = (obj) => {
    return typeof obj === 'object' && obj !== null;
};
// ============= 路由相关工具函数 =============
/**
 * 规范化路由路径
 * 移除多余的斜杠,确保路径格式正确
 */
function normalizePath(path) {
    if (!path || path === '/')
        return '/';
    // 移除多余的斜杠
    const normalized = path.replace(/\/{2,}/g, '/');
    // 移除末尾的斜杠(除了根路径)
    return normalized.length > 1 && normalized.endsWith('/')
        ? normalized.slice(0, -1)
        : normalized;
}
/**
 * 连接路径片段
 */
function joinPath(...segments) {
    const joined = segments
        .filter(Boolean)
        .join('/')
        .replace(/\/{2,}/g, '/');
    return normalizePath(joined);
}
/**
 * 检查路径是否匹配模式
 * 支持动态参数匹配
 */
function matchPath(pattern, path) {
    const patternParts = pattern.split('/').filter(Boolean);
    const pathParts = path.split('/').filter(Boolean);
    if (patternParts.length !== pathParts.length)
        return false;
    return patternParts.every((part, index) => {
        return part.startsWith(':') || part === pathParts[index];
    });
}
/**
 * 从路径中提取参数
 */
function extractParams(pattern, path) {
    const params = {};
    const patternParts = pattern.split('/').filter(Boolean);
    const pathParts = path.split('/').filter(Boolean);
    if (patternParts.length !== pathParts.length)
        return params;
    patternParts.forEach((part, index) => {
        if (part.startsWith(':')) {
            const paramName = part.slice(1);
            params[paramName] = pathParts[index];
        }
    });
    return params;
}
// ============= 类型检查工具函数 =============
/**
 * 检查值是否为空(null、undefined、空字符串、空数组、空对象)
 */
function isEmpty(value) {
    if (value == null)
        return true;
    if (typeof value === 'string')
        return value.trim().length === 0;
    if (Array.isArray(value))
        return value.length === 0;
    if (typeof value === 'object')
        return Object.keys(value).length === 0;
    return false;
}
/**
 * 检查值是否为函数
 */
function isFunction(value) {
    return typeof value === 'function';
}
/**
 * 检查值是否为Promise
 */
function isPromise(value) {
    return value != null && typeof value.then === 'function';
}
/**
 * 安全的类型转换
 */
function safeParseInt(value, defaultValue = 0) {
    const parsed = parseInt(value, 10);
    return isNaN(parsed) ? defaultValue : parsed;
}
// ============= 字符串处理工具函数 =============
/**
 * 将字符串转换为驼峰命名
 */
function toCamelCase(str) {
    return str.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
}
/**
 * 将驼峰命名转换为短横线命名
 */
function toKebabCase(str) {
    return str.replace(/([A-Z])/g, '-$1').toLowerCase().replace(/^-/, '');
}
/**
 * 首字母大写
 */
function capitalize(str) {
    if (!str)
        return str;
    return str.charAt(0).toUpperCase() + str.slice(1);
}
/**
 * 截断字符串
 */
function truncate(str, length, suffix = '...') {
    if (str.length <= length)
        return str;
    return str.slice(0, length - suffix.length) + suffix;
}
// ============= 数组和对象操作工具函数 =============
/**
 * 深度克隆对象
 */
function deepClone(obj) {
    if (obj === null || typeof obj !== 'object')
        return obj;
    if (obj instanceof Date)
        return new Date(obj.getTime());
    if (obj instanceof Array)
        return obj.map(item => deepClone(item));
    if (typeof obj === 'object') {
        const cloned = {};
        Object.keys(obj).forEach(key => {
            cloned[key] = deepClone(obj[key]);
        });
        return cloned;
    }
    return obj;
}
/**
 * 深度合并对象
 */
function deepMerge(target, source) {
    const result = Object.assign({}, target);
    Object.keys(source).forEach(key => {
        const sourceValue = source[key];
        const targetValue = result[key];
        if (isRecord(sourceValue) && isRecord(targetValue)) {
            result[key] = deepMerge(targetValue, sourceValue);
        }
        else if (sourceValue !== undefined) {
            result[key] = sourceValue;
        }
    });
    return result;
}
/**
 * 数组去重
 */
function unique(array, keyFn) {
    if (!keyFn) {
        return Array.from(new Set(array));
    }
    const seen = new Set();
    return array.filter(item => {
        const key = keyFn(item);
        if (seen.has(key))
            return false;
        seen.add(key);
        return true;
    });
}
/**
 * 数组分组
 */
function groupBy(array, keyFn) {
    return array.reduce((groups, item) => {
        const key = keyFn(item);
        if (!groups[key])
            groups[key] = [];
        groups[key].push(item);
        return groups;
    }, {});
}
// ============= 缓存工具函数 =============
/**
 * 简单的内存缓存实现
 */
class SimpleCache {
    constructor(maxAge = 300000, maxSize = 100) {
        this.cache = new Map();
        this.maxAge = maxAge;
        this.maxSize = maxSize;
    }
    set(key, value) {
        // 清理过期缓存
        this.cleanup();
        // 如果缓存已满,删除最旧的条目
        if (this.cache.size >= this.maxSize) {
            const oldestKey = this.cache.keys().next().value;
            if (oldestKey !== undefined) {
                this.cache.delete(oldestKey);
            }
        }
        this.cache.set(key, { value, timestamp: Date.now() });
    }
    get(key) {
        const item = this.cache.get(key);
        if (!item)
            return undefined;
        if (Date.now() - item.timestamp > this.maxAge) {
            this.cache.delete(key);
            return undefined;
        }
        return item.value;
    }
    has(key) {
        return this.get(key) !== undefined;
    }
    delete(key) {
        return this.cache.delete(key);
    }
    clear() {
        this.cache.clear();
    }
    cleanup() {
        const now = Date.now();
        for (const [key, item] of this.cache.entries()) {
            if (now - item.timestamp > this.maxAge) {
                this.cache.delete(key);
            }
        }
    }
}
// ============= 性能工具函数 =============
/**
 * 防抖函数
 */
function debounce(fn, delay) {
    let timeoutId;
    return ((...args) => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn(...args), delay);
    });
}
/**
 * 节流函数
 */
function throttle(fn, delay) {
    let lastCall = 0;
    return ((...args) => {
        const now = Date.now();
        if (now - lastCall >= delay) {
            lastCall = now;
            fn(...args);
        }
    });
}
/**
 * 测量函数执行时间
 */
function measureTime(fn, name) {
    return ((...args) => {
        const start = performance.now();
        const result = fn(...args);
        const end = performance.now();
        if (name) {
            console.log(`${name} took ${end - start} milliseconds`);
        }
        return result;
    });
}
// ============= URL和查询参数工具函数 =============
/**
 * 解析查询字符串
 */
function parseQuery(search) {
    const params = {};
    const urlParams = new URLSearchParams(search);
    for (const [key, value] of urlParams.entries()) {
        params[key] = value;
    }
    return params;
}
/**
 * 构建查询字符串
 */
function buildQuery(params) {
    const searchParams = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
        if (value != null) {
            searchParams.append(key, String(value));
        }
    });
    return searchParams.toString();
}
/**
 * 更新URL查询参数
 */
function updateQuery(url, params) {
    const [base, search] = url.split('?');
    const currentParams = parseQuery(search || '');
    const newParams = Object.assign(Object.assign({}, currentParams), params);
    const queryString = buildQuery(newParams);
    return queryString ? `${base}?${queryString}` : base;
}
// ============= 错误处理工具函数 =============
/**
 * 安全地执行函数,捕获错误
 */
function safely(fn, fallback) {
    try {
        return fn();
    }
    catch (_a) {
        return fallback;
    }
}
/**
 * 安全地执行异步函数,捕获错误
 */
function safelyAsync(fn, fallback) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            return yield fn();
        }
        catch (_a) {
            return fallback;
        }
    });
}
function isLocalized(localized) {
    if (!localized)
        return false;
    if (typeof localized === 'string')
        return false;
    return isRecord(localized) && 'localizedId' in localized && localized.localizedId !== undefined;
}

/**
 * 国际化资源加载工具 - 对标 @gulibs/vite-plugin-i18n 优化版
 */
/**
 * 安全地导入虚拟模块
 */
function loadVirtualModule() {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            // 使用动态导入字符串,避免 TypeScript 模块解析错误
            const virtualModuleId = '~i18n-locales-loader';
            const virtualModule = yield import(/* @vite-ignore */ virtualModuleId);
            return {
                resources: virtualModule.resources || {},
                supportedLocales: virtualModule.supportedLocales || [],
                keys: virtualModule.keys || []
            };
        }
        catch (error) {
            // 虚拟模块不存在时返回 null
            return null;
        }
    });
}
/**
 * 虚拟模块加载器 - 优先使用 vite-plugin-i18n 生成的资源
 */
class ViteI18nLoader {
    constructor(config = {}) {
        this.config = Object.assign({ basePath: '/locales', extensions: ['.json', '.ts', '.js'], localePattern: 'directory', defaultLocale: 'en', cacheTime: 60 * 60 * 1000, cache: true, debug: false }, config);
        this.cache = new SimpleCache(this.config.cacheTime);
        this.initVirtualModule();
    }
    /**
     * 初始化虚拟模块资源
     */
    initVirtualModule() {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const virtualModule = yield loadVirtualModule();
                if (virtualModule) {
                    this.virtualModuleResources = virtualModule.resources;
                    this.virtualModuleKeys = virtualModule.keys;
                    this.virtualModuleSupportedLocales = virtualModule.supportedLocales;
                    if (this.config.debug) {
                        console.log('[I18nLoader] Loaded virtual module resources:', {
                            locales: ((_a = this.virtualModuleSupportedLocales) === null || _a === void 0 ? void 0 : _a.length) || 0,
                            keys: ((_b = this.virtualModuleKeys) === null || _b === void 0 ? void 0 : _b.length) || 0
                        });
                    }
                    // 预缓存所有虚拟模块资源
                    if (this.virtualModuleResources && this.config.cache) {
                        Object.entries(this.virtualModuleResources).forEach(([locale, resources]) => {
                            this.cache.set(locale, resources);
                        });
                    }
                }
            }
            catch (error) {
                if (this.config.debug) {
                    console.warn('[I18nLoader] Virtual module not available, falling back to dynamic loading:', error);
                }
            }
        });
    }
    /**
     * 加载指定语言的翻译资源
     */
    loadResources(locale) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            // 检查缓存
            if (this.config.cache && this.cache.has(locale)) {
                const cached = this.cache.get(locale);
                if (cached)
                    return cached;
            }
            // 优先使用虚拟模块资源
            if ((_a = this.virtualModuleResources) === null || _a === void 0 ? void 0 : _a[locale]) {
                const resources = this.virtualModuleResources[locale];
                if (this.config.cache) {
                    this.cache.set(locale, resources);
                }
                if (this.config.onLoad) {
                    this.config.onLoad(locale, resources);
                }
                return resources;
            }
            // 回退到动态加载
            return this.dynamicLoadResources(locale);
        });
    }
    /**
     * 动态加载资源(当虚拟模块不可用时的回退方案)
     */
    dynamicLoadResources(locale) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                let resources;
                if (this.config.fetchResources) {
                    // 使用自定义获取函数
                    const path = `${this.config.basePath}/${locale}${this.config.extensions[0]}`;
                    resources = yield this.config.fetchResources(locale, path);
                }
                else {
                    // 默认使用 fetch API
                    const extension = this.config.extensions[0];
                    const url = `${this.config.basePath}/${locale}${extension}`;
                    const response = yield fetch(url);
                    if (!response.ok) {
                        throw new Error(`Failed to load locale ${locale}: ${response.statusText}`);
                    }
                    resources = yield response.json();
                }
                // 缓存资源
                if (this.config.cache) {
                    this.cache.set(locale, resources);
                }
                // 触发加载回调
                if (this.config.onLoad) {
                    this.config.onLoad(locale, resources);
                }
                return resources;
            }
            catch (error) {
                // 触发错误回调
                if (this.config.onError && error instanceof Error) {
                    this.config.onError(locale, error);
                }
                if (this.config.debug) {
                    console.error(`[I18nLoader] Failed to load locale ${locale}:`, error);
                }
                return {};
            }
        });
    }
    /**
     * 预加载多个语言的翻译资源
     */
    preloadResources(locales) {
        return __awaiter(this, void 0, void 0, function* () {
            const resources = {};
            // 如果有虚拟模块资源,直接返回相关的资源
            if (this.virtualModuleResources) {
                locales.forEach(locale => {
                    if (this.virtualModuleResources[locale]) {
                        resources[locale] = this.virtualModuleResources[locale];
                    }
                });
                // 只加载虚拟模块中没有的语言
                const missingLocales = locales.filter(locale => !this.virtualModuleResources[locale]);
                if (missingLocales.length === 0) {
                    return resources;
                }
                locales = missingLocales;
            }
            // 并行加载缺失的资源
            yield Promise.all(locales.map((locale) => __awaiter(this, void 0, void 0, function* () {
                try {
                    resources[locale] = yield this.loadResources(locale);
                }
                catch (error) {
                    if (this.config.debug) {
                        console.error(`[I18nLoader] Failed to preload locale ${locale}:`, error);
                    }
                    resources[locale] = {};
                }
            })));
            return resources;
        });
    }
    /**
     * 清除资源缓存
     */
    clearCache(locale) {
        if (locale) {
            this.cache.delete(locale);
        }
        else {
            this.cache.clear();
        }
    }
    /**
     * 获取配置
     */
    getConfig() {
        return Object.assign({}, this.config);
    }
    /**
     * 获取所有可用的键(来自虚拟模块)
     */
    getAvailableKeys() {
        return this.virtualModuleKeys || [];
    }
    /**
     * 检查键是否存在
     */
    hasKey(key) {
        var _a;
        return ((_a = this.virtualModuleKeys) === null || _a === void 0 ? void 0 : _a.includes(key)) || false;
    }
    /**
     * 获取命名空间资源
     */
    getNamespaceResources(locale, namespace) {
        var _a;
        const localeResources = (_a = this.virtualModuleResources) === null || _a === void 0 ? void 0 : _a[locale];
        return localeResources === null || localeResources === void 0 ? void 0 : localeResources[namespace];
    }
    /**
     * 获取支持的语言列表
     */
    getSupportedLocales() {
        return this.virtualModuleSupportedLocales || [this.config.defaultLocale];
    }
    /**
     * 检查是否使用虚拟模块
     */
    isUsingVirtualModule() {
        return !!this.virtualModuleResources;
    }
}
/**
 * 创建优化的资源加载器
 */
function createI18nLoader(config = {}) {
    return new ViteI18nLoader(config);
}
/**
 * 创建兼容旧版的资源加载器
 * @deprecated 使用 createI18nLoader 替代
 */
function createResourceLoader(config = {}) {
    const loader = new ViteI18nLoader(config);
    return {
        // 完整的 I18nResourceLoader 接口
        loadResources: loader.loadResources.bind(loader),
        preloadResources: loader.preloadResources.bind(loader),
        clearCache: loader.clearCache.bind(loader),
        getConfig: loader.getConfig.bind(loader),
        getAvailableKeys: loader.getAvailableKeys.bind(loader),
        hasKey: loader.hasKey.bind(loader),
        getNamespaceResources: loader.getNamespaceResources.bind(loader),
        // 为了向后兼容,保留旧的方法名
        loadFromImportGlob: () => __awaiter(this, void 0, void 0, function* () {
            console.warn('loadFromImportGlob is deprecated, resources are now automatically loaded from virtual module');
            return {};
        })
    };
}

/**
 * 增强的国际化客户端类
 */
class I18nClient {
    constructor(config) {
        this.config = Object.assign({ fallbackToDefault: true, detectBrowserLanguage: false, interpolation: {
                prefix: '{',
                suffix: '}',
                escape: (value) => String(value)
            }, persistence: {
                enabled: false,
                key: 'user_locale',
                storage: 'localStorage'
            } }, config);
        // 创建资源加载器
        this.loader = createI18nLoader(this.config);
    }
    /** 获取资源加载器 */
    getLoader() {
        return this.loader;
    }
    /** 获取资源加载函数 */
    getLoadResources() {
        return this.loader.loadResources.bind(this.loader);
    }
    /** 预加载资源 */
    preloadResources(locales) {
        return __awaiter(this, void 0, void 0, function* () {
            const targetLocales = locales || this.config.supportedLocales || [this.config.defaultLocale];
            return this.loader.preloadResources(targetLocales);
        });
    }
    /** 清除缓存 */
    clearCache(locale) {
        this.loader.clearCache(locale);
    }
    /** 获取所有可用的键 */
    getAvailableKeys() {
        var _a, _b;
        return ((_b = (_a = this.loader).getAvailableKeys) === null || _b === void 0 ? void 0 : _b.call(_a)) || [];
    }
    /** 检查键是否存在 */
    hasKey(key) {
        var _a, _b;
        return ((_b = (_a = this.loader).hasKey) === null || _b === void 0 ? void 0 : _b.call(_a, key)) || false;
    }
    /** 获取命名空间资源 */
    getNamespaceResources(locale, namespace) {
        var _a, _b;
        return (_b = (_a = this.loader).getNamespaceResources) === null || _b === void 0 ? void 0 : _b.call(_a, locale, namespace);
    }
    /** 检查是否使用虚拟模块 */
    isUsingVirtualModule() {
        var _a, _b;
        return ((_b = (_a = this.loader).isUsingVirtualModule) === null || _b === void 0 ? void 0 : _b.call(_a)) || false;
    }
}
/**
 * 创建国际化客户端
 */
function createI18nClient(config) {
    return new I18nClient(config);
}
/**
 * 创建国际化上下文
 */
const I18nContext = React.createContext({
    locale: 'en',
    setLocale: () => __awaiter(void 0, void 0, void 0, function* () { }),
    t: (key) => key,
    td: (key, defaultValue) => defaultValue,
    isReady: false,
    availableLocales: ['en'],
    availableKeys: [],
    hasKey: () => false,
    getNamespaceResources: () => undefined,
    isUsingVirtualModule: false
});
/**
 * 内部存储资源
 */
const resourcesCache = {};
/**
 * 国际化提供者组件 - 优化版
 */
function I18nProvider({ children, client, defaultLocale = 'en', locales = ['en'], loadResources, resources = {} }) {
    // 处理客户端配置
    const i18nClient = React.useMemo(() => {
        if (client instanceof I18nClient) {
            return client;
        }
        else if (client) {
            return new I18nClient(client);
        }
        else {
            // 向后兼容的配置方式
            return new I18nClient({
                defaultLocale,
                supportedLocales: locales,
                resources,
                fetchResources: loadResources
            });
        }
    }, [client, defaultLocale, locales, loadResources, resources]);
    const loader = i18nClient.getLoader();
    const finalDefaultLocale = i18nClient.config.defaultLocale;
    const finalLocales = i18nClient.config.supportedLocales || [finalDefaultLocale];
    const [locale, setLocaleState] = React.useState(finalDefaultLocale);
    const [isReady, setIsReady] = React.useState(false);
    // 获取可用的键
    const availableKeys = React.useMemo(() => {
        return i18nClient.getAvailableKeys();
    }, [i18nClient]);
    // 初始化时合并静态资源到缓存并设置初始状态
    React.useEffect(() => {
        let hasInitialResources = false;
        // 合并静态资源到缓存
        if (i18nClient.config.resources) {
            Object.entries(i18nClient.config.resources).forEach(([lang, langResources]) => {
                if (!resourcesCache[lang]) {
                    resourcesCache[lang] = {};
                }
                resourcesCache[lang] = Object.assign(Object.assign({}, resourcesCache[lang]), langResources);
                if (lang === finalDefaultLocale) {
                    hasInitialResources = true;
                }
            });
        }
        // 检查虚拟模块是否提供了默认语言的资源
        if (!hasInitialResources && i18nClient.isUsingVirtualModule()) {
            const loader = i18nClient.getLoader();
            // 尝试从虚拟模块缓存中获取默认语言资源
            loader.loadResources(finalDefaultLocale)
                .then(resources => {
                if (resources && Object.keys(resources).length > 0) {
                    resourcesCache[finalDefaultLocale] = resources;
                    setIsReady(true);
                    if (i18nClient.config.debug) {
                        console.log('[I18nProvider] Loaded default locale from virtual module:', finalDefaultLocale);
                    }
                }
            })
                .catch(error => {
                console.warn('[I18nProvider] Failed to load default locale resources:', error);
                setIsReady(true); // 即使失败也要设置为就绪
            });
        }
        else {
            setIsReady(true);
        }
        if (i18nClient.config.debug) {
            console.log('[I18nProvider] Initialized with config:', {
                defaultLocale: finalDefaultLocale,
                supportedLocales: finalLocales,
                hasStaticResources: hasInitialResources,
                isUsingVirtualModule: i18nClient.isUsingVirtualModule()
            });
        }
    }, [finalDefaultLocale, finalLocales, i18nClient]);
    // 设置语言并加载资源
    const setLocale = React.useCallback((newLocale) => __awaiter(this, void 0, void 0, function* () {
        var _a;
        if (!finalLocales.includes(newLocale)) {
            console.warn(`[I18nProvider] Locale ${newLocale} is not in the available locales list.`);
            return;
        }
        setIsReady(false);
        try {
            // 加载资源
            if (!resourcesCache[newLocale]) {
                const newResources = yield loader.loadResources(newLocale);
                resourcesCache[newLocale] = newResources;
            }
            setLocaleState(newLocale);
            // 更新 HTML lang 属性
            if (typeof document !== 'undefined') {
                document.documentElement.lang = newLocale;
            }
            // 持久化用户语言选择
            if (((_a = i18nClient.config.persistence) === null || _a === void 0 ? void 0 : _a.enabled) && typeof window !== 'undefined') {
                try {
                    const storage = i18nClient.config.persistence.storage === 'sessionStorage'
                        ? sessionStorage
                        : localStorage;
                    const key = i18nClient.config.persistence.key || 'user_locale';
                    storage.setItem(key, newLocale);
                }
                catch (error) {
                    // 存储失败时不阻塞程序
                    console.warn('[I18nProvider] Failed to persist locale:', error);
                }
            }
        }
        catch (error) {
            console.error(`[I18nProvider] Failed to load resources for locale ${newLocale}:`, error);
        }
        finally {
            setIsReady(true);
        }
    }), [finalLocales, loader, i18nClient.config.persistence]);
    // 解析嵌套键 'user.profile.title' => resources.user.profile.title
    const resolveNestedKey = React.useCallback((obj, path) => {
        // 添加类型检查,确保 path 是字符串
        if (typeof path !== 'string') {
            console.warn('[I18nProvider] resolveNestedKey received non-string path:', path);
            return '';
        }
        const keys = path.split('.');
        let current = obj;
        for (const key of keys) {
            if (current === undefined || current === null)
                return path;
            current = current[key];
        }
        return typeof current === 'string' ? current : path;
    }, []);
    // 插入参数 'Hello, {name}!' + { name: 'World' } => 'Hello, World!'
    const interpolate = React.useCallback((text, params) => {
        if (!params)
            return text;
        const { prefix = '{', suffix = '}', escape = (v) => String(v) } = i18nClient.config.interpolation || {};
        const pattern = new RegExp(`\\${prefix}(\\w+)\\${suffix}`, 'g');
        return text.replace(pattern, (_, key) => {
            return params[key] !== undefined ? escape(params[key]) : `${prefix}${key}${suffix}`;
        });
    }, [i18nClient.config.interpolation]);
    // 增强的翻译函数
    const t = React.useCallback((key, params) => {
        // 添加类型检查,确保 key 是字符串
        if (typeof key !== 'string') {
            if (i18nClient.config.debug) {
                console.warn('[I18nProvider] Translation key is not a string:', key);
            }
            return '';
        }
        if (!key) {
            if (i18nClient.config.debug) {
                console.warn('[I18nProvider] Empty translation key provided');
            }
            return '';
        }
        // 处理键前缀
        const fullKey = i18nClient.config.keyPrefix ? `${i18nClient.config.keyPrefix}.${key}` : key;
        const currentResources = resourcesCache[locale] || {};
        let value = resolveNestedKey(currentResources, fullKey);
        // 调试信息
        if (i18nClient.config.debug) {
            console.log('[I18nProvider] Translation lookup:', {
                key,
                fullKey,
                locale,
                hasResources: Object.keys(currentResources).length > 0,
                found: value !== fullKey
            });
        }
        // 如果找不到翻译且启用了回退,尝试从默认语言获取
        if (value === fullKey &&
            i18nClient.config.fallbackToDefault &&
            locale !== finalDefaultLocale) {
            const defaultResources = resourcesCache[finalDefaultLocale] || {};
            const defaultValue = resolveNestedKey(defaultResources, fullKey);
            if (defaultValue !== fullKey) {
                value = defaultValue;
                if (i18nClient.config.debug) {
                    console.log('[I18nProvider] Used fallback translation:', {
                        key: fullKey,
                        fromLocale: finalDefaultLocale
                    });
                }
            }
        }
        // 如果仍然找不到,返回原始键名(不包含前缀)
        if (value === fullKey) {
            value = key;
            if (i18nClient.config.debug) {
                console.warn('[I18nProvider] Translation not found:', {
                    key,
                    fullKey,
                    locale,
                    availableKeys: Object.keys(currentResources)
                });
            }
        }
        return interpolate(value, params);
    }, [locale, finalDefaultLocale, i18nClient.config, resolveNestedKey, interpolate]);
    // 带默认值的翻译函数
    const td = React.useCallback((key, defaultValue, params) => {
        // 添加类型检查,确保 key 是字符串
        if (typeof key !== 'string') {
            if (i18nClient.config.debug) {
                console.warn('[I18nProvider] Translation key is not a string:', key);
            }
            return defaultValue;
        }
        if (!key) {
            if (i18nClient.config.debug) {
                console.warn('[I18nProvider] Empty translation key provided');
            }
            return defaultValue;
        }
        // 处理键前缀
        const fullKey = i18nClient.config.keyPrefix ? `${i18nClient.config.keyPrefix}.${key}` : key;
        const currentResources = resourcesCache[locale] || {};
        let value = resolveNestedKey(currentResources, fullKey);
        // 调试信息
        if (i18nClient.config.debug) {
            console.log('[I18nProvider] Translation lookup (with default):', {
                key,
                fullKey,
                locale,
                defaultValue,
                hasResources: Object.keys(currentResources).length > 0,
                found: value !== fullKey
            });
        }
        // 如果找不到翻译且启用了回退,尝试从默认语言获取
        if (value === fullKey &&
            i18nClient.config.fallbackToDefault &&
            locale !== finalDefaultLocale) {
            const defaultResources = resourcesCache[finalDefaultLocale] || {};
            const defaultTranslation = resolveNestedKey(defaultResources, fullKey);
            if (defaultTranslation !== fullKey) {
                value = defaultTranslation;
                if (i18nClient.config.debug) {
                    console.log('[I18nProvider] Used fallback translation (with default):', {
                        key: fullKey,
                        fromLocale: finalDefaultLocale
                    });
                }
            }
        }
        // 如果仍然找不到翻译,返回提供的默认值
        if (value === fullKey) {
            value = defaultValue;
            if (i18nClient.config.debug) {
                console.log('[I18nProvider] Using provided default value:', {
                    key,
                    fullKey,
                    locale,
                    defaultValue
                });
            }
        }
        return interpolate(value, params);
    }, [locale, finalDefaultLocale, i18nClient.config, resolveNestedKey, interpolate]);
    // 检查键是否存在
    const hasKey = React.useCallback((key) => {
        return i18nClient.hasKey(key);
    }, [i18nClient]);
    // 获取命名空间资源
    const getNamespaceResources = React.useCallback((namespace) => {
        return i18nClient.getNamespaceResources(locale, namespace);
    }, [i18nClient, locale]);
    // 组件挂载时恢复用户语言选择和浏览器语言检测
    React.useEffect(() => {
        var _a;
        let targetLocale = finalDefaultLocale; // 始终从默认语言开始
        let shouldChangeLocale = false;
        try {
            // 只有在明确启用持久化时才尝试恢复
            if (((_a = i18nClient.config.persistence) === null || _a === void 0 ? void 0 : _a.enabled) && typeof window !== 'undefined') {
                const storage = i18nClient.config.persistence.storage === 'sessionStorage'
                    ? sessionStorage
                    : localStorage;
                const key = i18nClient.config.persistence.key || 'user_locale';
                const savedLocale = storage.getItem(key);
                if (savedLocale && finalLocales.includes(savedLocale)) {
                    targetLocale = savedLocale;
                    shouldChangeLocale = true;
                    if (i18nClient.config.debug) {
                        console.log('[I18nProvider] Restored saved locale:', savedLocale);
                    }
                }
            }
            // 只有在没有保存的语言且明确启用浏览器检测时才使用浏览器语言
            if (!shouldChangeLocale &&
                i18nClient.config.detectBrowserLanguage &&
                typeof navigator !== 'undefined') {
                const browserLocale = navigator.language.split('-')[0];
                if (finalLocales.includes(browserLocale) && browserLocale !== finalDefaultLocale) {
                    targetLocale = browserLocale;
                    shouldChangeLocale = true;
                    if (i18nClient.config.debug) {
                        console.log('[I18nProvider] Detected browser locale:', browserLocale);
                    }
                }
            }
        }
        catch (error) {
            console.warn('[I18nProvider] Failed to detect locale:', error);
        }
        // 只有在确实需要改变语言时才调用 setLocale
        if (targetLocale !== locale) {
            if (i18nClient.config.debug) {
                console.log('[I18nProvider] Setting initial locale:', targetLocale);
            }
            setLocale(targetLocale);
        }
    }, []); // 空依赖数组,只在组件挂载时执行一次
    return (jsxRuntime.jsx(I18nContext.Provider, Object.assign({ value: {
            locale,
            setLocale,
            t,
            td,
            isReady,
            availableLocales: finalLocales,
            availableKeys,
            hasKey,
            getNamespaceResources,
            isUsingVirtualModule: i18nClient.isUsingVirtualModule()
        } }, { children: children })));
}
/**
 * 使用国际化上下文的 Hook
 */
function useI18n() {
    const context = React.useContext(I18nContext);
    if (!context) {
        throw new Error('useI18n must be used within an I18nProvider');
    }
    return context;
}
/**
 * 用于翻译本地化对象的 Hook - 优化版
 */
function useTranslateLocalized() {
    const { t } = useI18n();
    return React.useCallback((localized) => {
        return translateLocalized(localized, t);
    }, [t]);
}
/**
 * 转换本地化对象为字符串 - 优化版
 */
function translateLocalized(localized, translate) {
    if (!localized)
        return '';
    // 如果是字符串,直接翻译
    if (typeof localized === 'string') {
        return translate(localized);
    }
    // 如果是 Localized 对象
    if (localized && typeof localized === 'object' && 'localizedId' in localized) {
        const localizedId = localized.localizedId;
        // 确保 localizedId 是字符串
        if (typeof localizedId === 'string') {
            return translate(localizedId);
        }
        else {
            console.warn('[translateLocalized] localizedId is not a string:', localizedId, 'in object:', localized);
            return '';
        }
    }
    // 其他情况返回原值
    return localized;
}
/**
 * 创建本地化对象
 */
function localize(key) {
    return { localizedId: key };
}
/**
 * 使用国际化键验证 Hook
 */
function useI18nKeyValidator() {
    const { hasKey, availableKeys } = useI18n();
    return {
        /** 检查键是否存在 */
        hasKey,
        /** 获取所有可用键 */
        getAvailableKeys: () => availableKeys,
        /** 验证键并返回建议 */
        validateKey: (key) => {
            if (hasKey(key)) {
                return { valid: true, suggestions: [] };
            }
            // 提供相似键的建议
            const suggestions = availableKeys
                .filter(availableKey => availableKey.toLowerCase().includes(key.toLowerCase()) ||
                key.toLowerCase().includes(availableKey.toLowerCase()))
                .slice(0, 5);
            return { valid: false, suggestions };
        }
    };
}
/**
 * 使用命名空间 Hook
 */
function useI18nNamespace(namespace) {
    const { getNamespaceResources, t, locale } = useI18n();
    const namespaceResources = React.useMemo(() => {
        return getNamespaceResources(namespace);
    }, [getNamespaceResources, namespace]);
    const tNamespace = React.useCallback((key, params) => {
        const namespacedKey = `${namespace}.${key}`;
        return t(namespacedKey, params);
    }, [t, namespace]);
    return {
        /** 命名空间内的翻译函数 */
        t: tNamespace,
        /** 获取命名空间资源 */
        resources: namespaceResources,
        /** 当前语言 */
        locale,
        /** 检查命名空间是否存在 */
        exists: !!namespaceResources
    };
}
/**
 * 使用复数形式 Hook
 */
function usePlural() {
    const { t } = useI18n();
    return React.useCallback((key, count, params) => {
        const pluralKey = count === 1 ? `${key}.one` : `${key}.other`;
        return t(pluralKey, Object.assign({ count }, params));
    }, [t]);
}

/**
 * 基于 react-storage 的 useStorage hook
 */
function useStorage(key, defaultValue, options = {}) {
    const { storage = 'local' } = options;
    // 创建存储实例
    const storageInstance = React.useMemo(() => {
        const instance = reactStorage.ReactStorage.getInstance();
        instance.type = storage === 'session' ? 'sessionStorage' : 'localStorage';
        return instance;
    }, [storage]);
    // 获取初始值
    const getStoredValue = React.useCallback(() => {
        try {
            const stored = storageInstance.get(key);
            return stored !== null ? stored : defaultValue;
        }
        catch (error) {
            console.warn(`Error reading from storage (${key}):`, error);
            return defaultValue;
        }
    }, [storageInstance, key, defaultValue]);
    const [value, setValue] = React.useState(getStoredValue);
    // 设置值
    const setStoredValue = React.useCallback((newValue) => {
        try {
            setValue(newValue);
            storageInstance.set(key, newValue);
        }
        catch (error) {
            console.warn(`Error writing to storage (${key}):`, error);
        }
    }, [storageInstance, key]);
    // 移除值
    const removeValue = React.useCallback(() => {
        try {
            setValue(defaultValue);
            storageInstance.remove(key);
        }
        catch (error) {
            console.warn(`Error removing from storage (${key}):`, error);
        }
    }, [storageInstance, key, defaultValue]);
    // 监听存储变化(跨标签页同步)
    React.useEffect(() => {
        const handleStorageChange = (e) => {
            if (e.key === key && e.storageArea === (storage === 'session' ? sessionStorage : localStorage)) {
                try {
                    const newValue = e.newValue ? JSON.parse(e.newValue) : defaultValue;
                    setValue(newValue);
                }
                catch (error) {
                    console.warn(`Error parsing storage change for ${key}:`, error);
                }
            }
        };
        window.addEventListener('storage', handleStorageChange);
        return () => window.removeEventListener('storage', handleStorageChange);
    }, [key, storage, defaultValue]);
    return [value, setStoredValue, removeValue];
}
/**
 * 用户状态管理 Hook
 */
function useUser(options = {}) {
    const { storagePrefix = 'auth', useSessionStorage = false, fetchUser, loginApi, refreshTokenApi, autoRefreshInterval = 0, isTokenExpired, isRefreshTokenExpired, fieldMapping, transformers } = options;
    // 默认字段映射
    const fields = Object.assign({ userField: 'user', tokenField: 'token', refreshTokenField: 'refreshToken' }, fieldMapping);
    // 持久化存储
    const [user, setUser, removeUser] = useStorage(`${storagePrefix}_user`, null, { storage: useSessionStorage ? 'session' : 'local' });
    const [token, setTokenStorage, removeToken] = useStorage(`${storagePrefix}_token`, null, { storage: useSessionStorage ? 'session' : 'local' });
    const [refreshTokenValue, setRefreshTokenStorage, removeRefreshToken] = useStorage(`${storagePrefix}_refresh_token`, null, { storage: useSessionStorage ? 'session' : 'local' });
    // 本地状态
    const [isLoading, setIsLoading] = React.useState(false);
    const [error, setError] = React.useState(null);
    // 计算认证状态
    const isAuthenticated = React.useMemo(() => {
        if (!token || !user)
            return false;
        // 检查token是否过期
        if (isTokenExpired && isTokenExpired(token)) {
            return false;
        }
        return true;
    }, [token, user, isTokenExpired]);
    /**
     * 数据转换
     */
    const transformUserData = React.useCallback((userData, direction) => {
        if (direction === 'store' && (transformers === null || transformers === void 0 ? void 0 : transformers.beforeStore)) {
            return transformers.beforeStore(userData);
        }
        if (direction === 'restore' && (transformers === null || transformers === void 0 ? void 0 : transformers.afterRestore)) {
            return transformers.afterRestore(userData);
        }
        return userData;
    }, [transformers]);
    /**
     * 解析API响应
     */
    const parseApiResponse = React.useCallback((response) => {
        const userData = response[fields.userField];
        const token = response[fields.tokenField];
        const refreshToken = response[fields.refreshTokenField];
        return {
            user: userData ? ((transformers === null || transformers === void 0 ? void 0 : transformers.transformUser) ? transformers.transformUser(userData) : userData) : null,
            token: token || null,
            refreshToken: refreshToken || null
        };
    }, [fields, transformers]);
    /**
     * 存储用户数据
     */
    const storeUserData = React.useCallback((userData) => {
        const transformedData = transformUserData(userData, 'store');
        setUser(transformedData);
    }, [setUser, transformUserData]);
    /**
     * 读取用户数据
     */
    const getUserData = React.useMemo(() => {
        if (!user)
            return null;
        return transformUserData(user, 'restore');
    }, [user, transformUserData]);
    /**
     * 设置Token
     */
    const setToken = React.useCallback((newToken) => {
        setTokenStorage(newToken);
    }, [setTokenStorage]);
    /**
     * 设置RefreshToken
     */
    const setRefreshToken = React.useCallback((newRefreshToken) => {
        setRefreshTokenStorage(newRefreshToken);
    }, [setRefreshTokenStorage]);
    /**
     * 登录
     */
    const login = React.useCallback((credentials) => __awaiter(this, void 0, void 0, function* () {
        if (!loginApi) {
            throw new Error('Login API function not provided');
        }
        setIsLoading(true);
        setError(null);
        try {
            // 转换凭据
            const transformedCredentials = (transformers === null || transformers === void 0 ? void 0 : transformers.transformCredentials)
                ? transformers.transformCredentials(credentials)
                : credentials;
            const response = yield loginApi(transformedCredentials);
            // 解析响应
            const parsed = parseApiResponse(response);
            // 保存数据
            if (parsed.user) {
                storeUserData(parsed.user);
            }
            if (parsed.token) {
                setTokenStorage(parsed.token);
            }
            if (parsed.refreshToken) {
                setRefreshTokenStorage(parsed.refreshToken);
            }
        }
        catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'Login failed';
            setError(errorMessage);
            throw err;
        }
        finally {
            setIsLoading(false);
        }
    }), [loginApi, transformers, parseApiResponse, storeUserData, setTokenStorage, setRefreshTokenStorage]);
    /**
     * 登出
     */
    const logout = React.useCallback(() => {
        // 清除存储的数据
        removeUser();
        removeToken();
        removeRefreshToken();
        // 重置状态
        setError(null);
        setIsLoading(false);
    }, [removeUser, removeToken, removeRefreshToken]);
    /**
     * 刷新用户信息
     */
    const refreshUser = React.useCallback(() => __awaiter(this, void 0, void 0, function* () {
        if (!token || !fetchUser) {
            return;
        }
        setIsLoading(true);
        setError(null);
        try {
            const updatedUser = yield fetchUser(token);
            storeUserData(updatedUser);
        }
        catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'Failed to refresh user';
            setError(errorMessage);
            // token可能过期了,清除状态
            if (err instanceof Error && err.message.includes('401')) {
                logout();
            }
        }
        finally {
            setIsLoading(false);
        }
    }), [token, fetchUser, storeUserData, logout]);
    /**
     * 刷新Token
     */
    const refreshTokenAction = React.useCallback(() => __awaiter(this, void 0, void 0, function* () {
        if (!refreshTokenValue || !refreshTokenApi) {
            throw new Error('Refresh token or refresh API not available');
        }
        // 检查refreshToken是否过期
        if (isRefreshTokenExpired && isRefreshTokenExpired(refreshTokenValue)) {
            logout();
            throw new Error('Refresh token expired');
        }
        setIsLoading(true);
        setError(null);
        try {
            const response = yield refreshTokenApi(refreshTokenValue);
            // 解析响应
            const parsed = parseApiResponse(response);
            // 更新token
            if (parsed.token) {
                setTokenStorage(parsed.token);
            }
            // 更新refreshToken
            if (parsed.refreshToken) {
                setRefreshTokenStorage(parsed.refreshToken);
            }
            // 更新用户信息
            if (parsed.user) {
                storeUserData(parsed.user);
            }
        }
        catch (err) {
            const errorMessage = err instanceof Error ? err.message : 'Failed to refresh token';
            setError(errorMessage);
            // 刷新失败,清除认证状态
            logout();
            throw err;
        }
        finally {
            setIsLoading(false);
        }
    }), [refreshTokenValue, refreshTokenApi, isRefreshTokenExpired, logout, parseApiResponse, setTokenStorage, setRefreshTokenStorage, storeUserData]);
    /**
     * 更新用户信息
     */
    const updateUser = React.useCallback((userData) => {
        if (!getUserData)
            return;
        const updatedUser = Object.assign(Object.assign({}, getUserData), userData);
        storeUserData(updatedUser);
    }, [getUserData, storeUserData]);
    /**
     * 清除错误
     */
    const clearError = React.useCallback(() => {
        setError(null);
    }, []);
    // 自动刷新用户信息
    React.useEffect(() => {
        if (autoRefreshInterval > 0 && isAuthenticated && fetchUser) {
            const interval = setInterval(() => {
                refreshUser();
            }, autoRefreshInterval);
            return () => clearInterval(interval);
        }
    }, [autoRefreshInterval, isAuthenticated, fetchUser, refreshUser]);
    // 检查token过期,自动刷新
    React.useEffect(() => {
        if (token && isTokenExpired && isTokenExpired(token)) {
            if (refreshTokenValue && refreshTokenApi) {
                // 尝试自动刷新token
                refreshTokenAction().catch(() => {
                    // 刷新失败,logout已处理
                });
            }
            else {
                logout();
            }
        }
    }, [token, isTokenExpired, refreshTokenValue, refreshTokenApi, refreshTokenAction, logout]);
    return {
        // 状态
        user: getUserData,
        token,
        refreshToken: refreshTokenValue,
        isAuthenticated,
        isLoading,
        error,
        // 操作
        login,
        logout,
        refreshUser,
        refreshTokenAction,
        updateUser,
        setToken,
        setRefreshToken,
        clearError
    };
}
/**
 * 只读的用户状态 Hook
 */
function useUserState(storagePrefix = 'auth', useSessionStorage = false) {
    const [user] = useStorage(`${storagePrefix}_user`, null, { storage: useSessionStorage ? 'session' : 'local' });
    const [token] = useStorage(`${storagePrefix}_token`, null, { storage: useSessionStorage ? 'session' : 'local' });
    const [refreshToken] = useStorage(`${storagePrefix}_refresh_token`, null, { storage: useSessionStorage ? 'session' : 'local' });
    const isAuthenticated = React.useMemo(() => {
        return !!(token && user);
    }, [token, user]);
    return {
        user,
        token,
        refreshToken,
        isAuthenticated
    };
}
/**
 * Token管理 Hook
 */
function useAuthToken(storagePrefix = 'auth', useSessionStorage = false) {
    const [token, setTokenStorage, removeToken] = useStorage(`${storagePrefix}_token`, null, { storage: useSessionStorage ? 'session' : 'local' });
    const [refreshToken, setRefreshTokenStorage, removeRefreshToken] = useStorage(`${storagePrefix}_refresh_token`, null, { storage: useSessionStorage ? 'session' : 'local' });
    const setToken = React.useCallback((newToken) => {
        setTokenStorage(newToken);
    }, [setTokenStorage]);
    const setRefreshToken = React.useCallback((newRefreshToken) => {
        setRefreshTokenStorage(newRefreshToken);
    }, [setRefreshTokenStorage]);
    const clearToken = React.useCallback(() => {
        removeToken();
    }, [removeToken]);
    const clearRefreshToken = React.useCallback(() => {
        removeRefreshToken();
    }, [removeRefreshToken]);
    const clearAllTokens = React.useCallback(() => {
        removeToken();
        removeRefreshToken();
    }, [removeToken, removeRefreshToken]);
    return {
        token,
        refreshToken,
        setToken,
        setRefreshToken,
        clearToken,
        clearRefreshToken,
        clearAllTokens,
        hasToken: !!token,
        hasRefreshToken: !!refreshToken
    };
}
/**
 * 面包屑 Hook(支持国际化和路由匹配)
 */
function useBreadcrumbs(handle, options = {}) {
    const location = reactRouter.useLocation();
    const matches = reactRouter.useMatches();
    const { enableI18n = false, includeMatches = false } = options;
    // 只有在启用国际化时才调用 useI18n
    const i18n = enableI18n ? useI18n() : null;
    const breadcrumbs = [];
    if (includeMatches) {
        // 基于路由匹配构建面包屑
        matches.forEach((match) => {
            var _a, _b;
            if (match.handle && isRecord(match.handle)) {
                const matchHandle = match.handle;
                if (matchHandle.breadcrumbs) {
                    const breadcrumb = {
                        href: matchHandle.breadcrumbs.href || match.pathname,
                        className: matchHandle.breadcrumbs.className,
                        isDisabled: matchHandle.breadcrumbs.isDisabled,
                        isCurrent: match.pathname === location.pathname,
                        startContent: matchHandle.breadcrumbs.startContent,
                        endContent: matchHandle.breadcrumbs.endContent,
                        children: 'Page'
                    };
                    // 如果启用国际化,翻译标题
                    if (enableI18n && i18n && ((_a = matchHandle.meta) === null || _a === void 0 ? void 0 : _a.title)) {
                        const translated = translateLocalized(matchHandle.meta.title, i18n.t);
                        breadcrumb.children = translated;
                    }
                    else if (((_b = matchHandle.meta) === null || _b === void 0 ? void 0 : _b.title) && typeof matchHandle.meta.title === 'string') {
                        breadcrumb.children = matchHandle.meta.title;
                    }
                    breadcrumbs.push(breadcrumb);
                }
            }
        });
    }
    else if (handle === null || handle === void 0 ? void 0 : handle.breadcrumbs) {
        // 使用传入的handle构建单个面包屑
        const breadcrumbConfig = handle.breadcrumbs;
        const baseBreadcrumb = {
            href: breadcrumbConfig.href || location.pathname,
            className: breadcrumbConfig.className,
            isDisabled: breadcrumbConfig.isDisabled,
            isCurrent: breadcrumbConfig.isCurrent,
            startContent: breadcrumbConfig.startContent,
            endContent: breadcrumbConfig.endContent,
            children: 'Current Page'
        };
        // 如果启用国际化且有翻译函数,则翻译children
        if (enableI18n && i18n && typeof baseBreadcrumb.children === 'string') {
            const translated = translateLocalized(baseBreadcrumb.children, i18n.t);
            baseBreadcrumb.children = translated;
        }
        breadcrumbs.push(baseBreadcrumb);
    }
    return breadcrumbs;
}
/**
 * 页面元数据 Hook(支持国际化)
 */
function usePageMeta(handle, options = {}) {
    const { enableI18n = false } = options;
    const i18n = enableI18n ? useI18n() : null;
    const meta = handle === null || handle === void 0 ? void 0 : handle.meta;
    if (!meta)
        return undefined;
    // 如果启用国际化且有翻译函数,则翻译标题和描述
    if (enableI18n && i18n) {
        return {
            title: meta.title ? translateLocalized(meta.title, i18n.t) : undefined,
            description: meta.description ? String(translateLocalized(meta.description, i18n.t)) : undefined
        };
    }
    return meta;
}
/**
 * 布局设置 Hook
 */
function useLayoutSettings(handle) {
    return handle === null || handle === void 0 ? void 0 : handle.layoutSettings;
}
/**
 * VGrove 布局设置 Hook
 * 提供更便捷的布局配置访问和默认值处理
 */
function useVGroveLayoutSettings(handle, defaults) {
    const layoutSettings = useLayoutSettings(handle);
    const defaultConfig = Object.assign({ sidebar: true, header: true, footer: false, navbar: {
            sticky: true,
            transparent: false,
            height: '64px'
        }, sidebarConfig: {
            width: '280px',
            collapsible: true,
            defaultCollapsed: false
        }, footerConfig: {
            sticky: false,
            height: 'auto'
        }, theme: {
            mode: 'light'
        }, responsive: {
            hideSidebarOnMobile: true,
            mobileBreakpoint: '768px'
        } }, defaults);
    return React.useMemo(() => {
        if (!layoutSettings)
            return defaultConfig;
        // 使用 lodash merge 进行深度合并:先 defaultConfig,再 layoutSettings
        return _.merge({}, defaultConfig, layoutSettings);
    }, [layoutSettings, defaultConfig]);
}
/**
 * 获取布局配置的特定部分
 */
function useLayoutConfig(section, handle) {
    const layoutSettings = useVGroveLayoutSettings(handle);
    return layoutSettings[section];
}
/**
 * 检查布局功能是否启用
 */
function useLayoutFeatures(handle) {
    const layoutSettings = useVGroveLayoutSettings(handle);
    return React.useMemo(() => {
        var _a, _b, _c, _d;
        return ({
            hasSidebar: !!layoutSettings.sidebar,
            hasHeader: !!layoutSettings.header,
            hasFooter: !!layoutSettings.footer,
            isSidebarCollapsible: !!((_a = layoutSettings.sidebarConfig) === null || _a === void 0 ? void 0 : _a.collapsible),
            isNavbarSticky: !!((_b = layoutSettings.navbar) === null || _b === void 0 ? void 0 : _b.sticky),
            isFooterSticky: !!((_c = layoutSettings.footerConfig) === null || _c === void 0 ? void 0 : _c.sticky),
            shouldHideSidebarOnMobile: !!((_d = layoutSettings.responsive) === null || _d === void 0 ? void 0 : _d.hideSidebarOnMobile)
        });
    }, [layoutSettings]);
}
/**
 * 页面配置 Hook(支持国际化)
 */
function usePageConfig(handle, options = {}) {
    const { enableI18n = false } = options;
    const breadcrumbs = useBreadcrumbs(handle, { enableI18n });
    const meta = usePageMeta(handle, { enableI18n });
    const layoutSettings = useLayoutSettings(handle);
    return {
        breadcrumbs,
        meta,
        layoutSettings,
        handle
    };
}
/**
 * 完整的页面配置 Hook(包含所有元数据,支持国际化)
 */
function useI18nPageConfig(handle) {
    const i18n = useI18n();
    const translatedMeta = usePageMeta(handle, { enableI18n: true });
    const translatedBreadcrumbs = useBreadcrumbs(handle, { enableI18n: true });
    const layoutSettings = useLayoutSettings(handle);
    // 翻译页面头部元数据
    const translatedHeaderMeta = React.useMemo(() => {
        const pageMeta = handle === null || handle === void 0 ? void 0 : handle.pageMeta;
        if (!pageMeta)
            return undefined;
        return {
            title: pageMeta.title ? translateLocalized(pageMeta.title, i18n.t) : undefined,
            description: pageMeta.description ? translateLocalized(pageMeta.description, i18n.t) : undefined
        };
    }, [handle === null || handle === void 0 ? void 0 : handle.pageMeta, i18n.t]);
    return {
        meta: translatedMeta,
        pageMeta: translatedHeaderMeta,
        breadcrumbs: translatedBreadcrumbs,
        layoutSettings,
        handle
    };
}
/**
 * 使用动态页面标题 Hook
 */
function useDocumentTitle(handle, suffix, options = {}) {
    const { enableI18n = false } = options;
    const meta = usePageMeta(handle, { enableI18n });
    return React.useCallback(() => {
        if (meta === null || meta === void 0 ? void 0 : meta.title) {
            const title = typeof meta.title === 'string' ? meta.title : String(meta.title);
            document.title = suffix ? `${title} | ${suffix}` : title;
        }
    }, [meta, suffix]);
}
/**
 * 获取页面handle(支持继承)
 */
function useHandle() {
    const matches = reactRouter.useMatches();
    const [meta, setMeta] = React.useState({});
    const [pageMeta, setPageMeta] = React.useState({});
    const [layoutSettings, setLayoutSettings] = React.useState({});
    const [extras, setExtras] = React.useState("");
    const [breadcrumbs, setBreadcrumbs] = React.useState();
    // 缓存过滤结果
    const filterMatches = React.useMemo(() => {
        return matches.filter((obj) => {
            return obj.handle !== undefined;
        });
    }, [matches]);
    React.useEffect(() => {
        // 从根路由开始合并所有的handle配置
        let mergedLayoutSettings = {};
        let currentMeta = {};
        let currentPageMeta = {};
        let currentExtras = "";
        let currentBreadcrumbs;
        // 遍历所有matches,从根到叶子
        filterMatches.forEach((match) => {
            if (match && isRecord(match.handle)) {
                const handle = match.handle;
                // 深度合并layoutSettings(子路由覆盖父路由)
                if (handle.layoutSettings) {
                    mergedLayoutSettings = _.merge({}, mergedLayoutSettings, handle.layoutSettings);
                }
                // 更新其他属性(最后一个有值的为准)
                if (handle.meta) {
                    currentMeta = handle.meta;
                }
                if (handle.pageMeta) {
                    currentPageMeta = handle.pageMeta;
                }
                if (handle.extras !== undefined) {
                    currentExtras = handle.extras;
                }
                if (handle.breadcrumbs) {
                    currentBreadcrumbs = handle.breadcrumbs;
                }
            }
        });
        // 设置状态
        setMeta(currentMeta);
        setPageMeta(currentPageMeta);
        setLayoutSettings(mergedLayoutSettings);
        setExtras(currentExtras);
        setBreadcrumbs(currentBreadcrumbs);
    }, [filterMatches]);
    return {
        meta,
        pageMeta,
        extras,
        layoutSettings,
        breadcrumbs,
        matches: filterMatches
    };
}

/**
 * 客户端运行时执行器
 * 处理守卫、中间件和认证的执行逻辑
 */
// 结果缓存提高性能
const executionCache = new PerformanceCache(50);
const guardCache = new PerformanceCache(100);
/**
 * 运行时执行器
 */
class RuntimeExecutor {
    /**
     * 执行认证守卫
     */
    static executeAuth(authConfig, context) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            if (!(authConfig === null || authConfig === void 0 ? void 0 : authConfig.check)) {
                return { success: true, allowed: true };
            }
            // 创建缓存键
            const cacheKey = `auth_${context.path}_${((_a = context.user) === null || _a === void 0 ? void 0 : _a.id) || 'anonymous'}`;
            // 检查缓存
            const cached = executionCache.get(cacheKey);
            if (cached) {
                return cached;
            }
            globalPerformanceTracker.startTimer('auth_execution');
            try {
                const authContext = {
                    path: context.path,
                    params: context.params,
                    query: context.query,
                    user: context.user,
                    permissions: context.permissions,
                    roles: context.roles,
                    data: context.data
                };
                const isAuthenticated = yield authConfig.check(authContext);
                const result = {
                    success: true,
                    allowed: !!isAuthenticated,
                    redirectTo: !isAuthenticated ? authConfig.redirectTo : undefined,
                    errorMessage: !isAuthenticated ? authConfig.errorMessage : undefined
                };
                // 缓存成功的认证结果
                if (result.allowed) {
                    executionCache.set(cacheKey, result);
                }
                return result;
            }
            catch (error) {
                const result = {
                    success: false,
                    allowed: false,
                    error: error instanceof Error ? error.message : String(error),
                    redirectTo: authConfig.redirectTo,
                    errorMessage: authConfig.errorMessage || '认证检查失败'
                };
                return result;
            }
            finally {
                globalPerformanceTracker.endTimer('auth_execution');
                globalPerformanceTracker.increment('auth_executions');
            }
        });
    }
    /**
     * 执行路由守卫
     */
    static executeGuard(guardConfig, context) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            if (!(guardConfig === null || guardConfig === void 0 ? void 0 : guardConfig.condition)) {
                return {
                    success: true,
                    allowed: true,
                    guardName: guardConfig.name || 'unknown'
                };
            }
            // 创建缓存键
            const cacheKey = `guard_${guardConfig.name}_${context.path}_${((_a = context.user) === null || _a === void 0 ? void 0 : _a.id) || 'anonymous'}`;
            // 检查缓存
            const cached = guardCache.get(cacheKey);
            if (cached) {
                return cached;
            }
            globalPerformanceTracker.startTimer('guard_execution');
            try {
                const guardContext = {
                    path: context.path,
                    params: context.params,
                    query: context.query,
                    user: context.user,
                    permissions: context.permissions,
                    roles: context.roles,
                    data: context.data
                };
                const conditionResult = yield guardConfig.condition(guardContext);
                const result = {
                    success: true,
                    allowed: !!conditionResult,
                    guardName: guardConfig.name || 'unknown',
                    redirectTo: !conditionResult ? guardConfig.redirectTo : undefined,
                    errorMessage: !conditionResult ? guardConfig.errorMessage : undefined
                };
                // 缓存允许的结果
                if (result.allowed) {
                    guardCache.set(cacheKey, result);
                }
                return result;
            }
            catch (error) {
                const result = {
                    success: false,
                    allowed: false,
                    guardName: guardConfig.name || 'unknown',
                    error: error instanceof Error ? error.message : String(error),
                    redirectTo: guardConfig.redirectTo,
                    errorMessage: guardConfig.errorMessage || '守卫检查失败'
                };
                return result;
            }
            finally {
                globalPerformanceTracker.endTimer('guard_execution');
                globalPerformanceTracker.increment('guard_executions');
            }
        });
    }
    /**
     * 执行中间件
     */
    static executeMiddleware(middlewareConfig, context, next) {
        return __awaiter(this, void 0, void 0, function* () {
            try {
                const middlewareContext = {
                    path: context.path,
                    params: context.params,
                    query: context.query,
                    user: context.user,
                    data: context.data,
                    headers: context.headers
                };
                // 只在生产环境检查 devOnly
                if (middlewareConfig.devOnly && process.env.NODE_ENV === 'production') {
                    yield next();
                    return;
                }
                yield middlewareConfig.handler(middlewareContext, next);
            }
            catch (error) {
                console.error('Middleware execution failed:', error);
                throw error;
            }
        });
    }
    /**
     * 执行中间件链
     */
    static executeMiddlewareChain(middlewares, context, finalHandler) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!middlewares || middlewares.length === 0) {
                yield finalHandler();
                return;
            }
            globalPerformanceTracker.startTimer('middleware_chain');
            // 按优先级排序
            const sortedMiddlewares = [...middlewares].sort((a, b) => (a.priority || 0) - (b.priority || 0));
            let currentIndex = 0;
            const next = () => __awaiter(this, void 0, void 0, function* () {
                if (currentIndex >= sortedMiddlewares.length) {
                    yield finalHandler();
                    return;
                }
                const middleware = sortedMiddlewares[currentIndex++];
                // 跳过开发环境限制的中间件
                if (middleware.devOnly && process.env.NODE_ENV === 'production') {
                    yield next();
                    return;
                }
                globalPerformanceTracker.startTimer(`middleware_${middleware.name || currentIndex}`);
                try {
                    if (middleware.handler) {
                        yield middleware.handler(context, next);
                    }
                    else {
                        yield next();
                    }
                }
                catch (error) {
                    console.error(`Middleware ${middleware.name || currentIndex} failed:`, error);
                    // 继续执行下一个中间件
                    yield next();
                }
                finally {
                    globalPerformanceTracker.endTimer(`middleware_${middleware.name || currentIndex}`);
                    globalPerformanceTracker.increment('middleware_executions');
                }
            });
            try {
                yield next();
            }
            finally {
                globalPerformanceTracker.endTimer('middleware_chain');
            }
        });
    }
    /**
     * 执行守卫链
     */
    static executeGuardChain(guards, context) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!guards || guards.length === 0) {
                return { success: true, allowed: true };
            }
            globalPerformanceTracker.startTimer('guard_chain');
            try {
                // 并行执行所有守卫
                const guardPromises = guards.map((guard) => __awaiter(this, void 0, void 0, function* () {
                    if ('check' in guard) {
                        // 认证守卫
                        return this.executeAuth(guard, context);
                    }
                    else {
                        // 路由守卫
                        return this.executeGuard(guard, context);
                    }
                }));
                const results = yield Promise.all(guardPromises);
                // 检查是否有守卫失败
                for (const result of results) {
                    if (!result.success || !result.allowed) {
                        return {
                            success: result.success,
                            allowed: false,
                            redirectTo: result.redirectTo,
                            errorMessage: result.errorMessage,
                            error: result.error
                        };
                    }
                }
                return { success: true, allowed: true };
            }
            catch (error) {
                return {
                    success: false,
                    allowed: false,
                    error: error instanceof Error ? error.message : String(error),
                    errorMessage: '守卫链执行失败'
                };
            }
            finally {
                globalPerformanceTracker.endTimer('guard_chain');
                globalPerformanceTracker.increment('guard_chain_executions');
            }
        });
    }
    /**
     * 清理缓存
     */
    static clearCache() {
        executionCache.clear();
        guardCache.clear();
    }
    /**
     * 获取性能统计
     */
    static getPerformanceStats() {
        return Object.assign(Object.assign({}, globalPerformanceTracker.getStats()), { cacheStats: {
                executionCache: executionCache.size(),
                guardCache: guardCache.size()
            } });
    }
}
/**
 * 创建运行时上下文
 */
function createRuntimeContext(path, params = {}, query = {}, user, additionalData = {}) {
    return {
        path,
        params,
        query,
        user,
        permissions: (user === null || user === void 0 ? void 0 : user.permissions) || [],
        roles: (user === null || user === void 0 ? void 0 : user.roles) || [],
        data: additionalData,
        headers: {}
    };
}

/**
 * 从存储中获取当前用户
 */
function getCurrentUser() {
    try {
        const instance = reactStorage.ReactStorage.getInstance();
        instance.type = 'localStorage';
        return instance.get('auth_user') || null;
    }
    catch (_a) {
        return null;
    }
}
/**
 * 检查是否有本地认证状态
 */
function hasLocalAuth() {
    try {
        const instance = reactStorage.ReactStorage.getInstance();
        instance.type = 'localStorage';
        const token = instance.get('auth_token');
        const user = instance.get('auth_user');
        if (!token && !user) {
            // 尝试 sessionStorage
            instance.type = 'sessionStorage';
            const sessionToken = instance.get('auth_token');
            const sessionUser = instance.get('auth_user');
            return !!(sessionToken || sessionUser);
        }
        return !!(token || user);
    }
    catch (_a) {
        return false;
    }
}
/**
 * 路由保护包装器组件
 *
 * 用于保护路由,执行守卫检查和中间件逻辑
 * 兼容原始库的 RouteProtectionWrapper
 */
function RouteProtectionWrapper({ guards = [], middlewares = [], loadingElement, component, children }) {
    const location = reactRouter.useLocation();
    const navigate = reactRouter.useNavigate();
    const [isReady, setIsReady] = React.useState(false);
    const [error, setError] = React.useState(null);
    // 缓存用户信息和上下文
    const currentUser = React.useMemo(() => getCurrentUser(), [location.pathname]);
    const hasAuth = React.useMemo(() => hasLocalAuth(), [location.pathname]);
    // 创建运行时上下文
    const context = React.useMemo(() => {
        const searchParams = new URLSearchParams(location.search);
        return createRuntimeContext(location.pathname, {}, // 路由参数将由路由系统自动提供
        Object.fromEntries(searchParams), currentUser, { hasLocalAuth: hasAuth, timestamp: Date.now() });
    }, [location.pathname, location.search, currentUser, hasAuth]);
    React.useEffect(() => {
        const executeProtectionLogic = () => __awaiter(this, void 0, void 0, function* () {
            setIsReady(false);
            setError(null);
            try {
                // 1. 规范化守卫数组
                const normalizedGuards = guards.map(guard => {
                    // 如果是函数,转换为 GuardOptions
                    if (typeof guard === 'function') {
                        return {
                            name: 'anonymous-guard',
                            type: 'custom',
                            condition: guard,
                            redirectTo: '/login'
                        };
                    }
                    // 如果是模块对象,提取实际的守卫配置
                    if (guard && typeof guard === 'object') {
                        const module = guard.default || guard;
                        // 如果有 condition 属性,认为是 GuardOptions
                        if (module.condition) {
                            return {
                                name: module.name || 'guard',
                                type: module.type || 'custom',
                                condition: module.condition,
                                redirectTo: module.redirectTo || '/403',
                                errorMessage: module.errorMessage
                            };
                        }
                        // 如果有 check 属性,认为是 AuthOptions
                        if (module.check) {
                            return {
                                name: module.name || 'auth',
                                check: module.check,
                                redirectTo: module.redirectTo || '/login',
                                errorMessage: module.errorMessage,
                                roles: module.roles,
                                permissions: module.permissions
                            };
                        }
                        // 直接返回,假设已经是正确格式
                        return module;
                    }
                    return guard;
                });
                // 2. 规范化中间件数组
                const normalizedMiddlewares = middlewares.map(middleware => {
                    // 如果是函数,转换为 MiddlewareOptions
                    if (typeof middleware === 'function') {
                        return {
                            name: 'anonymous-middleware',
                            priority: 50,
                            handler: middleware
                        };
                    }
                    // 如果是模块对象,提取实际的中间件配置
                    if (middleware && typeof middleware === 'object') {
                        const module = middleware.default || middleware;
                        // 如果有 handler 属性,认为是 MiddlewareOptions
                        if (module.handler) {
                            return {
                                name: module.name || 'middleware',
                                priority: module.priority || 50,
                                devOnly: module.devOnly || false,
                                handler: module.handler
                            };
                        }
                        // 直接返回,假设已经是正确格式
                        return module;
                    }
                    return middleware;
                });
                // 3. 执行中间件链
                if (normalizedMiddlewares.length > 0) {
                    yield RuntimeExecutor.executeMiddlewareChain(normalizedMiddlewares, context, () => Promise.resolve());
                }
                // 4. 执行守卫链
                if (normalizedGuards.length > 0) {
                    const guardResult = yield RuntimeExecutor.executeGuardChain(normalizedGuards, context);
                    if (!guardResult.success || !guardResult.allowed) {
                        // 守卫检查失败
                        if (guardResult.redirectTo) {
                            navigate(guardResult.redirectTo, { replace: true });
                            return;
                        }
                        else {
                            setError(guardResult.errorMessage || '访问被拒绝');
                            setIsReady(true);
                            return;
                        }
                    }
                }
                // 5. 所有检查通过
                setIsReady(true);
            }
            catch (err) {
                console.error('Route protection failed:', err);
                setError('路由保护检查失败');
                setIsReady(true);
            }
        });
        // 防抖执行,避免频繁重复检查
        const timeoutId = setTimeout(executeProtectionLogic, 10);
        return () => clearTimeout(timeoutId);
    }, [location.pathname, location.search, guards, middlewares, currentUser]);
    // 显示加载状态
    if (!isReady && loadingElement) {
        return jsxRuntime.jsx(jsxRuntime.Fragment, { children: loadingElement });
    }
    // 显示错误状态
    if (error) {
        return (jsxRuntime.jsx("div", Object.assign({ style: {
                padding: '20px',
                color: 'red',
                textAlign: 'center'
            } }, { children: error })));
    }
    // 如果还在加载且没有加载元素,显示默认加载
    if (!isReady) {
        return (jsxRuntime.jsx("div", Object.assign({ style: {
                padding: '20px',
                textAlign: 'center'
            } }, { children: "Loading..." })));
    }
    // 渲染受保护的组件
    const targetComponent = children || component;
    // 如果有加载元素,使用 Suspense 包装
    if (loadingElement) {
        return (jsxRuntime.jsx(React.Suspense, Object.assign({ fallback: loadingElement }, { children: targetComponent })));
    }
    return jsxRuntime.jsx(jsxRuntime.Fragment, { children: targetComponent });
}
/**
 * 高阶组件形式的路由保护
 */
function withRouteProtection(WrappedComponent, options = {}) {
    const WithRouteProtectionComponent = (props) => {
        return (jsxRuntime.jsx(RouteProtectionWrapper, Object.assign({}, options, { component: jsxRuntime.jsx(WrappedComponent, Object.assign({}, props)) })));
    };
    WithRouteProtectionComponent.displayName = `WithRouteProtection(${WrappedComponent.displayName || WrappedComponent.name})`;
    return WithRouteProtectionComponent;
}
/**
 * Hook 形式的路由保护
 */
function useRouteProtection(guards = [], middlewares = []) {
    const location = reactRouter.useLocation();
    const navigate = reactRouter.useNavigate();
    const [isLoading, setIsLoading] = React.useState(true);
    const [error, setError] = React.useState(null);
    const [hasAccess, setHasAccess] = React.useState(false);
    const currentUser = React.useMemo(() => getCurrentUser(), [location.pathname]);
    React.useEffect(() => {
        const checkAccess = () => __awaiter(this, void 0, void 0, function* () {
            setIsLoading(true);
            setError(null);
            try {
                const searchParams = new URLSearchParams(location.search);
                const context = createRuntimeContext(location.pathname, {}, Object.fromEntries(searchParams), currentUser);
                // 检查守卫
                if (guards && guards.length > 0) {
                    const normalizedGuards = guards.map(guard => {
                        if (typeof guard === 'function') {
                            return {
                                name: 'hook-guard',
                                type: 'custom',
                                condition: guard,
                                redirectTo: '/login'
                            };
                        }
                        return guard;
                    });
                    const result = yield RuntimeExecutor.executeGuardChain(normalizedGuards, context);
                    if (!result.success || !result.allowed) {
                        if (result.redirectTo) {
                            navigate(result.redirectTo, { replace: true });
                            return;
                        }
                        else {
                            setError(result.errorMessage || '访问被拒绝');
                            setHasAccess(false);
                            setIsLoading(false);
                            return;
                        }
                    }
                }
                setHasAccess(true);
            }
            catch (err) {
                setError('访问检查失败');
                setHasAccess(false);
            }
            finally {
                setIsLoading(false);
            }
        });
        checkAccess();
    }, [location.pathname, guards, middlewares, currentUser]);
    return {
        isLoading,
        error,
        hasAccess,
        user: currentUser
    };
}

/**
 * 国际化路由加载器集成
 * 为 React Router v7 提供国际化支持
 */
/**
 * 创建国际化路由 loader
 * 用于在路由加载时预加载所需的翻译资源
 */
function createI18nRouteLoader(i18nClient, options) {
    return ({ request, params }) => __awaiter(this, void 0, void 0, function* () {
        var _a;
        const url = new URL(request.url);
        const searchParams = url.searchParams;
        // 从 URL 参数或路径参数中获取语言
        const urlLocale = searchParams.get('locale') || params.locale;
        // 从 localStorage/sessionStorage 获取保存的语言
        const savedLocale = typeof window !== 'undefined'
            ? localStorage.getItem(((_a = i18nClient.config.persistence) === null || _a === void 0 ? void 0 : _a.key) || 'user_locale')
            : null;
        // 确定要加载的语言
        const targetLocale = urlLocale || savedLocale || i18nClient.config.defaultLocale;
        // 预加载翻译资源
        if (options === null || options === void 0 ? void 0 : options.preloadAll) {
            yield i18nClient.preloadResources();
        }
        else {
            const localesToLoad = (options === null || options === void 0 ? void 0 : options.locales) || [targetLocale];
            yield i18nClient.preloadResources(localesToLoad);
        }
        // 如果有延迟设置(用于演示加载状态)
        if ((options === null || options === void 0 ? void 0 : options.delay) && options.delay > 0) {
            yield new Promise(resolve => setTimeout(resolve, options.delay));
        }
        return {
            locale: targetLocale,
            i18nLoaded: true
        };
    });
}
/**
 * 创建带国际化的 defer loader
 * 支持 React Router v7 的 defer 功能
 */
function createDeferredI18nLoader(i18nClient, dataLoader) {
    return ({ request, params }) => __awaiter(this, void 0, void 0, function* () {
        const url = new URL(request.url);
        const locale = url.searchParams.get('locale') ||
            params.locale ||
            i18nClient.config.defaultLocale;
        // 延迟加载国际化资源
        const i18nPromise = i18nClient.preloadResources([locale]);
        // 如果有数据加载器,同时执行
        if (dataLoader) {
            const dataPromise = dataLoader({ request, params, context: {} });
            // 使用 defer 支持流式渲染
            return {
                locale,
                i18n: i18nPromise,
                data: dataPromise
            };
        }
        return {
            locale,
            i18n: i18nPromise
        };
    });
}
/**
 * 国际化路由 handle 增强
 * 自动处理页面标题的国际化
 */
function createI18nHandle(baseHandle = {}) {
    return Object.assign(Object.assign({}, baseHandle), { 
        // 标记为需要国际化处理
        i18n: true, 
        // 保留原始的 meta 配置
        meta: baseHandle.meta || {}, 
        // 添加国际化元数据处理器
        getI18nMeta: (t) => {
            const meta = baseHandle.meta || {};
            return {
                title: meta.title ? t(meta.title) : undefined,
                description: meta.description ? t(meta.description) : undefined
            };
        } });
}
/**
 * 创建国际化路由配置
 * 为现有路由配置添加国际化支持
 */
function enhanceRoutesWithI18n(routes, i18nClient, options) {
    const { autoAddLoader = true, localeParam = 'locale' } = options || {};
    return routes.map(route => {
        // 如果路由已经有 loader,增强它
        if (route.loader && autoAddLoader) {
            const originalLoader = route.loader;
            route.loader = createDeferredI18nLoader(i18nClient, originalLoader);
        }
        else if (autoAddLoader && !route.loader) {
            // 如果没有 loader,添加一个简单的国际化 loader
            route.loader = createI18nRouteLoader(i18nClient);
        }
        // 如果有 handle,增强它以支持国际化
        if (route.handle) {
            route.handle = createI18nHandle(route.handle);
        }
        // 递归处理子路由
        if (route.children) {
            route.children = enhanceRoutesWithI18n(route.children, i18nClient, options);
        }
        return route;
    });
}
/**
 * Hook: 在组件中使用路由国际化数据
 */
function useRouteI18n() {
    // 该 Hook 应该与 useLoaderData 配合使用
    // 由 createI18nRouteLoader 提供的数据
    return {
    // 这里可以添加更多的辅助方法
    };
}

exports.BatchProcessor = BatchProcessor;
exports.Debouncer = Debouncer;
exports.I18nClient = I18nClient;
exports.I18nProvider = I18nProvider;
exports.MemoryOptimizer = MemoryOptimizer;
exports.PerformanceCache = PerformanceCache;
exports.PerformanceTracker = PerformanceTracker;
exports.RouteProtectionWrapper = RouteProtectionWrapper;
exports.RuntimeExecutor = RuntimeExecutor;
exports.SimpleCache = SimpleCache;
exports.ViteI18nLoader = ViteI18nLoader;
exports.buildQuery = buildQuery;
exports.capitalize = capitalize;
exports.createDeferredI18nLoader = createDeferredI18nLoader;
exports.createI18nClient = createI18nClient;
exports.createI18nHandle = createI18nHandle;
exports.createI18nLoader = createI18nLoader;
exports.createI18nRouteLoader = createI18nRouteLoader;
exports.createResourceLoader = createResourceLoader;
exports.createRuntimeContext = createRuntimeContext;
exports.debounce = debounce;
exports.deepClone = deepClone;
exports.deepMerge = deepMerge;
exports.defineAuth = defineAuth;
exports.defineCustomGuard = defineCustomGuard;
exports.defineGuard = defineGuard;
exports.defineHandle = defineHandle;
exports.defineMiddleware = defineMiddleware;
exports.definePermissionGuard = definePermissionGuard;
exports.defineRoleGuard = defineRoleGuard;
exports.enhanceRoutesWithI18n = enhanceRoutesWithI18n;
exports.extractParams = extractParams;
exports.globalMemoryOptimizer = globalMemoryOptimizer;
exports.globalPerformanceTracker = globalPerformanceTracker;
exports.groupBy = groupBy;
exports.isEmpty = isEmpty;
exports.isFunction = isFunction;
exports.isLocalized = isLocalized;
exports.isPromise = isPromise;
exports.isRecord = isRecord;
exports.joinPath = joinPath;
exports.localize = localize;
exports.mapToArray = mapToArray;
exports.matchPath = matchPath;
exports.measureAsync = measureAsync;
exports.measureTime = measureTime;
exports.normalizePath = normalizePath;
exports.parseQuery = parseQuery;
exports.safeParseInt = safeParseInt;
exports.safely = safely;
exports.safelyAsync = safelyAsync;
exports.throttle = throttle;
exports.toCamelCase = toCamelCase;
exports.toJSON = toJSON;
exports.toKebabCase = toKebabCase;
exports.translateLocalized = translateLocalized;
exports.truncate = truncate;
exports.unique = unique;
exports.updateQuery = updateQuery;
exports.useAuthToken = useAuthToken;
exports.useBreadcrumbs = useBreadcrumbs;
exports.useDocumentTitle = useDocumentTitle;
exports.useHandle = useHandle;
exports.useI18n = useI18n;
exports.useI18nKeyValidator = useI18nKeyValidator;
exports.useI18nNamespace = useI18nNamespace;
exports.useI18nPageConfig = useI18nPageConfig;
exports.useLayoutConfig = useLayoutConfig;
exports.useLayoutFeatures = useLayoutFeatures;
exports.useLayoutSettings = useLayoutSettings;
exports.usePageConfig = usePageConfig;
exports.usePageMeta = usePageMeta;
exports.usePlural = usePlural;
exports.useRouteI18n = useRouteI18n;
exports.useRouteProtection = useRouteProtection;
exports.useStorage = useStorage;
exports.useTranslateLocalized = useTranslateLocalized;
exports.useUser = useUser;
exports.useUserState = useUserState;
exports.useVGroveLayoutSettings = useVGroveLayoutSettings;
exports.withRouteProtection = withRouteProtection;
//# sourceMappingURL=index.js.map