First commit to the code repository

This commit is contained in:
Liujian committed 2025-07-20 22:38:52 +08:00
1 parent 692cdee407
commit 0c0dd1cb56
323 files changed
+45712

No files matched your search

@@ -0,0 +1,36 @@
"use client";
import React, { useEffect } from "react";
import { I18nextProvider } from "react-i18next";
import i18n, { i18nPromise } from "@/shared/lib/i18n";
interface ClientI18nProviderProps {
children: React.ReactNode;
}
export const ClientI18nProvider: React.FC<ClientI18nProviderProps> = ({
children,
}) => {
const initAll = async () => {
if (i18n.isInitialized) return
await i18nPromise;
const storedLang = localStorage.getItem("i18nextLng");
// only switch when the stored language is different from the current language
if (storedLang && storedLang !== i18n.language) {
await i18n.changeLanguage(storedLang);
}
};
useEffect(() => {
initAll();
}, []);
return (
<div style={{
opacity: 1,
transition: 'opacity 0.2s ease-in-out'
}}>
<I18nextProvider i18n={i18n}>{children}</I18nextProvider>
</div>
);
};
@@ -0,0 +1,26 @@
"use client";
import React from "react";
import { Providers } from "@/shared/providers/nextui-provider";
import { ClientI18nProvider } from "@/shared/components/ClientI18nProvider";
import { PlatformConfigProvider } from "@/shared/contexts/PlatformConfigContext";
import { Toaster } from "react-hot-toast";
import { PlatformConfigResponse } from "@/shared/types/system";
export default function ClientRootProviders({
children,
initConfig
}: {
children: React.ReactNode;
initConfig: PlatformConfigResponse;
}) {
return (
<ClientI18nProvider>
<PlatformConfigProvider initConfig={initConfig}>
<Toaster position="top-center" />
<Providers>{children}</Providers>
</PlatformConfigProvider>
</ClientI18nProvider>
);
}
@@ -0,0 +1,30 @@
"use client";
import React from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
interface DashboardDemoContentProps {
children: React.ReactNode;
title: string;
description: string;
}
const DashboardDemoContent: React.FC<DashboardDemoContentProps> = ({
children,
title,
description,
}) => {
const { t } = useTranslation();
return (
<div className="flex flex-col h-full overflow-auto p-8">
{/* Header */}
<div className="mb-8">
<h1 className="text-3xl font-bold text-foreground mb-2">{t(title)}</h1>
<p className="text-default-600">{t(description)}</p>
</div>
{children}
</div>
);
};
export default DashboardDemoContent;
@@ -0,0 +1,82 @@
"use client";
import React from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import {
Button,
Divider,
Link,
} from "@nextui-org/react";
import {
LogOut,
} from "lucide-react";
import { DashboardSidebarProps } from "@/shared/types/dashboard";
import { DynamicLogo } from "@/shared/components/DynamicLogo";
const DashboardSidebar: React.FC<DashboardSidebarProps> = ({
activeTab,
onTabNavigate,
onLogout,
sidebarItems, userProfilePanel
}) => {
const { t } = useTranslation();
return (
<div className="w-[340px] h-screen bg-content1 border-r border-divider overflow-y-auto sidebar-thin">
<div className="p-6">
{/* Header */}
<div className="mb-8 flex flex-col gap-2">
<div className="flex justify-between items-center gap-2">
<Link href={process.env.NEXT_PUBLIC_DOMAIN || "/"}>
<DynamicLogo
alt="Platform Logo"
className="h-[20px]"
/>
</Link>
</div>
<p className="text-default-600 text-sm">
{t("Build incredible AI agents together")}
</p>
</div>
{/* User Profile */}
{userProfilePanel}
{/* Navigation */}
<div className="flex flex-col gap-4">
{sidebarItems.map((item) => (
<Button
key={item.key}
variant={activeTab === item.key ? "solid" : "bordered"}
color={activeTab === item.key ? "primary" : "default"}
startContent={item.icon}
className="w-full justify-start h-auto p-4"
onPress={() => onTabNavigate?.(item.key)}
>
<div className="flex flex-col items-start">
<div className="font-medium">{t(item.label)}</div>
<div className="text-xs opacity-80">{t(item.description)}</div>
</div>
</Button>
))}
</div>
<Divider className="my-6" />
{/* Logout */}
<Button
variant="light"
color="danger"
startContent={<LogOut className="w-4 h-4" />}
className="w-full justify-start"
onPress={onLogout}
>
{t("Log Out")}
</Button>
</div>
</div>
);
};
export default DashboardSidebar;
@@ -0,0 +1,44 @@
'use client';
import React from 'react';
import { usePlatformConfig } from '@/shared/contexts/PlatformConfigContext';
import { getURL } from '@/shared/rpc/adapter';
interface DynamicLogoProps {
className?: string;
alt?: string;
width?: number;
height?: number;
fallbackSrc?: string;
}
export const DynamicLogo: React.FC<DynamicLogoProps> = ({
className = '',
alt,
width,
height,
fallbackSrc = '/static/logo/logo.png'
}) => {
const { platformConfig } = usePlatformConfig();
const logoSrc = getURL(platformConfig.logo || fallbackSrc);
const logoAlt = alt || `Platform Logo`;
if (!platformConfig.logo) return <></>
return (
<img
src={logoSrc}
alt={logoAlt}
className={className}
width={width}
height={height}
onError={(e) => {
// if custom logo loading fails, fallback to default logo
const target = e.target as HTMLImageElement;
if (target.src !== fallbackSrc) {
target.src = fallbackSrc;
}
}}
/>
);
};
@@ -0,0 +1,84 @@
import React, { useState } from "react";
import { Button } from "@nextui-org/react";
import { ArrowRightIcon } from "lucide-react";
interface FlipButtonProps {
text: string;
onPress?: () => void;
className?: string;
}
export const FlipButton: React.FC<FlipButtonProps> = ({
text,
onPress,
className = "",
}) => {
const [isHovered, setIsHovered] = useState(false);
const characters = text.split("");
const STAGGER = 20;
return (
<Button
color="primary"
radius="full"
onPress={onPress}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
className={`relative min-w-[200px] bg-black flex items-center justify-between gap-4 pr-1 md:pr-2 h-[40px] md:h-[50px] overflow-hidden ${className}`.trim()}
>
{/* Primary text */}
<div className="text-md md:text-lg font-bold flex items-center">
{characters.map((char, index) => (
<span
key={index}
className="inline-block transition-all duration-500 ease-in-out"
style={{
transitionProperty: "transform, opacity, filter",
transform: isHovered
? `translateY(-18px) rotateX(80deg)`
: "none",
filter: isHovered ? "blur(4px)" : "blur(0px)",
opacity: isHovered ? 0 : 1,
transitionDelay: isHovered
? `${index * STAGGER}ms`
: `${(characters.length - index - 1) * STAGGER}ms`,
}}
>
{char === " " ? "\u00A0" : char}
</span>
))}
</div>
{/* Overlay text (appears on hover) */}
<div
className="absolute left-4 text-md md:text-lg font-bold flex items-center"
aria-hidden="true"
>
{characters.map((char, index) => (
<span
key={index}
className="inline-block transition-all duration-500 ease-in-out"
style={{
transitionProperty: "transform, opacity, filter",
transform: isHovered
? "none"
: `translateY(18px) rotateX(-80deg)`,
filter: isHovered ? "blur(0px)" : "blur(4px)",
opacity: isHovered ? 1 : 0,
transitionDelay: isHovered
? `${index * STAGGER}ms`
: `${(characters.length - index - 1) * STAGGER}ms`,
}}
>
{char === " " ? "\u00A0" : char}
</span>
))}
</div>
{/* Arrow icon */}
<div className="w-8 h-8 min-w-8 min-h-8 bg-gray-100 flex items-center justify-center rounded-full">
<ArrowRightIcon size={16} className="text-default-700" />
</div>
</Button>
);
};
+15
View File
@@ -0,0 +1,15 @@
'use client'
import React from "react";
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
import { Link } from "@nextui-org/react";
export function Footer() {
const { platformConfig } = usePlatformConfig();
return (
<footer className="py-4 px-4 sm:px-6 text-center sm:text-end max-w-7xl mx-auto text-xs">
<span className="mr-1">© 2025 {platformConfig?.name}. All rights reserved.</span>
<Link className="text-xs" href="https://xpack.ai">Powered By XPack.AI</Link>
</footer>
);
}
@@ -0,0 +1,151 @@
"use client";
import React, { useState } from "react";
import {
Navbar,
NavbarContent,
NavbarItem,
NavbarMenuToggle,
NavbarMenu,
NavbarMenuItem,
Button,
} from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { useAuth } from "@/shared/lib/useAuth";
import { ArrowRightIcon } from "lucide-react";
import { DynamicLogo } from "@/shared/components/DynamicLogo";
import Link from "next/link";
interface NavigationProps {
items?: {
label: string;
href: string;
}[];
}
// Client-side wrapper for interactive functionality
function NavigationClient({ items = [] }: NavigationProps) {
const [isMenuOpen, setIsMenuOpen] = useState(false);
const { t } = useTranslation();
const { handleLogin } = useAuth();
return (
<>
{/* Main Navigation */}
<Navbar
onMenuOpenChange={setIsMenuOpen}
maxWidth="full"
/*
* Rounded-pill navigation container with subtle border & backdrop blur
* Matches the reference design that features a floating white bar with full-round corners.
*/
className="mt-2 sm:mt-5 rounded-full bg-background/50 backdrop-blur-[10px] border-1 border-gray-100 top-2 sm:top-5 max-w-7xl mx-auto"
height="66px"
isBordered={false}
>
<NavbarContent>
<NavbarMenuToggle
aria-label={isMenuOpen ? "Close menu" : "Open menu"}
className="sm:hidden"
/>
<div className="flex justify-start bg-transparent w-max">
{/* Logo using dynamic platform config */}
<Link href="/">
<DynamicLogo
alt="Platform Logo"
className="h-[20px]"
/>
</Link>
<Link
href="https://xpack.ai/techblog"
target="_blank"
className="hidden"
></Link>
</div>
{/* Desktop Navigation */}
<div className="hidden lg:flex gap-6 justify-center">
{items.map((item) => (
<NavbarItem key={item.href}>
<Link
color="foreground"
href={item.href}
className="font-medium text-foreground-600 hover:text-foreground transition-colors px-2 py-1"
>
{t(item.label)}
</Link>
</NavbarItem>
))}
</div>
</NavbarContent>
{/* Right Side Actions */}
<NavbarContent justify="end" className="items-center gap-2 sm:gap-4">
{/* Desktop Auth Button */}
<div className="hidden sm:block">
<Button
color="primary"
className="bg-black flex items-center justify-center gap-4 pr-1 h-[45px]"
radius="full"
onPress={handleLogin}
>
<b className="text-md"> {t("Get Started")}</b>
<div className="w-8 h-8 bg-gradient-to-r from-primary to-[#9ab0f2] flex items-center justify-center rounded-full">
<ArrowRightIcon
size={16}
className="transition-transform duration-200 ease-in-out group-hover:translate-x-[3px]"
/>
</div>
</Button>
</div>
{/* Mobile Auth Button */}
<div className="sm:hidden">
<Button color="primary" onPress={handleLogin} size="sm">
<b className="text-md"> {t("Get Started")}</b>
</Button>
</div>
</NavbarContent>
{/* Mobile Menu */}
<NavbarMenu className="pt-6 pb-6">
{items.map((item, index) => (
<NavbarMenuItem key={`${item.href}-${index}`}>
<Link
color="foreground"
href={item.href}
className="w-full py-2 font-medium text-sm"
>
{t(item.label)}
</Link>
</NavbarMenuItem>
))}
<NavbarMenuItem className="mt-4">
<Button
color="primary"
className="w-full bg-black flex items-center justify-between gap-4 pr-1 h-[45px]"
radius="full"
onPress={handleLogin}
>
<b className="text-md"> {t("Get Started")}</b>
<div className="w-8 h-8 bg-gradient-to-r from-primary to-[#9ab0f2] flex items-center justify-center rounded-full">
<ArrowRightIcon
size={16}
className="transition-transform duration-200 ease-in-out group-hover:translate-x-[3px]"
/>
</div>
</Button>
</NavbarMenuItem>
</NavbarMenu>
</Navbar>
</>
);
}
// Export the client component
export function Navigation(props: NavigationProps) {
return <NavigationClient {...props} />;
}
@@ -0,0 +1,127 @@
import React, { useState, useEffect, useRef } from "react";
import { Input, Button } from "@nextui-org/react";
import { Search } from "lucide-react";
import { useTranslation } from "react-i18next";
import { _DefaultPlatformConfig, usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
interface HeroSectionProps {
searchQuery: string;
onSearchChange: (value: string) => void;
onSearch?: () => void;
}
export const HeroSection: React.FC<HeroSectionProps> = ({
searchQuery,
onSearchChange,
onSearch,
}) => {
const { platformConfig } = usePlatformConfig();
const { t } = useTranslation();
const [isFocused, setIsFocused] = useState(false);
const [animatedText, setAnimatedText] = useState("");
const [currentSuggestionIndex, setCurrentSuggestionIndex] = useState(0);
const [isTyping, setIsTyping] = useState(true);
const inputRef = useRef<HTMLInputElement>(null);
const searchSuggestions = [
t("get latest documentation for libraries"),
t("execute terminal commands safely"),
t("find latest scientific research papers"),
t("tools to enhance thinking and reasoning"),
t("find flight tickets and airbnb listings"),
t("automate web browser interactions"),
t("send messages and receive notifications")
];
useEffect(() => {
if (isFocused || searchQuery) {
return;
}
const currentSuggestion = searchSuggestions[currentSuggestionIndex];
let timeoutId: NodeJS.Timeout;
if (isTyping) {
// typing effect
if (animatedText.length < currentSuggestion.length) {
timeoutId = setTimeout(() => {
setAnimatedText(currentSuggestion.slice(0, animatedText.length + 1));
}, 100);
} else {
// typing completed, wait for a while then start deleting
timeoutId = setTimeout(() => {
setIsTyping(false);
}, 2000);
}
} else {
// deleting effect
if (animatedText.length > 0) {
timeoutId = setTimeout(() => {
setAnimatedText(animatedText.slice(0, -1));
}, 50);
} else {
// deleting completed, switch to next suggestion
setCurrentSuggestionIndex((prev) => (prev + 1) % searchSuggestions.length);
setIsTyping(true);
}
}
return () => clearTimeout(timeoutId);
}, [animatedText, currentSuggestionIndex, isTyping, isFocused, searchQuery]);
const handleKeyPress = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
onSearch?.();
}
};
const handleSearchClick = () => {
onSearch?.();
};
return (
<div className="relative overflow-hidden mx-auto p-6 py-24 max-w-7xl">
<div className="text-center mb-12">
<h1 className="text-5xl lg:text-6xl font-bold mb-6 leading-tight text-primary">
{platformConfig.headline || t(_DefaultPlatformConfig.headline || "")}
</h1>
<p className="text-2xl font-medium max-w-3xl mx-auto leading-relaxed">
{platformConfig.subheadline || t(_DefaultPlatformConfig.subheadline || "")}
</p>
</div>
{/* Search Bar */}
<div className="max-w-4xl mx-auto relative">
<Input
ref={inputRef}
size="lg"
placeholder={isFocused || searchQuery ? "" : animatedText}
value={searchQuery}
onChange={(e) => onSearchChange(e.target.value)}
onFocus={() => setIsFocused(true)}
onBlur={() => setIsFocused(false)}
onKeyDown={handleKeyPress}
endContent={
searchQuery && (
<Button
isIconOnly
onPress={handleSearchClick}
variant="flat"
color="primary"
>
<Search size={20} />
</Button>
)
}
className="w-full"
classNames={{
input: "text-lg text-gray-900 placeholder:text-gray-500",
inputWrapper: "h-16 shadow-none px-4 bg-white",
}}
variant="faded"
/>
</div>
</div>
);
};
@@ -0,0 +1,50 @@
"use client";
import { useTranslation } from "@/shared/lib/useTranslation";
import { ChargeType } from "@/shared/types/marketplace";
import { Chip } from "@nextui-org/react";
import { Zap } from "lucide-react";
import React from "react";
interface PriceProps {
price?: string;
charge_type: ChargeType;
}
export const Price: React.FC<PriceProps> = ({
price,
charge_type
}) => {
const { t } = useTranslation();
if (charge_type === ChargeType.Free) {
return (
<Chip size="sm" variant="flat" color="default">
{t('Free')}
</Chip>
);
}
const priceText = parseFloat(price || '0');
if (charge_type === ChargeType.PerCall) {
return (
<div className="flex items-center gap-1">
<span className="text-sm font-medium text-green-600">
${priceText.toFixed(2)}
</span>
<span className="text-xs text-gray-500">/{t('Per Call')}</span>
</div>
);
} else {
return (
<div className="flex items-center gap-1">
<Zap className="w-3 h-3 text-blue-600" />
<span className="text-sm font-medium text-blue-600">
${priceText.toFixed(2)}
</span>
<span className="text-xs text-gray-500">/{t('token')}</span>
</div>
);
}
};
@@ -0,0 +1,79 @@
"use client";
import React, { useState } from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { Tabs, Tab, Chip } from "@nextui-org/react";
import { ProductHeader } from "./ProductHeader";
import { ProductOverview } from "./ProductOverview";
import { ProductTools } from "./ProductTools";
import { ProductNotFound } from "./ProductNotFound";
import { ServerConfig } from "./ServerConfig";
import { ServiceData } from "@/shared/types/marketplace";
interface ProductDetailClientProps {
product: ServiceData;
breadcrumbs?: {
link: string;
name: string
}[];
}
export const ProductDetailClient: React.FC<ProductDetailClientProps> = ({
product,
breadcrumbs
}) => {
const { t } = useTranslation();
const [activeTab, setActiveTab] = useState("overview");
return (
<div className="flex flex-col mx-auto p-6 max-w-7xl">
{product ? (<>
<ProductHeader
product={product}
breadcrumbs={breadcrumbs}
/>
<div className="flex gap-6 mt-6">
{/* Left side - Main content */}
<div className="flex-1">
<Tabs
selectedKey={activeTab}
onSelectionChange={(key) => setActiveTab(key as string)}
variant="underlined"
color="primary"
>
<Tab key="overview" title={t("Overview")}>
<ProductOverview product={product} />
</Tab>
<Tab key="tools" title={<div className="flex gap-2 items-center">
<span>{t("Tools")}</span>
<Chip size="sm" className="h-4 text-xs"> {product.tools.length}</Chip>
</div>}>
<ProductTools product={product} />
</Tab>
</Tabs>
</div>
{/* Right side - Server Config */}
<ServerConfig product={product} />
</div>
{/* SEO-friendly: Simple text content for search engines */}
<div className="hidden" aria-hidden="true">
<h2>Tools ({product.tools.length})</h2>
{product.tools.length > 0 && (
product.tools.map((tool, index) => (
<div key={`seo-${product.service_id}-tool-${index}`}>
<h4>{tool.name}</h4>
<p>{tool.description || ""}</p>
</div>
))
)}
</div>
</>
) : (<ProductNotFound />)}
</div>
);
};
@@ -0,0 +1,88 @@
"use client";
import React from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import {
Card,
CardBody,
Chip,
} from "@nextui-org/react";
import { ChargeType, ServiceData } from "@/shared/types/marketplace";
import Link from "next/link";
import { Price } from "./Price";
interface ProductHeaderProps {
product: ServiceData;
breadcrumbs?: {
link: string;
name: string
}[];
}
export const ProductHeader: React.FC<ProductHeaderProps> = ({
product,
breadcrumbs = [],
}) => {
const { t } = useTranslation();
return (
<Card shadow="none">
<CardBody>
{/* Breadcrumb */}
<nav className="text-sm text-default-500 flex items-center gap-1 mb-10">
<Link href="/" className="hover:underline">
{t("Home")}
</Link>
{breadcrumbs.map((item, index) => (
<React.Fragment key={index}>
<span>/</span>
<Link href={item.link} className="hover:underline">
{t(item.name)}
</Link>
</React.Fragment>
))}
<span>/</span>
<b className="text-default-700">{t(product.name)}</b>
</nav>
{/* Header with title and price */}
<div className="flex items-start justify-between mb-4">
<div className="flex-1">
<h1 className="text-3xl font-bold mb-2">
{product.name}
</h1>
{/* Tags */}
{product.tags && product.tags.length > 0 && (
<div className="flex flex-wrap gap-2 my-3">
{product.tags.map((tag, index) => (
<Chip
key={index}
size="sm"
variant="flat"
color="primary"
radius="sm"
className="text-xs h-5"
>
{tag}
</Chip>
))}
</div>
)}
<p className="text-lg mb-4">
{product.short_description || t("No description available")}
</p>
</div>
</div>
{/* Price section */}
<div className="flex gap-2 items-center">
<b className="text-xs">{t("Price")}:</b>
<Price price={product.price} charge_type={product.charge_type || ChargeType.Free} />
</div>
</CardBody>
</Card>
);
};
@@ -0,0 +1,47 @@
"use client";
import React from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { useRouter } from "next/navigation";
import {
Card,
CardBody,
Button,
} from "@nextui-org/react";
import { Package } from "lucide-react";
import { Navigation } from "@/shared/components/Navigation";
export const ProductNotFound: React.FC = () => {
const { t } = useTranslation();
const router = useRouter();
return (
<div className="min-h-screen bg-gradient-to-br from-background via-default-50 to-primary-50">
<Navigation />
<div className="flex items-center justify-center py-20">
<Card className="w-full max-w-sm mx-4 sm:mx-0 sm:w-96 shadow-2xl">
<CardBody className="text-center p-8">
<div className="w-16 h-16 mx-auto mb-4 bg-danger-100 rounded-full flex items-center justify-center">
<Package className="text-danger" size={32} />
</div>
<h1 className="text-2xl font-bold mb-4">
{t("Product Not Found")}
</h1>
<p className="text-default-600 mb-6">
{t(
"The product you're looking for doesn't exist or has been removed."
)}
</p>
<Button
onPress={() => router.push("/")}
color="primary"
size="lg"
>
{t("Back to Store")}
</Button>
</CardBody>
</Card>
</div>
</div>
);
};
@@ -0,0 +1,31 @@
"use client";
import React from "react";
import ReactMarkdown from "react-markdown";
import { useTranslation } from "@/shared/lib/useTranslation";
import { Card, CardBody } from "@nextui-org/react";
import { ServiceData } from "@/shared/types/marketplace";
interface ProductOverviewProps {
product: ServiceData;
}
export const ProductOverview: React.FC<ProductOverviewProps> = ({
product,
}) => {
const { t } = useTranslation();
return (
<Card shadow="none">
<CardBody className="space-y-4">
<div className="leading-relaxed prose prose-sm max-w-none">
{product.long_description ? (
<ReactMarkdown>{product.long_description}</ReactMarkdown>
) : (
<p>{t("No description available")}</p>
)}
</div>
</CardBody>
</Card>
);
};
@@ -0,0 +1,39 @@
"use client";
import React from "react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { Button, Avatar, Chip, Card, CardBody } from "@nextui-org/react";
import { ServiceData } from "@/shared/types/marketplace";
interface ProductToolsProps {
product: ServiceData;
}
export const ProductTools: React.FC<ProductToolsProps> = ({ product }) => {
const { t } = useTranslation();
return (
<div className="space-y-4 px-3">
{product.tools.length > 0 ? (
product.tools.map((tool, index) => (
<Card radius="sm" key={`${product.service_id}-tool-${index}`} shadow="none" className="border-1">
<CardBody>
<h4 className="font-semibold text-sm mb-2 text-primary">{tool.name}</h4>
<p className="text-sm mb-3">
{tool.description || t("No description available")}
</p>
</CardBody>
</Card>
))
) : (
<Card>
<CardBody>
<p className="text-center">
{t("No tools available in this service.")}
</p>
</CardBody>
</Card>
)}
</div>
);
};
@@ -0,0 +1,62 @@
"use client";
import React, { useEffect, useState } from "react";
import { ServiceData } from "@/shared/types/marketplace";
import { Card, Chip } from "@nextui-org/react";
import { FlipButton } from "@/shared/components/FlipButton";
import { useAuth } from "@/shared/lib/useAuth";
import { useTranslation } from "react-i18next";
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
interface ServerConfigProps {
product: ServiceData;
}
export const ServerConfig: React.FC<ServerConfigProps> = ({ product }) => {
const { t } = useTranslation();
const { handleLogin } = useAuth();
const { platformConfig } = usePlatformConfig();
const [url, setUrl] = useState<string>(process.env.NEXT_PUBLIC_MCP_URL || "");
useEffect(() => {
if (url || !product.slug_name) return
setUrl(`${window.location.origin}/mcp/${product.slug_name}`);
}, [product.slug_name]);
return (
<div className="min-w-[400px] w-[40%] max-w-100 flex-shrink-0 mt-12">
<div className="mb-4 mt-1">
<FlipButton
className="w-full rounded-md"
text={t("Try for free")}
onPress={handleLogin}
/>
</div>
{/* Code Snippet */}
<Card className="w-full max-w-2xl bg-black text-white p-2 sm:p-4 rounded-lg relative z-10">
<div className="text-left font-mono">
<Chip className="mb-2 text-white" size="sm" variant="flat">
{platformConfig?.name} MCP
</Chip>
<pre className="p-2 sm:p-4 rounded-md text-xs overflow-x-auto">
<code className="text-gray-300 whitespace-pre-wrap">
{`{
"mcpServers": {
"xpack-mcp-market": {
"type": "sse",
"autoApprove"":"all",
"url": "${url}?apikey=`}
<span className="text-success">{`{Your-${platformConfig?.name}-API-Key}`}</span>
{`"
}
}
}`}
</code>
</pre>
</div>
</Card>
</div>
);
};
@@ -0,0 +1,60 @@
"use client";
import React from "react";
import { Card, CardBody, CardFooter, Chip } from "@nextui-org/react";
import { ServiceData } from "@/shared/types/marketplace";
import { useTranslation } from "react-i18next";
import Link from "next/link";
import { ChargeType } from "@/shared/types/marketplace";
import { Price } from "./Price";
interface ServiceCardProps {
service: ServiceData;
}
export const ServiceCard: React.FC<ServiceCardProps> = ({ service }) => {
// generate different icon background color for different services
const { t } = useTranslation();
return (
<Link href={`/marketplace/${service.service_id}`}>
<Card
className="group w-full h-[180px] hover:border-primary-500 transition-all duration-300 border-1"
shadow="none"
radius="sm"
>
<CardBody>
{/* Header with icon and title */}
<div className="flex items-start gap-3 mb-3">
<h3 className="font-semibold text-gray-900 text-sm mb-1 truncate group-hover:text-primary">
{service.name}
</h3>
</div>
{/* Description */}
<p className="text-xs text-gray-600 mb-4 line-clamp-2 leading-relaxed">
{service.short_description || t("No description available")}
</p>
</CardBody>
{/* Footer with tools count */}
<CardFooter>
<div className="flex items-center justify-between w-full">
<Chip
size="sm"
variant="flat"
color="primary"
className="text-[10px] h-5"
>
{t("{{count}} Tools", { count: service.tools.length })}
</Chip>
<div className="flex flex-col gap-1">
<Price price={service.price} charge_type={service.charge_type || ChargeType.Free} />
</div>
</div>
</CardFooter>
</Card>
</Link>
);
};
@@ -0,0 +1,49 @@
"use client";
import React from "react";
import { Pagination } from "@nextui-org/react";
import { ServiceData } from "@/shared/types/marketplace";
import { ServiceCard } from "./ServiceCard";
interface ServiceListSectionProps {
services: ServiceData[];
currentPage: number;
total: number;
pageSize: number;
onPageChange: (page: number) => void;
}
export const ServiceListSection: React.FC<ServiceListSectionProps> = ({
services,
currentPage,
total,
pageSize,
onPageChange,
}) => {
const totalPages = Math.ceil(total / pageSize);
return (
<div className="mx-auto px-6 py-12 max-w-7xl">
{/* Services Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 mb-12">
{services.map((service) => (
<ServiceCard key={service.service_id} service={service} />
))}
</div>
{/* Pagination */}
{totalPages > 1 && (
<div className="flex justify-center">
<Pagination
total={totalPages}
page={currentPage}
onChange={onPageChange}
showControls
color="primary"
variant="light"
/>
</div>
)}
</div>
);
};
@@ -0,0 +1,179 @@
import { Modal, ModalContent, ModalBody, Button } from "@nextui-org/react";
import { useState, useRef, useEffect } from "react";
import { CheckIcon, XCircleIcon, ClockIcon } from "lucide-react";
import toast from "react-hot-toast";
import { useSWRConfig } from "swr";
import { useTranslation } from "react-i18next";
import { fetchAPI } from "@/shared/rpc/common-function";
interface ConfirmPurchaseModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
paymentId: string;
}
export const ConfirmPurchaseModal = ({
isOpen,
onClose,
onConfirm,
paymentId,
}: ConfirmPurchaseModalProps) => {
const { t } = useTranslation();
const [countdown, setCountdown] = useState(300); // 5 minutes in seconds
const [isLoading, setIsLoading] = useState(false);
const intervalRef = useRef<NodeJS.Timeout>();
const checkIntervalRef = useRef<NodeJS.Timeout>();
const [paymentStatus, setPaymentStatus] = useState("pending");
const { mutate } = useSWRConfig();
const checkPaymentStatus = () => {
return new Promise(async (resolve) => {
try {
const response = await fetchAPI(
`/api/payment/order_status?payment_id=${paymentId}`,
{
method: "GET",
}
);
if (response.success && response.data.status === 1) {
setPaymentStatus("completed");
clearInterval(intervalRef.current);
clearInterval(checkIntervalRef.current);
mutate("/api/user/info"); // manually trigger user info refresh
resolve(true);
}
resolve(false);
} catch (error) {
console.error("Failed to check payment status:", error);
resolve(false);
}
});
};
const handleManualConfirm = async () => {
setIsLoading(true);
const isCompleted = await checkPaymentStatus();
if (!isCompleted) {
toast.error(
t(
"Payment not completed yet. Please complete the payment before proceeding."
)
);
}
setIsLoading(false);
};
useEffect(() => {
if (isOpen) {
// start countdown
intervalRef.current = setInterval(() => {
setCountdown((prev) => {
if (prev <= 1) {
clearInterval(intervalRef.current);
clearInterval(checkIntervalRef.current);
return 0;
}
return prev - 1;
});
}, 1000);
// Check payment status every 15 seconds
checkIntervalRef.current = setInterval(checkPaymentStatus, 15000);
return () => {
clearInterval(intervalRef.current);
clearInterval(checkIntervalRef.current);
};
}
}, [isOpen]);
const formatTime = (seconds: number) => {
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
return `${mins}:${secs.toString().padStart(2, "0")}`;
};
// Add status icon components
const StatusIcon = () => {
if (paymentStatus === "completed") {
return <CheckIcon className="w-16 h-16 text-green-500" />;
} else if (countdown <= 0) {
return <XCircleIcon className="w-16 h-16 text-red-500" />;
}
return (
<div className="animate-spin">
<ClockIcon className="w-16 h-16 text-yellow-500" />
</div>
);
};
return (
<Modal isOpen={isOpen} onClose={onClose} size="md" isDismissable={false}>
<ModalContent>
<ModalBody className="p-6">
<h3 className="text-lg font-semibold mb-4">
{t("Confirm Purchase")}
</h3>
<div className="flex flex-col items-center mb-6">
<StatusIcon />
{paymentStatus === "completed" ? (
<div className="mb-6 mt-4 text-center">
<p className="text-green-500 text-sm mb-2">
{t("Payment completed")}
</p>
</div>
) : countdown > 0 ? (
<div className="text-sm text-default-500 text-center mt-4">
{t("Waiting for payment, remaining time: ") +
formatTime(countdown)}
</div>
) : (
<div className="mb-6 mt-4 text-center">
<p className="text-red-500 text-sm mb-2">
{t("Payment timeout")}
</p>
<p className="text-xs text-default-500">
{t("Please restart the payment process")}
</p>
</div>
)}
</div>
<div className="flex justify-center gap-3">
{paymentStatus === "pending" ? (
<>
<Button variant="bordered" onPress={onClose}>
{countdown > 0 ? t("Cancel") : t("Close")}
</Button>
{countdown > 0 && (
<Button
color="primary"
onPress={handleManualConfirm}
isLoading={isLoading}
>
{t("Yes, I've Paid")}
</Button>
)}
</>
) : (
<Button
onPress={onConfirm}
>
{t("Start Now!!")}
</Button>
)}
</div>
{paymentStatus === "pending" && countdown > 0 && (
<p className="text-[10px] text-default-500 mb-4 whitespace-pre-line">
{t(
"After the transaction is completed, the status will be automatically refreshed. If there is no response for a long time, you can manually click the [Yes, I've Paid] button to refresh the status."
)}
</p>
)}
</ModalBody>
</ModalContent>
</Modal>
);
};
@@ -0,0 +1,136 @@
"use client";
import React, { useState, useEffect } from "react";
import {
Modal,
ModalContent,
ModalHeader,
ModalBody,
ModalFooter,
Button,
Input,
Alert,
} from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
interface DeleteConfirmModalProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void | Promise<void>;
title?: string | React.ReactNode;
description?: string | React.ReactNode;
loading?: boolean;
requireNameConfirmation?: boolean;
confirmationName?: string;
confirmationPlaceholder?: string;
}
export const DeleteConfirmModal: React.FC<DeleteConfirmModalProps> = ({
isOpen,
onClose,
onConfirm,
title,
description,
loading = false,
requireNameConfirmation = false,
confirmationName = "",
confirmationPlaceholder,
}) => {
const { t } = useTranslation();
const [inputValue, setInputValue] = useState("");
const [isConfirmDisabled, setIsConfirmDisabled] = useState(false);
// Reset input when modal opens/closes
useEffect(() => {
if (isOpen) {
setInputValue("");
}
}, [isOpen]);
// Check if confirm button should be disabled
useEffect(() => {
if (requireNameConfirmation && confirmationName) {
setIsConfirmDisabled(inputValue.trim() !== confirmationName.trim());
} else {
setIsConfirmDisabled(false);
}
}, [inputValue, requireNameConfirmation, confirmationName]);
const handleConfirm = async () => {
if (isConfirmDisabled) return;
try {
await onConfirm();
} catch (error) {
console.error("Delete confirmation error:", error);
}
};
const defaultTitle = t("Confirm Delete");
const defaultDescription = t("Are you sure you want to delete this item? This action cannot be undone.");
return (
<Modal isOpen={isOpen} onClose={onClose} size="md">
<ModalContent>
{() => (
<>
<ModalHeader className="flex flex-col gap-1">
{title || defaultTitle}
</ModalHeader>
<ModalBody>
<div className="space-y-4">
{/* Description */}
<div className="text-default-600">
{description || defaultDescription}
</div>
{/* Warning message */}
<Alert title={t("This action cannot be undone.")} color="danger" />
{/* Name confirmation input */}
{requireNameConfirmation && confirmationName && (
<div className="space-y-2">
<p className="text-sm text-default-600">
{t('Please type "{{name}}" to confirm deletion:', {
name: confirmationName,
})}
</p>
<Input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder={confirmationPlaceholder || confirmationName}
variant="bordered"
size="sm"
isDisabled={loading}
autoFocus
/>
</div>
)}
</div>
</ModalBody>
<ModalFooter>
<Button
color="default"
variant="light"
onPress={onClose}
isDisabled={loading}
>
{t("Cancel")}
</Button>
<Button
color="danger"
onPress={handleConfirm}
isLoading={loading}
isDisabled={isConfirmDisabled}
>
{t("Delete")}
</Button>
</ModalFooter>
</>
)}
</ModalContent>
</Modal >
);
};
export default DeleteConfirmModal;
@@ -0,0 +1,157 @@
import React, { useState } from "react";
import {
Modal,
ModalContent,
ModalHeader,
ModalBody,
ModalFooter,
Button,
Input,
} from "@nextui-org/react";
import { useTranslation } from "@/shared/lib/useTranslation";
import { fetchAPI } from "@/shared/rpc/common-function";
import toast from "react-hot-toast";
import { ConfirmPurchaseModal } from "./ConfirmPurchaseModal";
interface RechargeModalProps {
isOpen: boolean;
onClose: () => void;
}
export const RechargeModal: React.FC<RechargeModalProps> = ({
isOpen,
onClose,
}) => {
const { t } = useTranslation();
const [amount, setAmount] = useState<string>("");
const [error, setError] = useState<string>("");
const [paymentId, setPaymentId] = useState("");
const [isConfirmOpen, setIsConfirmOpen] = useState(false);
const handlePurchase = async () => {
const numAmount = parseFloat(amount);
if (isNaN(numAmount) || numAmount <= 0) {
setError(t("Please enter a valid amount"));
return;
}
if (numAmount < 1) {
setError(t("Minimum recharge amount is $1"));
return;
}
const response = await fetchAPI("/api/payment/create_payment_link", {
method: "POST",
body: {
amount: numAmount,
success_url: window.location.origin + "/pay_success",
} as unknown as BodyInit,
});
if (!response.success) {
toast.error(
t(`Purchase Error:{{error_msg}}`, {
error_msg: response.error_message,
}),
{
duration: 3000,
className: "max-w-fit",
}
);
return;
}
const purchaseWindow = window.open(
response.data.pay_url,
"PurchaseWindow",
"width=600,height=600"
);
setPaymentId(response.data.payment_id);
if (!purchaseWindow) {
alert("The purchase window was blocked by the browser.");
return;
}
setIsConfirmOpen(true);
};
const handleConfirmPurchase = async (confirmed: boolean = false) => {
if (confirmed) {
//auto refresh user info
onClose();
}
setIsConfirmOpen(false);
};
const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
// only allow input numbers and decimal points
if (/^\d*\.?\d*$/.test(value) || value === "") {
setAmount(value);
setError("");
}
};
const handleClose = () => {
setAmount("");
setError("");
onClose();
};
return (
<>
<Modal isOpen={isOpen} onClose={handleClose} size="sm">
<ModalContent>
{() => (
<>
<ModalHeader className="flex flex-col gap-1">
{t("Recharge Account")}
</ModalHeader>
<ModalBody>
<Input
autoFocus
label={t("Amount")}
placeholder="0.00"
value={amount}
onChange={handleAmountChange}
startContent={
<div className="pointer-events-none flex items-center">
<span className="text-default-400 text-small">$</span>
</div>
}
type="text"
variant="bordered"
isInvalid={!!error}
errorMessage={error}
onKeyDown={(e) => {
if (e.key === "Enter") {
handlePurchase();
}
}}
/>
<p className="text-xs text-default-500">
{t("Funds will be added to your account balance")}
</p>
</ModalBody>
<ModalFooter>
<Button variant="light" onPress={handleClose}>
{t("Cancel")}
</Button>
<Button color="primary" onPress={handlePurchase}>
{t("Confirm")}
</Button>
</ModalFooter>
</>
)}
</ModalContent>
</Modal>
{/**Confirm Purchase Modal */}
<ConfirmPurchaseModal
isOpen={isConfirmOpen}
onClose={() => setIsConfirmOpen(false)}
onConfirm={handleConfirmPurchase}
paymentId={paymentId}
/>
</>
);
};
+57
View File
@@ -0,0 +1,57 @@
/**
* SSG (Static Site Generation) Configuration
*
* This file contains configuration for SSG behavior:
* - How many popular products to pre-generate
* - ISR revalidation intervals
* - Fallback behavior settings
*/
export const SSG_CONFIG = {
// Number of popular products to pre-generate at build time
// Other products will be generated on-demand with fallback
POPULAR_PRODUCTS_LIMIT: 50,
// ISR revalidation interval in seconds
// How often to check for updates and regenerate pages
REVALIDATION_INTERVAL: 3600 * 24,
// Enable fallback for non-pre-generated pages
// 'blocking' - server-side render on first request then cache
// 'true' - show loading state then hydrate
// false - 404 for non-pre-generated pages
FALLBACK_MODE: "blocking" as const,
// Cache settings
CACHE: {
// Memory cache size for ISR (0 = unlimited)
ISR_MEMORY_CACHE_SIZE: 0,
// How long to cache pages in seconds
PAGE_CACHE_TTL: 3600 * 24, // 1 day
},
} as const;
// Stand-alone constant so that pages can statically import a literal value.
// Next.js requires `export const revalidate` to reference an Identifier or literal,
// not a computed member expression.
export const REVALIDATION_INTERVAL = 86400;
/**
* Environment-specific overrides
*/
export const getSSGConfig = () => {
const env = process.env.NODE_ENV;
if (env === "development") {
return {
...SSG_CONFIG,
// In development, generate fewer pages for faster builds
POPULAR_PRODUCTS_LIMIT: 10,
// More frequent revalidation in development
REVALIDATION_INTERVAL: 10,
};
}
return SSG_CONFIG;
};
@@ -0,0 +1,51 @@
'use client';
import React, { createContext, useContext, useState, ReactNode, useEffect } from 'react';
import { PlatformConfig, PlatformConfigResponse, GoogleAuthConfig } from '@/shared/types/system';
export const _DefaultPlatformConfig: PlatformConfig = {
name: "XPack",
logo: "/static/logo/logo.png",
currency: "USD",
language: "en",
website_title: "Connect Your AI Agent to the Real World - XPack",
headline: "Connect Your AI Agent to the Real World",
subheadline: "Open‑source MCP marketplace — publish or consume APIs in minutes.",
};
interface PlatformConfigContextType {
platformConfig: PlatformConfig;
googleAuthConfig: GoogleAuthConfig | null;
updateClientConfig: (config: PlatformConfigResponse) => void;
}
const PlatformConfigContext = createContext<PlatformConfigContextType | undefined>(undefined);
interface PlatformConfigProviderProps {
children: ReactNode;
initConfig: PlatformConfigResponse;
}
export const PlatformConfigProvider: React.FC<PlatformConfigProviderProps> = ({
children,
initConfig,
}) => {
const [platformConfig, setPlatformConfig] = useState<PlatformConfig>(initConfig.platform || _DefaultPlatformConfig);
const [googleAuthConfig, setGoogleAuthConfig] = useState<GoogleAuthConfig | null>(initConfig.login?.google || null);
const updateClientConfig = (config: PlatformConfigResponse) => {
if (config.platform) setPlatformConfig(config.platform);
if (config.login?.google) setGoogleAuthConfig(config.login?.google);
};
return (
<PlatformConfigContext.Provider value={{ platformConfig, googleAuthConfig, updateClientConfig }}>
{children}
</PlatformConfigContext.Provider>
);
};
export const usePlatformConfig = () => {
const context = useContext(PlatformConfigContext);
if (context === undefined) {
throw new Error('usePlatformConfig must be used within a PlatformConfigProvider');
}
return context;
};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,19 @@
"use client";
import { useTranslation as useI18nTranslation } from "@/shared/lib/useTranslation";
import { usePlatformConfig } from "@/shared/contexts/PlatformConfigContext";
export const useTranslationWithPlatform = () => {
const { t: originalT, ...rest } = useI18nTranslation();
const { platformConfig } = usePlatformConfig();
const t = (key: string, options?: any) => {
const mergedOptions = {
platformName: platformConfig.name || "XPack",
...options,
};
return originalT(key, mergedOptions);
};
return { t, ...rest };
};
@@ -0,0 +1,309 @@
/*
* EarthPixelAnimation.ts
* An interactive particle-based Earth sphere background animation inspired by the standalone "Sphere" demo.
*
* Because this animation is used from a React Client Component we do **all** DOM / WebGL calls inside
* `initEarthPixelAnimation` and *never* on the server. A cleanup callback is returned so the caller can
* dispose ThreeJS resources when the component un-mounts.
*/
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
import { EffectComposer } from "three/examples/jsm/postprocessing/EffectComposer.js";
import { RenderPass } from "three/examples/jsm/postprocessing/RenderPass.js";
import { UnrealBloomPass } from "three/examples/jsm/postprocessing/UnrealBloomPass.js";
/** Public configuration options */
export interface EarthAnimationOptions {
/** Particle count (default 12_000) */
particleCount?: number;
/** Radius of the sphere in world units (default 12) */
radius?: number;
/** Whether user can orbit the camera (default true) */
interactive?: boolean;
/** Strength of the bloom effect (default 1.2) */
bloomStrength?: number;
background?: string;
color?: string;
colorPole?: string;
}
// Internal (default) config. We merge these with the incoming partial config.
const DEFAULT_CONFIG: Required<EarthAnimationOptions> = {
particleCount: 12000,
radius: 12,
interactive: true,
bloomStrength: 0,
background: "0x000000",
color: "#00aaff",
colorPole: "#3399ff",
};
export function initEarthPixelAnimation(
canvas: HTMLCanvasElement,
container: HTMLDivElement,
options?: EarthAnimationOptions
) {
// ---- Merge config -------------------------------------------------------
const CFG = {
...DEFAULT_CONFIG,
...(options || {}),
} as Required<EarthAnimationOptions>;
// ---- THREE.js essentials ----------------------------------------------
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x000308, 0.025);
const camera = new THREE.PerspectiveCamera(
65,
container.clientWidth / container.clientHeight,
0.1,
1000
);
camera.position.set(0, 8, 28);
scene.add(camera);
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(container.clientWidth, container.clientHeight);
renderer.setClearColor(CFG.background, 1); // 白色背景
renderer.toneMapping = THREE.NoToneMapping;
// Post-processing (bloom) -------------------------------------------------
const composer = new EffectComposer(renderer);
const renderPass = new RenderPass(scene, camera);
composer.addPass(renderPass);
const bloomPass = new UnrealBloomPass(
new THREE.Vector2(container.clientWidth, container.clientHeight),
CFG.bloomStrength,
0.55,
0.02
);
composer.addPass(bloomPass);
// Orbit controls ---------------------------------------------------------
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.autoRotate = true;
controls.autoRotateSpeed = 0.2;
controls.enableZoom = CFG.interactive;
controls.enableRotate = CFG.interactive;
// Lights -----------------------------------------------------------------
scene.add(new THREE.AmbientLight(0x404040));
const dirLight = new THREE.DirectionalLight(0xffffff, 1.2);
dirLight.position.set(10, 15, 10);
scene.add(dirLight);
// ---- Utility functions --------------------------------------------------
const tempVec = new THREE.Vector3();
function generateSpherePoints(count: number, radius: number): Float32Array {
const pts = new Float32Array(count * 3);
const golden = Math.PI * (Math.sqrt(5) - 1);
for (let i = 0; i < count; i++) {
const y = 1 - (i / (count - 1)) * 2; // from 1 to -1
const r = Math.sqrt(1 - y * y);
const theta = golden * i;
const x = Math.cos(theta) * r;
const z = Math.sin(theta) * r;
const idx = i * 3;
pts[idx] = x * radius;
pts[idx + 1] = y * radius;
pts[idx + 2] = z * radius;
}
return pts;
}
function createStarTexture(): THREE.CanvasTexture {
const size = 64;
const cvs = document.createElement("canvas");
cvs.width = size;
cvs.height = size;
const ctx = cvs.getContext("2d")!;
const gradient = ctx.createRadialGradient(
size / 2,
size / 2,
0,
size / 2,
size / 2,
size / 2
);
gradient.addColorStop(0, "rgba(255,255,255,1)");
gradient.addColorStop(0.2, "rgba(255,255,255,0.8)");
gradient.addColorStop(0.5, "rgba(255,255,255,0.3)");
gradient.addColorStop(1, "rgba(255,255,255,0)");
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, size, size);
return new THREE.CanvasTexture(cvs);
}
// ---- Particle system (Earth) -------------------------------------------
const positions = generateSpherePoints(CFG.particleCount, CFG.radius);
const sizes = new Float32Array(CFG.particleCount);
const opacities = new Float32Array(CFG.particleCount);
const colors = new Float32Array(CFG.particleCount * 3);
const colorCenter = new THREE.Color(CFG.color);
const colorPole = new THREE.Color(CFG.colorPole);
for (let i = 0; i < CFG.particleCount; i++) {
sizes[i] = THREE.MathUtils.randFloat(0.08, 0.22);
opacities[i] = 1.0;
// colouring: make poles slightly lighter
tempVec.fromArray(positions, i * 3);
const t = (tempVec.y / CFG.radius + 1) / 2; // 0..1
const c = colorCenter.clone().lerp(colorPole, t);
colors[i * 3] = c.r;
colors[i * 3 + 1] = c.g;
colors[i * 3 + 2] = c.b;
}
const geo = new THREE.BufferGeometry();
geo.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geo.setAttribute("size", new THREE.BufferAttribute(sizes, 1));
geo.setAttribute("opacity", new THREE.BufferAttribute(opacities, 1));
geo.setAttribute("color", new THREE.BufferAttribute(colors, 3));
const starTex = createStarTexture();
const mat = new THREE.ShaderMaterial({
uniforms: {
pointTexture: { value: starTex },
uTime: { value: 0 },
},
vertexShader: /* glsl */ `
attribute float size;
attribute float opacity;
varying float vOpacity;
varying vec3 vColor;
uniform float uTime;
void main() {
vOpacity = opacity;
vColor = color;
vec3 pos = position;
float n = sin(pos.x * 0.08 + uTime * 0.4) * 0.4;
pos += normalize(pos) * n; // subtle breathing
vec4 mvPosition = modelViewMatrix * vec4(pos, 1.0);
gl_PointSize = size * (400.0 / -mvPosition.z);
gl_Position = projectionMatrix * mvPosition;
}`,
fragmentShader: /* glsl */ `
uniform sampler2D pointTexture;
varying float vOpacity;
varying vec3 vColor;
void main() {
vec4 texColor = texture2D(pointTexture, gl_PointCoord);
if (texColor.a < 0.05) discard;
gl_FragColor = vec4(vColor, vOpacity * texColor.a);
}`,
blending: THREE.NormalBlending,
depthWrite: false,
transparent: true,
vertexColors: true,
});
const particles = new THREE.Points(geo, mat);
scene.add(particles);
// ---- Star field ---------------------------------------------------------
function addStarField(count = 14000) {
const starPos: number[] = [];
const starSizeArr: number[] = [];
const starColorArr: number[] = [];
for (let i = 0; i < count; i++) {
tempVec.set(
THREE.MathUtils.randFloatSpread(600),
THREE.MathUtils.randFloatSpread(600),
THREE.MathUtils.randFloatSpread(600)
);
if (tempVec.length() < 150) tempVec.setLength(150 + Math.random() * 450);
starPos.push(tempVec.x, tempVec.y, tempVec.z);
starSizeArr.push(Math.random() * 0.25 + 0.1);
const twinkle = Math.random() < 0.15;
const c = new THREE.Color();
if (twinkle) c.setHSL(Math.random(), 0.7, 0.65);
else c.setHSL(0.6, Math.random() * 0.1, 0.8 + Math.random() * 0.2);
starColorArr.push(c.r, c.g, c.b);
}
const starGeo = new THREE.BufferGeometry();
starGeo.setAttribute(
"position",
new THREE.Float32BufferAttribute(starPos, 3)
);
starGeo.setAttribute(
"size",
new THREE.Float32BufferAttribute(starSizeArr, 1)
);
starGeo.setAttribute(
"color",
new THREE.Float32BufferAttribute(starColorArr, 3)
);
const starMat = new THREE.ShaderMaterial({
uniforms: { pointTexture: { value: starTex } },
vertexShader: /* glsl */ `
attribute float size; varying vec3 vColor; void main() {
vColor = color;
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
gl_PointSize = size * (400.0 / -mvPosition.z);
gl_Position = projectionMatrix * mvPosition;
}`,
fragmentShader: /* glsl */ `
uniform sampler2D pointTexture; varying vec3 vColor; void main() {
float a = texture2D(pointTexture, gl_PointCoord).a; if (a < 0.1) discard;
gl_FragColor = vec4(vColor, a * 0.8);
}`,
blending: THREE.AdditiveBlending,
depthWrite: false,
transparent: true,
vertexColors: true,
});
const starPts = new THREE.Points(starGeo, starMat);
scene.add(starPts);
}
addStarField();
// ---- Resize handling ----------------------------------------------------
function onResize() {
camera.aspect = container.clientWidth / container.clientHeight;
camera.updateProjectionMatrix();
renderer.setSize(container.clientWidth, container.clientHeight);
composer.setSize(container.clientWidth, container.clientHeight);
}
window.addEventListener("resize", onResize);
// ---- Animation loop -----------------------------------------------------
const clock = new THREE.Clock();
let rafId: number;
function animate() {
rafId = requestAnimationFrame(animate);
const elapsed = clock.getElapsedTime();
mat.uniforms.uTime.value = elapsed;
controls.update();
composer.render();
}
animate();
// ---- Cleanup ------------------------------------------------------------
return () => {
cancelAnimationFrame(rafId);
window.removeEventListener("resize", onResize);
controls.dispose();
renderer.dispose();
geo.dispose();
mat.dispose();
starTex.dispose();
};
}
@@ -0,0 +1,274 @@
// Pixel class for animation
export class Pixel {
x: number;
y: number;
color: string;
speed: number;
size: number;
sizeStep: number;
minSize: number;
maxSizeAvailable: number;
maxSize: number;
sizeDirection: number;
delay: number;
delayHide: number;
counter: number;
counterHide: number;
counterStep: number;
isHidden: boolean;
isFlicking: boolean;
constructor(
x: number,
y: number,
color: string,
speed: number,
delay: number,
delayHide: number,
step: number,
boundSize: number
) {
this.x = x;
this.y = y;
this.color = color;
this.speed = rand(0.1, 0.9) * speed;
this.size = 0;
this.sizeStep = rand(0, 0.5);
this.minSize = 0.5;
this.maxSizeAvailable = boundSize || 2;
this.maxSize = rand(this.minSize, this.maxSizeAvailable);
this.sizeDirection = 1;
this.delay = delay;
this.delayHide = delayHide;
this.counter = 0;
this.counterHide = 0;
this.counterStep = step;
this.isHidden = false;
this.isFlicking = false;
}
draw(ctx: CanvasRenderingContext2D) {
const centerOffset = this.maxSizeAvailable * 0.5 - this.size * 0.5;
ctx.fillStyle = this.color;
ctx.fillRect(
this.x + centerOffset,
this.y + centerOffset,
this.size,
this.size
);
}
show() {
this.isHidden = false;
this.counterHide = 0;
if (this.counter <= this.delay) {
this.counter += this.counterStep;
return;
}
if (this.size >= this.maxSize) {
this.isFlicking = true;
}
if (this.isFlicking) {
this.flicking();
} else {
this.size += this.sizeStep;
}
}
hide() {
this.counter = 0;
if (this.counterHide <= this.delayHide) {
this.counterHide += this.counterStep;
if (this.isFlicking) {
this.flicking();
}
return;
}
this.isFlicking = false;
if (this.size <= 0) {
this.size = 0;
this.isHidden = true;
return;
} else {
this.size -= 0.05;
}
}
flicking() {
if (this.size >= this.maxSize) {
this.sizeDirection = -1;
} else if (this.size <= this.minSize) {
this.sizeDirection = 1;
}
this.size += this.sizeDirection * this.speed;
}
}
// Utility functions
export const rand = (min: number, max: number) => {
return Math.random() * (max - min) + min;
};
export const getDelay = (
x: number,
y: number,
width: number,
height: number,
direction?: boolean
) => {
let dx = x - width * 0.5;
let dy = y - height;
if (direction) {
dy = y;
}
return Math.sqrt(dx ** 2 + dy ** 2);
};
interface PixelAnimationOptions {
hueRange?: [number, number]; // Min and max hue values
gap?: number; // Gap between pixels
speed?: [number, number]; // Min and max speed values
colorsLen?: number; // Number of colors to generate
}
export const initPixelsAnimation = (
canvas: HTMLCanvasElement,
container: HTMLDivElement,
options?: PixelAnimationOptions
) => {
const ctx = canvas.getContext("2d");
if (!ctx) return null;
const opts = {
hueRange: options?.hueRange || [200, 280], // Blue-ish hue range by default
gap: options?.gap || 6,
speed: options?.speed || [0.008, 0.25],
colorsLen: options?.colorsLen || 5,
};
const interval = 1000 / 60;
let width = 0;
let height = 0;
let pixels: Pixel[] = [];
let lastTime = 0;
let ticker = 0;
let maxTicker = 360;
let animationDirection = 1;
let animationRef: number = 0;
const initPixels = () => {
const h = Math.floor(rand(opts.hueRange[0], opts.hueRange[1]));
const colorsLen = opts.colorsLen;
const colors = Array.from(
{ length: colorsLen },
(_, index) =>
`hsl(${Math.floor(rand(h, h + (index + 1) * 10))} 100% ${rand(50, 100)}%)`
);
const gap = opts.gap;
const step = (width + height) * 0.005;
const speed = rand(opts.speed[0], opts.speed[1]);
const maxSize = Math.floor(gap * 0.5);
pixels = [];
for (let x = 0; x < width; x += gap) {
for (let y = 0; y < height; y += gap) {
if (x + maxSize > width || y + maxSize > height) {
continue;
}
const color = colors[Math.floor(Math.random() * colorsLen)];
const delay = getDelay(x, y, width, height);
const delayHide = getDelay(x, y, width, height);
pixels.push(
new Pixel(x, y, color, speed, delay, delayHide, step, maxSize)
);
}
}
};
const animate = () => {
const now = performance.now();
const diff = now - (lastTime || 0);
if (diff < interval) {
animationRef = requestAnimationFrame(animate);
return;
}
lastTime = now - (diff % interval);
ctx.clearRect(0, 0, width, height);
if (ticker >= maxTicker) {
animationDirection = -1;
} else if (ticker <= 0) {
animationDirection = 1;
}
let allHidden = true;
pixels.forEach((pixel) => {
if (animationDirection > 0) {
pixel.show();
} else {
pixel.hide();
allHidden = allHidden && pixel.isHidden;
}
pixel.draw(ctx);
});
ticker += animationDirection;
if (animationDirection < 0 && allHidden) {
ticker = 0;
}
animationRef = requestAnimationFrame(animate);
};
const resize = () => {
if (!canvas || !container) return;
const rect = container.getBoundingClientRect();
width = Math.floor(rect.width);
height = Math.floor(rect.height);
canvas.width = width;
canvas.height = height;
initPixels();
ticker = 0;
};
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(container);
resize();
animate();
// Return cleanup function
return () => {
cancelAnimationFrame(animationRef);
resizeObserver.disconnect();
};
};
+62
View File
@@ -0,0 +1,62 @@
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import Backend from "i18next-http-backend";
import { getDefaultLanguage } from "@/shared/utils/i18n";
import en from "../../../public/locales/en/translation.json";
import enConfig from "../../../public/locales/en/config.json";
import zhCN from "../../../public/locales/zh-CN/translation.json";
import zhCNConfig from "../../../public/locales/zh-CN/config.json";
// Try to read the preferred language from multiple sources:
// 1. URL parameters (lang=zh-CN)
// 2. localStorage (both i18next and XPack_Shared)
// 3. Browser language
// Falls back to browser language detection without hardcoding defaults
const DEFAULT_LANGUAGE = getDefaultLanguage();
const SUPPORTED_LANGUAGES = [
{ name: "en", label: "English" },
{ name: "zh-CN", label: "中文" },
];
export const i18nPromise = i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources: {
en: { translation: en, config: enConfig },
"zh-CN": { translation: zhCN, config: zhCNConfig },
},
ns: ["translation", "config"],
defaultNS: "translation",
fallbackNS: "config",
lng: DEFAULT_LANGUAGE,
fallbackLng: DEFAULT_LANGUAGE, // use dynamically detected language as fallback
supportedLngs: SUPPORTED_LANGUAGES.map((lang) => lang.name),
// preload resources to reduce switching delay
preload: SUPPORTED_LANGUAGES.map((lang) => lang.name),
interpolation: {
escapeValue: false,
},
detection: {
// optimize detection order, prioritize localStorage
order: ["localStorage", "navigator", "htmlTag"],
caches: ["localStorage"],
lookupLocalStorage: "i18nextLng", // use standard i18next localStorage key
},
react: {
useSuspense: false, // Important for Next.js SSR
bindI18n: "languageChanged loaded", // bind more events to ensure timely update
bindI18nStore: "added removed",
},
// debug config (can be closed in production)
debug: false,
});
export { DEFAULT_LANGUAGE, SUPPORTED_LANGUAGES };
export default i18n;
+110
View File
@@ -0,0 +1,110 @@
import { useState, useEffect, useCallback } from "react";
import { useSharedStore } from "../store/share";
export const useAuth = () => {
// 从 Zustand store 获取状态
const {
user_token,
user,
preference,
setUserToken,
setUser,
updatePreference,
} = useSharedStore();
const [isLoading, setIsLoading] = useState(true);
// 计算派生状态
const isLoggedIn = !!(user_token && user);
// 初始化时恢复持久化状态
useEffect(() => {
const initializeAuth = async () => {
try {
// 确保 Zustand persist 已经 rehydrate
if (typeof window !== "undefined" && useSharedStore.persist) {
// 等待持久化状态恢复
await new Promise((resolve) => {
const unsubscribe = useSharedStore.persist!.onFinishHydration(
() => {
unsubscribe();
resolve(void 0);
}
);
});
}
} catch (error) {
console.warn("Error initializing auth:", error);
} finally {
setIsLoading(false);
}
};
initializeAuth();
}, []);
const handleLogin = useCallback(() => {
const domain =
process.env.NEXT_PUBLIC_DOMAIN ||
(typeof window !== "undefined" ? window.location.origin : "");
if (isLoggedIn) {
window.location.href = `${domain}/dashboard`;
} else {
window.location.href = `${domain}/signin`;
}
}, [isLoggedIn]);
const handleLogout = useCallback(() => {
// 清理 Zustand store 中的认证数据
setUserToken("");
setUser(null);
// 清理可能残留的旧localStorage数据
if (typeof window !== "undefined") {
const keysToClean = ["user_token", "share-storage", "preference"];
keysToClean.forEach((key) => {
try {
localStorage.removeItem(key);
} catch (error) {
console.warn(`Error cleaning ${key}:`, error);
}
});
}
}, [setUserToken, setUser]);
// 监听跨标签页的状态变化(Zustand persist会自动处理)
useEffect(() => {
// Zustand的persist中间件已经处理了storage事件监听
// 这里只需要监听我们自己可能需要的额外逻辑
}, []);
// 刷新认证状态(主要用于强制重新检查)
const refreshAuth = useCallback(() => {
// 触发Zustand store重新hydrate
if (typeof window !== "undefined" && useSharedStore.persist) {
useSharedStore.persist.rehydrate();
}
}, []);
return {
// 认证状态
isLoggedIn,
user,
userToken: user_token,
isLoading,
// 用户偏好(直接从store获取)
preference,
// 操作方法
handleLogin,
handleLogout,
refreshAuth,
updatePreference,
// 直接暴露store方法以便其他组件使用
setUser,
setUserToken,
};
};
+18
View File
@@ -0,0 +1,18 @@
"use client";
import { useTranslation as useI18nextTranslation } from "react-i18next";
export const useTranslation = () => {
const { t, i18n, ready } = useI18nextTranslation();
const translate = (key: string, options?: any): string => {
const result = t(key, options);
return typeof result === "string" ? result : key;
};
return {
t: translate,
i18n,
ready,
};
};
@@ -0,0 +1,10 @@
"use client";
import { NextUIProvider } from "@nextui-org/react";
import { useRouter } from "next/navigation";
export function Providers({ children }: { children: React.ReactNode }) {
const router = useRouter();
return <NextUIProvider navigate={router.push}>{children}</NextUIProvider>;
}
+25
View File
@@ -0,0 +1,25 @@
import { SourceType } from "../types";
export const SOURCE_TYPE = SourceType.SSG;
// Define base URLs for API requests
export const API_BASE_URL =
process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8100";
// Helper function for constructing API URLs
export const getApiUrl = (endpoint: string) => {
//if window is undefined, it means it's server side, so we need to use the API_BASE_URL
if (
typeof window === "undefined" &&
(endpoint.startsWith("/v1/") || endpoint.startsWith("/api/"))
) {
return `${API_BASE_URL}${endpoint}`;
}
return endpoint;
};
export const getURL = (url: string) => {
if (url.startsWith("http")) return url;
if (process.env.NEXT_PUBLIC_STATIC_URL_PREFIX)
return process.env.NEXT_PUBLIC_STATIC_URL_PREFIX + url;
return url;
};
@@ -0,0 +1,65 @@
import { useSharedStore } from "../store/share";
import { ApiResponse } from "../types";
import { getApiUrl } from "./adapter";
const getAuth = () => {
//? window.localStorage.get('user_token') prevent extension includeChromeStore asynchrounous problem
return (
useSharedStore?.getState?.()?.user_token ||
(typeof window !== "undefined"
? window.localStorage.getItem("user_token")
: "")
);
};
/**
* Simplified fetch API for SSG application
*/
export const fetchAPI = async <T = any>(
url: string,
options: RequestInit = {}
): Promise<ApiResponse<T>> => {
try {
// Add default headers
options.headers = {
"Content-Type": "application/json",
// Prevent potential "Ill-formed language" errors by ensuring a valid default language tag
"Accept-Language": "en-US,en;q=0.9",
Authorization: getAuth() || undefined,
...(typeof window === "undefined"
? {
noCache: true,
}
: {}),
...(options.headers || {}),
} as any;
// Process JSON body
if (options.body && typeof options.body === "object") {
options.body = JSON.stringify(options.body);
}
const response = await fetch(getApiUrl(url), options);
const contentType = response.headers.get("Content-Type");
// Parse response based on content type
if (contentType?.includes("application/json")) {
const result = await response.json();
return result;
} else {
// Default fallback if not JSON
return {
success: response.ok,
code: response.status.toString(),
error_message: response.ok ? undefined : response.statusText,
data: null as T,
};
}
} catch (error) {
console.error("API fetch error:", error);
return {
success: false,
code: "ERROR",
error_message: error instanceof Error ? error.message : "Unknown error",
data: null as T,
};
}
};
+29
View File
@@ -0,0 +1,29 @@
interface APIKey {
name: string;
apikey: string;
create_time: number;
apikey_id: string;
}
export interface User {
user_id: string;
user_email: string;
user_name: string;
avatar?: string;
nick_name?: string;
language: NavigatorLanguage | "en" | "zh-CN";
/**
* subscription
*/
subscription?: {
wallet: number;
save_money: number;
package_level?: "free" | "enterprise" | "pro" | "max" | "ultra";
payment_status?: 0 | 1;
start_time?: number;
end_time?: number;
};
apikeys: APIKey[];
wallet?: {
balance: number;
};
}
+130
View File
@@ -0,0 +1,130 @@
import { createWithEqualityFn } from "zustand/traditional";
import useSWR, { SWRResponse } from "swr";
import { ApiResponse } from "../types";
import {
createJSONStorage,
devtools,
persist,
subscribeWithSelector,
} from "zustand/middleware";
import { fetchAPI } from "../rpc/common-function";
import { shallow } from "zustand/shallow";
import { useSharedStore } from "./share";
export const StorageGlobalName = "XPack_Global";
export type GlobalStore = {
/**
* For google analytics, if user is first time login
*/
isNewUser: boolean;
setIsNewUser: (isNewUser: boolean) => void;
getUser: () => Promise<ApiResponse>;
useGetUser: () => SWRResponse<any, any>;
logOut: () => void;
};
export const useGlobalStore = createWithEqualityFn<GlobalStore>()(
persist(
subscribeWithSelector(
devtools(
(set, get): GlobalStore => ({
isNewUser: false,
setIsNewUser: (isNewUser: boolean) => set({ isNewUser }),
getUser: async () => {
const { setUser } = useSharedStore.getState();
const res = await fetchAPI("/api/user/info");
if (res.success) {
setUser(res.data);
}
return res;
},
useGetUser: () => {
const { logOut } = get();
return useSWR(`/api/user/info`, async (url: string) => {
const { user_token, setUser } = useSharedStore.getState();
if (!user_token) {
console.warn(
"call user api before user_token is set, system will log out!"
);
setUser(null);
return { success: false };
}
const res = await fetchAPI(url, {
method: "GET",
});
if (!res) {
return { success: false };
}
if (!res?.success) {
logOut();
return res;
}
setUser(res.data);
return res;
});
},
logOut: () => {
const { setUserToken, setUser } = useSharedStore.getState();
try {
// 退出登录,异步处理
fetchAPI("/api/auth/logout", {
method: "DELETE",
});
} catch (e) {
console.error("ajax log out error", e);
}
// Logout return
setUserToken("");
setUser(null);
// 清理本地存储
try {
if (typeof window !== "undefined") {
const global = JSON.parse(
localStorage.getItem(StorageGlobalName) || "{}"
).state;
if (global) {
delete global.preference;
delete global.user_token;
delete global.user;
localStorage.setItem(
StorageGlobalName,
JSON.stringify({ state: global })
);
}
}
} catch (e) {
console.error("log out error", e);
}
},
})
)
),
{
name: StorageGlobalName,
storage: createJSONStorage(() => {
// SSG 安全:服务端返回一个mock storage
if (typeof window === "undefined") {
return {
getItem: () => null,
setItem: () => {},
removeItem: () => {},
};
}
return localStorage;
}),
skipHydration: typeof window === "undefined", // 服务端跳过hydration
}
),
shallow
);
// SSG hydration 安全函数
export const initializeGlobalStore = () => {
if (typeof window !== "undefined" && useGlobalStore.persist) {
// 客户端 hydration 后手动恢复持久化状态
useGlobalStore.persist.rehydrate();
}
};
+158
View File
@@ -0,0 +1,158 @@
import { User } from "./User";
import { createWithEqualityFn } from "zustand/traditional";
import { produce } from "immer";
import { shallow } from "zustand/shallow";
import {
createJSONStorage,
devtools,
persist,
subscribeWithSelector,
} from "zustand/middleware";
import { StateCreator } from "zustand";
import { getDefaultLanguage } from "@/shared/utils/i18n";
const _StorageKey = "XPack_Shared";
export interface GlobalPreference {
/**
* whether to generate image for chat message
*/
generate_image: boolean;
language: "zh-CN" | "en" | string;
theme: "dark" | "light" | "system";
inputHeight: number;
/**
* whether to use cmd + enter to send message
*/
useCmdEnterToSend?: boolean;
/**
* whether to hide more tips in welcome page
*/
hideMoreTips?: boolean;
/**
* Session panel width
*/
sessionsWidth: number;
showWebTool: boolean;
showWebCopilot: boolean;
webIconTop: number | undefined;
showIntendTips: boolean;
showRightPanel: boolean;
showLeftPanel?: boolean;
[key: string]: any;
}
export enum CategoryType {
Show = 1,
Edit = 2,
}
export interface IdentityInfo {
category: string;
category_type: number;
identity: string;
identity_type: number;
}
interface GlobalConfig {
hover_recommend: boolean;
max_file_size: number;
max_context_message_count: number;
discount: number;
max_bot_description: number;
category: { label: string; value: number; type: CategoryType }[];
max_token: number;
identity_infos: IdentityInfo[];
}
interface SharedStore {
user_token: string | null;
setUserToken: (user_token: string) => void;
user: null | User;
setUser: (user: User | null) => void;
preference: GlobalPreference;
updatePreference: (preference: Partial<GlobalPreference>) => void;
getPreferenceByKey: (key?: string) => any;
config: GlobalConfig;
setConfig: (config: GlobalConfig) => void;
}
const fn: StateCreator<SharedStore, []> = (set) => {
const storage =
(createJSONStorage(() => localStorage)?.getItem(_StorageKey) as any)
?.state || {};
return {
config: storage.config || {
hover_recommend: false,
category: [],
discount: 100,
model: "gpt-4-turbo-preview",
max_bot_description: 1000,
max_context_message_count: 10,
max_file_size: 500 * 1024 * 1024,
max_token: 4000,
identity_infos: [],
},
setConfig: (config: GlobalConfig) => set({ config }),
/**
* Unique client id,for google analytics
*
* This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
* https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
*/
user_token: storage.user_token || null,
setUserToken: (user_token: string) => {
if (!user_token) {
console.warn("for debugger tips: user_token has been set empty!");
}
set({ user_token });
},
getPreferenceByKey: (key?: string) => {
const preference =
JSON.parse(window.localStorage.getItem("preference") || "{}") ||
useSharedStore?.getState?.()?.preference;
return key ? preference[key] : preference;
},
user: storage.user || null,
setUser: (user) => set({ user }),
preference: storage.preference || {
model: "",
generate_image: false,
language: getDefaultLanguage(),
theme: "system",
inputHeight: 100,
useCmdEnterToSend: false,
hideMoreTips: false,
sessionsWidth: 320,
showWebTool: true,
showWebCopilot: true,
webIconTop: undefined,
showIntendTips: true,
showRightPanel: false,
showLeftPanel: undefined,
},
updatePreference: (preference) => {
set(
produce((draft: SharedStore) => {
draft.preference = {
...draft.preference,
...preference,
};
}),
false
);
// Sidepanel use localStorage to store user_token for backup
},
};
};
export const useSharedStore = createWithEqualityFn<SharedStore>()(
persist(subscribeWithSelector(devtools(fn)), {
name: _StorageKey,
storage: createJSONStorage(() => localStorage),
}),
shallow
);
+6
View File
@@ -0,0 +1,6 @@
export interface APIKey {
apikey_id: string;
name: string;
apikey: string;
create_time: number;
}
+25
View File
@@ -0,0 +1,25 @@
export type TabKey =
| "console"
| "mcp-services"
| "user-management"
| "revenue-management"
| "payment-channels"
| "system-settings"
| "overview"
| "wallet"
| "account";
export interface SidebarItem {
key: TabKey;
icon: React.ReactNode;
label: string;
description: string;
}
export interface DashboardSidebarProps {
activeTab: TabKey;
onTabNavigate?: (tab: TabKey) => void;
onLogout: () => void;
sidebarItems: SidebarItem[];
userProfilePanel?: React.ReactNode;
}
+37
View File
@@ -0,0 +1,37 @@
export enum SourceType {
ContentPanel = "ContentPanel",
WebTool = "WebTool",
SSG = "SSG",
}
// 基础API响应接口
export interface BaseApiResponse {
code: string;
error_message?: string;
success: boolean;
}
// 数组响应接口 (用于列表接口)
export interface ApiArrayResponse<T = any> extends BaseApiResponse {
data: T[];
page: {
page: number;
page_size: number;
total: number;
};
}
// 对象响应接口 (用于单个对象接口)
export interface ApiObjectResponse<T = any> extends BaseApiResponse {
data: T;
}
// 通用API响应接口 (保持向后兼容)
export interface ApiResponse<T = any> extends BaseApiResponse {
data: T;
page?: {
page: number;
page_size: number;
total: number;
};
}
+22
View File
@@ -0,0 +1,22 @@
export interface ServiceData {
name: string;
service_id: string;
tools: ToolData[];
long_description?: string;
short_description?: string;
slug_name?: string;
tags?: string[];
price?: string;
charge_type?: ChargeType;
}
export interface ToolData {
name: string;
description?: string;
}
export enum ChargeType {
Free = "free",
PerCall = "per_call",
PerToken = "per_token",
}
+25
View File
@@ -0,0 +1,25 @@
export interface PlatformConfig {
logo?: string; // platform logo url
name: string; // platform name
currency?: string; // currency unit, e.g. 'USD', 'CNY', 'EUR'
language?: string; // platform language, default 'en'
website_title?: string; // website title
headline?: string; // homepage headline
subheadline?: string; // homepage subheadline
}
export interface PlatformConfigResponse {
platform: PlatformConfig;
login?: {
google?: {
client_id: string;
is_enabled: boolean;
};
};
}
// google auth config
export interface GoogleAuthConfig {
client_id: string; // Google Client ID
client_secret?: string; // Google Client Secret (optional, for server-side validation)
is_enabled: boolean; // whether to enable google login
}
+49
View File
@@ -0,0 +1,49 @@
/**
* @description common copy to clipboard
* support https and non-https environment
*/
export interface CopyResult {
success: boolean;
error?: string;
}
/**
* @description copy text to clipboard
* @param text text to copy
* @returns Promise<CopyResult> copy result
*/
export const copyToClipboard = async (text: string): Promise<CopyResult> => {
try {
// first try to use modern clipboard api (need https)
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(text);
return { success: true };
}
// fallback: use document.execCommand (for non-https environment)
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed";
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const successful = document.execCommand("copy");
document.body.removeChild(textArea);
if (successful) {
return { success: true };
} else {
throw new Error("execCommand failed");
}
} catch (error) {
console.error("Copy failed:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error",
};
}
};
+10
View File
@@ -0,0 +1,10 @@
import CryptoJS from "crypto-js";
/**
* MD5 encrypt function
* @param text text to encrypt
* @returns MD5 encrypted string
*/
export const md5Encrypt = (text: string): string => {
return CryptoJS.MD5(text).toString();
};
+172
View File
@@ -0,0 +1,172 @@
/**
* 货币格式化工具函数
*/
export interface CurrencyFormatOptions {
minimumFractionDigits?: number;
maximumFractionDigits?: number;
showSymbol?: boolean;
}
/**
* 格式化货币金额
* @param amount 金额(数字)
* @param currency 货币代码,如 'USD', 'CNY', 'EUR'
* @param options 格式化选项
* @returns 格式化后的货币字符串
*/
export const formatCurrency = (
amount: number | undefined | null,
currency: string = 'USD',
options: CurrencyFormatOptions = {}
): string => {
// 处理无效值
if (amount === undefined || amount === null || isNaN(amount)) {
return '0.00';
}
const {
minimumFractionDigits = 2,
maximumFractionDigits = 2,
showSymbol = true
} = options;
try {
if (showSymbol) {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency,
minimumFractionDigits,
maximumFractionDigits
}).format(amount);
} else {
return amount.toLocaleString('en-US', {
minimumFractionDigits,
maximumFractionDigits
});
}
} catch (error) {
// 如果货币代码无效,回退到基本格式化
console.warn(`Invalid currency code: ${currency}, falling back to basic formatting`);
return amount.toLocaleString('en-US', {
minimumFractionDigits,
maximumFractionDigits
});
}
};
/**
* 格式化价格(以分为单位转换为元)
* @param priceInCents 以分为单位的价格
* @param currency 货币代码
* @param options 格式化选项
* @returns 格式化后的价格字符串
*/
export const formatPrice = (
priceInCents: number | undefined | null,
currency: string = 'USD',
options: CurrencyFormatOptions = {}
): string => {
if (priceInCents === undefined || priceInCents === null || isNaN(priceInCents)) {
return formatCurrency(0, currency, options);
}
const priceInDollars = priceInCents / 100;
return formatCurrency(priceInDollars, currency, options);
};
/**
* 获取货币符号
* @param currency 货币代码
* @returns 货币符号
*/
export const getCurrencySymbol = (currency: string = 'USD'): string => {
try {
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency,
minimumFractionDigits: 0,
maximumFractionDigits: 0
});
// 格式化0并提取符号
const formatted = formatter.format(0);
return formatted.replace(/[\d\s,]/g, '');
} catch (error) {
// 回退到常见货币符号
const symbols: Record<string, string> = {
'USD': '$',
'EUR': '€',
'GBP': '£',
'JPY': '¥',
'CNY': '¥',
'KRW': '₩'
};
return symbols[currency] || '$';
}
};
/**
* 格式化余额显示
* @param balance 余额
* @param currency 货币代码
* @returns 格式化后的余额字符串
*/
export const formatBalance = (
balance: number | undefined | null,
currency: string = 'USD'
): string => {
return formatCurrency(balance, currency, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
};
/**
* 货币选项接口
*/
export interface CurrencyOption {
value: string;
label: string;
symbol: string;
}
/**
* 获取支持的货币选项列表
* @returns 货币选项数组
*/
export const getCurrencyOptions = (): CurrencyOption[] => {
return [
{ value: 'USD', label: 'US Dollar (USD)', symbol: '$' },
{ value: 'EUR', label: 'Euro (EUR)', symbol: '€' },
{ value: 'GBP', label: 'British Pound (GBP)', symbol: '£' },
{ value: 'JPY', label: 'Japanese Yen (JPY)', symbol: '¥' },
{ value: 'CNY', label: 'Chinese Yuan (CNY)', symbol: '¥' },
{ value: 'KRW', label: 'Korean Won (KRW)', symbol: '₩' },
{ value: 'CAD', label: 'Canadian Dollar (CAD)', symbol: 'C$' },
{ value: 'AUD', label: 'Australian Dollar (AUD)', symbol: 'A$' },
{ value: 'CHF', label: 'Swiss Franc (CHF)', symbol: 'CHF' },
{ value: 'SEK', label: 'Swedish Krona (SEK)', symbol: 'kr' },
{ value: 'NOK', label: 'Norwegian Krone (NOK)', symbol: 'kr' },
{ value: 'DKK', label: 'Danish Krone (DKK)', symbol: 'kr' },
{ value: 'PLN', label: 'Polish Zloty (PLN)', symbol: 'zł' },
{ value: 'CZK', label: 'Czech Koruna (CZK)', symbol: 'Kč' },
{ value: 'HUF', label: 'Hungarian Forint (HUF)', symbol: 'Ft' },
{ value: 'RUB', label: 'Russian Ruble (RUB)', symbol: '₽' },
{ value: 'BRL', label: 'Brazilian Real (BRL)', symbol: 'R$' },
{ value: 'MXN', label: 'Mexican Peso (MXN)', symbol: '$' },
{ value: 'INR', label: 'Indian Rupee (INR)', symbol: '₹' },
{ value: 'SGD', label: 'Singapore Dollar (SGD)', symbol: 'S$' },
{ value: 'HKD', label: 'Hong Kong Dollar (HKD)', symbol: 'HK$' },
{ value: 'TWD', label: 'Taiwan Dollar (TWD)', symbol: 'NT$' },
{ value: 'THB', label: 'Thai Baht (THB)', symbol: '฿' },
{ value: 'MYR', label: 'Malaysian Ringgit (MYR)', symbol: 'RM' },
{ value: 'IDR', label: 'Indonesian Rupiah (IDR)', symbol: 'Rp' },
{ value: 'PHP', label: 'Philippine Peso (PHP)', symbol: '₱' },
{ value: 'VND', label: 'Vietnamese Dong (VND)', symbol: '₫' },
{ value: 'ZAR', label: 'South African Rand (ZAR)', symbol: 'R' },
{ value: 'TRY', label: 'Turkish Lira (TRY)', symbol: '₺' },
{ value: 'AED', label: 'UAE Dirham (AED)', symbol: 'د.إ' },
{ value: 'SAR', label: 'Saudi Riyal (SAR)', symbol: '﷼' }
];
};
+70
View File
@@ -0,0 +1,70 @@
const STORAGE_KEY = "XPack_Shared";
const getUrlLanguage = (): string | null => {
if (typeof window === "undefined") return null;
const urlParams = new URLSearchParams(window.location.search);
const langParam = urlParams.get("lang") || urlParams.get("locale");
if (langParam && ["en", "zh-CN"].includes(langParam)) {
return langParam;
}
return null;
};
const getBrowserDefaultLanguage = (): string => {
if (typeof window === "undefined") {
// SSR时根据Accept-Language header判断,这里先返回英语
return "en";
}
const browserLang = navigator.language;
const supportedLanguages: string[] = ["en", "zh-CN"];
// 尝试完全匹配
if (supportedLanguages.includes(browserLang)) {
return browserLang;
}
// 尝试匹配语言代码前缀(如 zh-CN 匹配 zh)
const langPrefix = browserLang.split("-")[0];
const match = supportedLanguages.find((lang) => lang.startsWith(langPrefix));
return match || "en"; // 最后才fallback到英语
};
export const getDefaultLanguage = (): string => {
// 1. 优先检查URL参数
const urlLang = getUrlLanguage();
if (urlLang) {
return urlLang;
}
if (typeof window === "undefined") {
return getBrowserDefaultLanguage();
}
try {
// 2. 检查i18next的localStorage缓存
const i18nextLng = localStorage.getItem("i18nextLng");
if (i18nextLng && ["en", "zh-CN"].includes(i18nextLng)) {
return i18nextLng;
}
// 3. 检查Zustand store中的语言设置
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) {
const parsed = JSON.parse(raw).state?.preference;
if (parsed?.language && typeof parsed.language === "string") {
return parsed.language;
}
}
} catch (error) {
// eslint-disable-next-line no-console
console.warn("Failed to parse language from localStorage", error);
}
// 4. 最后使用浏览器语言检测
return getBrowserDefaultLanguage();
};
+57
View File
@@ -0,0 +1,57 @@
// Utility functions related to Model Context Protocol (MCP)
/**
* Sanitises a user-provided Agent name so that it can safely be used as an
* MCP server identifier.
*
* Rules (derived from MCP spec and common conventions):
* 1. Lower-case alphanumeric characters, hyphen (-) and underscore (_)
* 2. Cannot start with a digit or hyphen – if it does, we prefix with "mcp-".
* 3. Consecutive illegal characters are collapsed into a single hyphen.
* 4. Empty or fully sanitised away strings fallback to "xpack-mcp-service".
*/
export function sanitizeMCPServerName(rawName: string | undefined): string {
if (!rawName) return "xpack-mcp-service";
// Lower-case & replace invalid chars with hyphen
let name = rawName
.trim()
.toLowerCase()
.replace(/[^a-z0-9-_]+/g, "-");
// Collapse multiple hyphens
name = name.replace(/-+/g, "-");
// Trim leading/trailing hyphens
name = name.replace(/^-+/, "").replace(/-+$/, "");
// Ensure it doesn't start with a digit or empty
if (!name || !/^(xpack-)/.test(name)) {
name = `xpack-${name}`;
}
return name || "xpack-mcp-service";
}
/**
* Generates a complete MCP configuration JSON string for a given API key & agent.
*
* @param key The raw API key returned from backend.
* @param name The human-friendly Agent name.
* @returns A pretty-printed JSON string that can be used directly in config files.
*/
export function generateMCPConfig(key: string, name?: string): string {
const sanitizedName = sanitizeMCPServerName(name);
const baseUrl = `${process.env.NEXT_PUBLIC_MCP_URL}?apikey=${key}`;
const mcpConfig = {
mcpServers: {
[sanitizedName]: {
type: "sse",
url: baseUrl,
},
},
} as const;
return JSON.stringify(mcpConfig, null, 2);
}
+61
View File
@@ -0,0 +1,61 @@
import { platformConfigService } from "@/services/platformConfigService";
import type { Metadata } from "next";
import { unstable_cache } from "next/cache";
// use Next.js unstable_cache to cache with tags
export const getCachedPlatformConfig = unstable_cache(
async () => {
return await platformConfigService.getPlatformConfig();
},
["platform-config"],
{
tags: ["platform-config"],
revalidate: 300, // 5 minutes cache
}
);
// get dynamic title
export const getDynamicTitle = async (pageTitle?: string) => {
const platformConfig = await getCachedPlatformConfig();
const websiteTitle =
platformConfig.platform?.website_title ||
"Connect Your AI Agent to the Real World - XPack";
if (pageTitle) {
return `${pageTitle} - ${websiteTitle}`;
}
return websiteTitle;
};
// create base metadata object
export const createBaseMetadata = (title?: string): Metadata => ({
title,
description:
"unified platform simplifies API access, accelerates development, and unlocks a universe of capabilities for your AI agents, chatbots, and automated workflows. ",
keywords: [
"API integration platform",
"Agent API connectivity",
"AI agent integration",
"Chatbot API access",
"Automated workflow API",
"Third-party API connector",
"MCP connector",
"MCP integration",
"API management for agents",
"Agent development platform",
"API orchestration",
"API gateway for agents",
"No-code API integration",
"Low-code API development",
"Enterprise API connectivity",
"Developer tools API",
"XPack.AI",
],
authors: [{ name: "XPack.AI Team" }],
openGraph: {
title: "XPack.AI",
description: "Connect Your Agent to Any API/MCP",
type: "website",
},
});