Compare commits
1 Commits
cloudflare
...
dev/migrat
Author | SHA1 | Date | |
---|---|---|---|
|
53a9fdd270 |
@ -1,7 +1,4 @@
|
|||||||
.cursor
|
.cursor
|
||||||
.claude
|
|
||||||
.conductor
|
|
||||||
.kiro
|
|
||||||
.github
|
.github
|
||||||
.next
|
.next
|
||||||
.open-next
|
.open-next
|
||||||
@ -13,4 +10,4 @@
|
|||||||
node_modules
|
node_modules
|
||||||
**/node_modules
|
**/node_modules
|
||||||
Dockerfile
|
Dockerfile
|
||||||
LICENSE
|
LICENSE
|
6
.gitignore
vendored
6
.gitignore
vendored
@ -41,9 +41,6 @@ certificates
|
|||||||
# claude code
|
# claude code
|
||||||
.claude
|
.claude
|
||||||
|
|
||||||
# conductor
|
|
||||||
.conductor
|
|
||||||
|
|
||||||
# kiro
|
# kiro
|
||||||
.kiro
|
.kiro
|
||||||
|
|
||||||
@ -65,3 +62,6 @@ next-env.d.ts
|
|||||||
.dev.vars
|
.dev.vars
|
||||||
.dev.vars*
|
.dev.vars*
|
||||||
!.dev.vars.example
|
!.dev.vars.example
|
||||||
|
|
||||||
|
# database migrations (generated locally)
|
||||||
|
src/db/migrations/
|
||||||
|
8
.vscode/settings.json
vendored
8
.vscode/settings.json
vendored
@ -24,12 +24,6 @@
|
|||||||
".next": true,
|
".next": true,
|
||||||
".source": true,
|
".source": true,
|
||||||
".wrangler": true,
|
".wrangler": true,
|
||||||
".open-next": true,
|
".open-next": true
|
||||||
".vscode": true,
|
|
||||||
".cursor": true,
|
|
||||||
".claude": true,
|
|
||||||
".conductor": true,
|
|
||||||
".kiro": true,
|
|
||||||
".github": true
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,7 +21,7 @@ If you found anything that could be improved, please let me know.
|
|||||||
- 📚 documentation: [mksaas.com/docs](https://mksaas.com/docs)
|
- 📚 documentation: [mksaas.com/docs](https://mksaas.com/docs)
|
||||||
- 🗓️ roadmap: [mksaas roadmap](https://mksaas.link/roadmap)
|
- 🗓️ roadmap: [mksaas roadmap](https://mksaas.link/roadmap)
|
||||||
- 👨💻 discord: [mksaas.link/discord](https://mksaas.link/discord)
|
- 👨💻 discord: [mksaas.link/discord](https://mksaas.link/discord)
|
||||||
- 📹 video: [mksaas.link/youtube](https://mksaas.link/youtube)
|
- 📹 video (WIP): [mksaas.link/youtube](https://mksaas.link/youtube)
|
||||||
|
|
||||||
## Repositories
|
## Repositories
|
||||||
|
|
||||||
|
14
biome.json
14
biome.json
@ -12,9 +12,6 @@
|
|||||||
".open-next/**",
|
".open-next/**",
|
||||||
".wrangler/**",
|
".wrangler/**",
|
||||||
".cursor/**",
|
".cursor/**",
|
||||||
".claude/**",
|
|
||||||
".kiro/**",
|
|
||||||
".conductor/**",
|
|
||||||
".vscode/**",
|
".vscode/**",
|
||||||
".source/**",
|
".source/**",
|
||||||
"node_modules/**",
|
"node_modules/**",
|
||||||
@ -26,11 +23,11 @@
|
|||||||
"src/components/magicui/*.tsx",
|
"src/components/magicui/*.tsx",
|
||||||
"src/components/animate-ui/*.tsx",
|
"src/components/animate-ui/*.tsx",
|
||||||
"src/components/tailark/*.tsx",
|
"src/components/tailark/*.tsx",
|
||||||
"src/components/ai-elements/*.tsx",
|
|
||||||
"src/app/[[]locale]/preview/**",
|
"src/app/[[]locale]/preview/**",
|
||||||
"src/payment/types.ts",
|
"src/payment/types.ts",
|
||||||
"src/credits/types.ts",
|
"src/credits/types.ts",
|
||||||
"src/types/index.d.ts"
|
"src/types/index.d.ts",
|
||||||
|
"public/sw.js"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"formatter": {
|
"formatter": {
|
||||||
@ -77,9 +74,6 @@
|
|||||||
".open-next/**",
|
".open-next/**",
|
||||||
".wrangler/**",
|
".wrangler/**",
|
||||||
".cursor/**",
|
".cursor/**",
|
||||||
".claude/**",
|
|
||||||
".conductor/**",
|
|
||||||
".kiro/**",
|
|
||||||
".vscode/**",
|
".vscode/**",
|
||||||
".source/**",
|
".source/**",
|
||||||
"node_modules/**",
|
"node_modules/**",
|
||||||
@ -91,11 +85,11 @@
|
|||||||
"src/components/magicui/*.tsx",
|
"src/components/magicui/*.tsx",
|
||||||
"src/components/animate-ui/*.tsx",
|
"src/components/animate-ui/*.tsx",
|
||||||
"src/components/tailark/*.tsx",
|
"src/components/tailark/*.tsx",
|
||||||
"src/components/ai-elements/*.tsx",
|
|
||||||
"src/app/[[]locale]/preview/**",
|
"src/app/[[]locale]/preview/**",
|
||||||
"src/payment/types.ts",
|
"src/payment/types.ts",
|
||||||
"src/credits/types.ts",
|
"src/credits/types.ts",
|
||||||
"src/types/index.d.ts"
|
"src/types/index.d.ts",
|
||||||
|
"public/sw.js"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"javascript": {
|
"javascript": {
|
||||||
|
7483
cloudflare-env.d.ts
vendored
7483
cloudflare-env.d.ts
vendored
File diff suppressed because it is too large
Load Diff
@ -1,56 +0,0 @@
|
|||||||
---
|
|
||||||
title: "Premium Blog Post"
|
|
||||||
description: "This blog post is a test for premium content."
|
|
||||||
date: "2025-08-30"
|
|
||||||
published: true
|
|
||||||
premium: true
|
|
||||||
categories: ["product"]
|
|
||||||
author: "fox"
|
|
||||||
image: "/images/blog/post-7.png"
|
|
||||||
---
|
|
||||||
|
|
||||||
This blog post is a test for premium content.
|
|
||||||
|
|
||||||
You can read this part of the blog post if you are not a premium user.
|
|
||||||
|
|
||||||
But for the rest of the blog post, you need to be logged in as a premium user.
|
|
||||||
|
|
||||||
You can click the "Sign In" button to sign in as a user with free plan.
|
|
||||||
|
|
||||||
Then you can click the "Upgrade Now" button to upgrade to a premium plan.
|
|
||||||
|
|
||||||
<Callout type="warn">
|
|
||||||
Don't worry, you don't actually pay any cents, because we are in the sandbox environment of Stripe.
|
|
||||||
</Callout>
|
|
||||||
|
|
||||||
You can use the test card number to pay for monthly or yearly PRO plan or LIFETIME plan.
|
|
||||||
|
|
||||||
```
|
|
||||||
Card number: 4242 4242 4242 4242
|
|
||||||
Exp: 12/34
|
|
||||||
CVV: 567
|
|
||||||
```
|
|
||||||
|
|
||||||
After that, you can return to the blog post and you can read the rest of the blog post.
|
|
||||||
|
|
||||||
For more details, please check out the documentation: [Blog](https://mksaas.com/docs/blog).
|
|
||||||
|
|
||||||
Now the rest of the blog post is premium content.
|
|
||||||
|
|
||||||
<PremiumContent>
|
|
||||||
|
|
||||||
<Callout type="info">
|
|
||||||
This is the beginning of the premium content part.
|
|
||||||
</Callout>
|
|
||||||
|
|
||||||
This is the premium content part.
|
|
||||||
|
|
||||||
You can read this paragraph only if you are a premium user.
|
|
||||||
|
|
||||||
Please don't share this blog post with others.
|
|
||||||
|
|
||||||
<Callout type="info">
|
|
||||||
This is the end of the premium content part.
|
|
||||||
</Callout>
|
|
||||||
|
|
||||||
</PremiumContent>
|
|
@ -1,56 +0,0 @@
|
|||||||
---
|
|
||||||
title: "测试专用付费文章"
|
|
||||||
description: "这是一篇测试专用付费文章。"
|
|
||||||
date: "2025-08-30"
|
|
||||||
published: true
|
|
||||||
premium: true
|
|
||||||
categories: ["product"]
|
|
||||||
author: "fox"
|
|
||||||
image: "/images/blog/post-7.png"
|
|
||||||
---
|
|
||||||
|
|
||||||
这是一篇测试专用的付费文章。
|
|
||||||
|
|
||||||
如果你不是付费用户,你可以阅读这篇文章的这部分内容。
|
|
||||||
|
|
||||||
但如果你想阅读剩下的内容,你需要成为一个付费用户。
|
|
||||||
|
|
||||||
你可以点击 "登录" 按钮来以免费用户的身份登录。
|
|
||||||
|
|
||||||
然后你可以点击 "立即升级" 按钮来升级到付费计划。
|
|
||||||
|
|
||||||
<Callout type="warn">
|
|
||||||
不用担心,你实际上不需要支付任何费用,因为我们处于 Stripe 的沙盒环境中。
|
|
||||||
</Callout>
|
|
||||||
|
|
||||||
你可以使用测试卡号来支付月度或年度 PRO 计划或终身计划。
|
|
||||||
|
|
||||||
```
|
|
||||||
Card number: 4242 4242 4242 4242
|
|
||||||
Exp: 12/34
|
|
||||||
CVV: 567
|
|
||||||
```
|
|
||||||
|
|
||||||
之后,你可以返回这篇博客文章,然后你可以阅读剩下的内容。
|
|
||||||
|
|
||||||
更多详情,请参考文档:[博客](https://mksaas.com/docs/blog)。
|
|
||||||
|
|
||||||
现在剩下的内容是付费内容。
|
|
||||||
|
|
||||||
<PremiumContent>
|
|
||||||
|
|
||||||
<Callout type="info">
|
|
||||||
这是付费内容部分的开始。
|
|
||||||
</Callout>
|
|
||||||
|
|
||||||
这是付费内容部分。
|
|
||||||
|
|
||||||
你可以阅读这篇内容,只要你是一个付费用户。
|
|
||||||
|
|
||||||
请不要分享这篇文章给其他人。
|
|
||||||
|
|
||||||
<Callout type="info">
|
|
||||||
这是付费内容部分的结束。
|
|
||||||
</Callout>
|
|
||||||
|
|
||||||
</PremiumContent>
|
|
@ -2,7 +2,6 @@
|
|||||||
title: What is Fumadocs
|
title: What is Fumadocs
|
||||||
description: Introducing Fumadocs, a docs framework that you can break.
|
description: Introducing Fumadocs, a docs framework that you can break.
|
||||||
icon: CircleHelp
|
icon: CircleHelp
|
||||||
premium: true
|
|
||||||
---
|
---
|
||||||
|
|
||||||
Fumadocs was created because I wanted a more customisable experience for building docs, to be a docs framework that is not opinionated, **a "framework" that you can break**.
|
Fumadocs was created because I wanted a more customisable experience for building docs, to be a docs framework that is not opinionated, **a "framework" that you can break**.
|
||||||
@ -19,8 +18,6 @@ You are still using features of Next.js App Router, like **Static Site Generatio
|
|||||||
**Opinionated on UI:** The only thing Fumadocs UI (the default theme) offers is **User Interface**. The UI is opinionated for bringing better mobile responsiveness and user experience.
|
**Opinionated on UI:** The only thing Fumadocs UI (the default theme) offers is **User Interface**. The UI is opinionated for bringing better mobile responsiveness and user experience.
|
||||||
Instead, we use a much more flexible approach inspired by Shadcn UI — [Fumadocs CLI](/docs/cli), so we can iterate our design quick, and welcome for more feedback about the UI.
|
Instead, we use a much more flexible approach inspired by Shadcn UI — [Fumadocs CLI](/docs/cli), so we can iterate our design quick, and welcome for more feedback about the UI.
|
||||||
|
|
||||||
<PremiumContent>
|
|
||||||
|
|
||||||
## Why Fumadocs
|
## Why Fumadocs
|
||||||
|
|
||||||
Fumadocs is designed with flexibility in mind.
|
Fumadocs is designed with flexibility in mind.
|
||||||
@ -59,5 +56,3 @@ docs easier, with less boilerplate.
|
|||||||
Fumadocs is maintained by Fuma and many contributors, with care on the maintainability of codebase.
|
Fumadocs is maintained by Fuma and many contributors, with care on the maintainability of codebase.
|
||||||
While we don't aim to offer every functionality people wanted, we're more focused on making basic features perfect and well-maintained.
|
While we don't aim to offer every functionality people wanted, we're more focused on making basic features perfect and well-maintained.
|
||||||
You can also help Fumadocs to be more useful by contributing!
|
You can also help Fumadocs to be more useful by contributing!
|
||||||
|
|
||||||
</PremiumContent>
|
|
||||||
|
@ -2,7 +2,6 @@
|
|||||||
title: 什么是 Fumadocs
|
title: 什么是 Fumadocs
|
||||||
description: 介绍 Fumadocs,一个可以打破常规的文档框架
|
description: 介绍 Fumadocs,一个可以打破常规的文档框架
|
||||||
icon: CircleHelp
|
icon: CircleHelp
|
||||||
premium: true
|
|
||||||
---
|
---
|
||||||
|
|
||||||
Fumadocs 的创建是因为我想要一种更加可定制化的文档构建体验,一个不固执己见的文档框架,**一个你可以"打破"的"框架"**。
|
Fumadocs 的创建是因为我想要一种更加可定制化的文档构建体验,一个不固执己见的文档框架,**一个你可以"打破"的"框架"**。
|
||||||
@ -19,8 +18,6 @@ Fumadocs 的创建是因为我想要一种更加可定制化的文档构建体
|
|||||||
**对 UI 有自己的看法:** Fumadocs UI(默认主题)提供的唯一东西是**用户界面**。UI 的设计理念是提供更好的移动响应性和用户体验。
|
**对 UI 有自己的看法:** Fumadocs UI(默认主题)提供的唯一东西是**用户界面**。UI 的设计理念是提供更好的移动响应性和用户体验。
|
||||||
相反,我们使用受 Shadcn UI 启发的更灵活的方法 — [Fumadocs CLI](/docs/cli),这样我们可以快速迭代设计,并欢迎更多关于 UI 的反馈。
|
相反,我们使用受 Shadcn UI 启发的更灵活的方法 — [Fumadocs CLI](/docs/cli),这样我们可以快速迭代设计,并欢迎更多关于 UI 的反馈。
|
||||||
|
|
||||||
<PremiumContent>
|
|
||||||
|
|
||||||
## 为什么选择 Fumadocs
|
## 为什么选择 Fumadocs
|
||||||
|
|
||||||
Fumadocs 的设计考虑了灵活性。
|
Fumadocs 的设计考虑了灵活性。
|
||||||
@ -56,6 +53,4 @@ Fumadocs 为 Next.js 提供了额外的工具,包括语法高亮、文档搜
|
|||||||
|
|
||||||
Fumadocs 由 Fuma 和许多贡献者维护,关注代码库的可维护性。
|
Fumadocs 由 Fuma 和许多贡献者维护,关注代码库的可维护性。
|
||||||
虽然我们不打算提供人们想要的每一项功能,但我们更专注于使基本功能完美且维护良好。
|
虽然我们不打算提供人们想要的每一项功能,但我们更专注于使基本功能完美且维护良好。
|
||||||
您也可以通过贡献来帮助 Fumadocs 变得更加有用!
|
您也可以通过贡献来帮助 Fumadocs 变得更加有用!
|
||||||
|
|
||||||
</PremiumContent>
|
|
@ -1 +0,0 @@
|
|||||||
NEXTJS_ENV=development
|
|
33
env.example
33
env.example
@ -8,13 +8,13 @@ NEXT_PUBLIC_BASE_URL="http://localhost:3000"
|
|||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Database
|
# Database
|
||||||
# https://mksaas.com/docs/database
|
# https://mksaas.com/docs/database#setup
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
DATABASE_URL=""
|
DATABASE_URL=""
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Better Auth
|
# Better Auth
|
||||||
# https://mksaas.com/docs/auth
|
# https://mksaas.com/docs/auth#setup
|
||||||
# Generate a random string for the secret key using `openssl rand -base64 32`
|
# Generate a random string for the secret key using `openssl rand -base64 32`
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
BETTER_AUTH_SECRET=""
|
BETTER_AUTH_SECRET=""
|
||||||
@ -39,8 +39,8 @@ GOOGLE_CLIENT_SECRET=""
|
|||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Email / Newsletter (Resend)
|
# Email / Newsletter (Resend)
|
||||||
# https://mksaas.com/docs/email
|
# https://mksaas.com/docs/email#setup
|
||||||
# https://mksaas.com/docs/newsletter
|
# https://mksaas.com/docs/newsletter#setup
|
||||||
# Get API key and audience id from https://resend.com
|
# Get API key and audience id from https://resend.com
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
RESEND_API_KEY=""
|
RESEND_API_KEY=""
|
||||||
@ -48,7 +48,7 @@ RESEND_AUDIENCE_ID=""
|
|||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Storage (Cloudflare R2 or S3-compatible service of your choice)
|
# Storage (Cloudflare R2 or S3-compatible service of your choice)
|
||||||
# https://mksaas.com/docs/storage
|
# https://mksaas.com/docs/storage#setup
|
||||||
# Cloudflare R2: https://www.cloudflare.com/developer-platform/products/r2
|
# Cloudflare R2: https://www.cloudflare.com/developer-platform/products/r2
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
STORAGE_REGION="auto"
|
STORAGE_REGION="auto"
|
||||||
@ -60,7 +60,7 @@ STORAGE_PUBLIC_URL=""
|
|||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Payment (Stripe)
|
# Payment (Stripe)
|
||||||
# https://mksaas.com/docs/payment
|
# https://mksaas.com/docs/payment#setup
|
||||||
# Get Stripe key and secret from https://dashboard.stripe.com
|
# Get Stripe key and secret from https://dashboard.stripe.com
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
STRIPE_SECRET_KEY=""
|
STRIPE_SECRET_KEY=""
|
||||||
@ -84,16 +84,13 @@ NEXT_PUBLIC_STRIPE_PRICE_CREDITS_ENTERPRISE=""
|
|||||||
# Configurations
|
# Configurations
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Disable image optimization, check out next.config.ts for more details
|
# Disable image optimization, check out next.config.ts for more details
|
||||||
# -----------------------------------------------------------------------------
|
|
||||||
DISABLE_IMAGE_OPTIMIZATION=false
|
DISABLE_IMAGE_OPTIMIZATION=false
|
||||||
# -----------------------------------------------------------------------------
|
|
||||||
# Run this website as demo website, in most cases, you should set this to false
|
# Run this website as demo website, in most cases, you should set this to false
|
||||||
# -----------------------------------------------------------------------------
|
|
||||||
NEXT_PUBLIC_DEMO_WEBSITE=false
|
NEXT_PUBLIC_DEMO_WEBSITE=false
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Analytics
|
# Analytics
|
||||||
# https://mksaas.com/docs/analytics
|
# https://mksaas.com/docs/analytics#setup
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Google Analytics (https://analytics.google.com)
|
# Google Analytics (https://analytics.google.com)
|
||||||
# https://mksaas.com/docs/analytics#google
|
# https://mksaas.com/docs/analytics#google
|
||||||
@ -159,39 +156,35 @@ NEXT_PUBLIC_AFFILIATE_PROMOTEKIT_ID=""
|
|||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Captcha (Cloudflare Turnstile)
|
# Captcha (Cloudflare Turnstile)
|
||||||
# https://mksaas.com/docs/captcha
|
# https://mksaas.com/docs/captcha#setup
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
NEXT_PUBLIC_TURNSTILE_SITE_KEY=""
|
NEXT_PUBLIC_TURNSTILE_SITE_KEY=""
|
||||||
TURNSTILE_SECRET_KEY=""
|
TURNSTILE_SECRET_KEY=""
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Crisp
|
# Crisp
|
||||||
# https://mksaas.com/docs/chat
|
# https://mksaas.com/docs/chat#setup
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
NEXT_PUBLIC_CRISP_WEBSITE_ID=""
|
NEXT_PUBLIC_CRISP_WEBSITE_ID=""
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Cron Jobs
|
# Inngest
|
||||||
# https://mksaas.com/docs/cronjobs
|
# https://mksaas.com/docs/jobs#setup
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
CRON_JOBS_USERNAME=""
|
INNGEST_SIGNING_KEY=""
|
||||||
CRON_JOBS_PASSWORD=""
|
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# AI
|
# AI
|
||||||
# https://mksaas.com/docs/ai
|
# https://mksaas.com/docs/ai
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
AI_GATEWAY_API_KEY=""
|
|
||||||
FAL_API_KEY=""
|
FAL_API_KEY=""
|
||||||
FIREWORKS_API_KEY=""
|
FIREWORKS_API_KEY=""
|
||||||
OPENAI_API_KEY=""
|
OPENAI_API_KEY=""
|
||||||
REPLICATE_API_TOKEN=""
|
REPLICATE_API_TOKEN=""
|
||||||
GOOGLE_GENERATIVE_AI_API_KEY=""
|
|
||||||
DEEPSEEK_API_KEY=""
|
|
||||||
OPENROUTER_API_KEY=""
|
|
||||||
|
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
# Web Content Analyzer (Firecrawl)
|
# Web Content Analyzer (Firecrawl)
|
||||||
# https://firecrawl.dev/
|
# https://firecrawl.dev/
|
||||||
|
# Get API key from https://firecrawl.dev/app
|
||||||
# -----------------------------------------------------------------------------
|
# -----------------------------------------------------------------------------
|
||||||
FIRECRAWL_API_KEY=""
|
FIRECRAWL_API_KEY=""
|
||||||
|
@ -5,7 +5,6 @@
|
|||||||
"description": "MkSaaS is the best AI SaaS boilerplate. Make AI SaaS in days, simply and effortlessly"
|
"description": "MkSaaS is the best AI SaaS boilerplate. Make AI SaaS in days, simply and effortlessly"
|
||||||
},
|
},
|
||||||
"Common": {
|
"Common": {
|
||||||
"premium": "Premium",
|
|
||||||
"login": "Log in",
|
"login": "Log in",
|
||||||
"logout": "Log out",
|
"logout": "Log out",
|
||||||
"signUp": "Sign up",
|
"signUp": "Sign up",
|
||||||
@ -293,20 +292,8 @@
|
|||||||
"nextPage": "Next",
|
"nextPage": "Next",
|
||||||
"chooseLanguage": "Select language",
|
"chooseLanguage": "Select language",
|
||||||
"title": "MkSaaS Docs",
|
"title": "MkSaaS Docs",
|
||||||
"homepage": "Homepage"
|
"homepage": "Homepage",
|
||||||
},
|
"blog": "Blog"
|
||||||
"PremiumContent": {
|
|
||||||
"title": "Unlock Premium Content",
|
|
||||||
"description": "Subscribe to our Pro plan to access all premium content and exclusive content.",
|
|
||||||
"upgradeCta": "Upgrade Now",
|
|
||||||
"benefit1": "All premium content",
|
|
||||||
"benefit2": "Exclusive content",
|
|
||||||
"benefit3": "Cancel anytime",
|
|
||||||
"signIn": "Sign In",
|
|
||||||
"loginRequired": "Sign in to continue reading",
|
|
||||||
"loginDescription": "This is premium content. Sign in to your account to access the full content.",
|
|
||||||
"checkingAccess": "Checking access...",
|
|
||||||
"loadingContent": "Loading full content..."
|
|
||||||
},
|
},
|
||||||
"Marketing": {
|
"Marketing": {
|
||||||
"navbar": {
|
"navbar": {
|
||||||
@ -333,10 +320,6 @@
|
|||||||
"title": "AI Image",
|
"title": "AI Image",
|
||||||
"description": "Show how to use AI to generate beautiful images"
|
"description": "Show how to use AI to generate beautiful images"
|
||||||
},
|
},
|
||||||
"chat": {
|
|
||||||
"title": "AI Chat",
|
|
||||||
"description": "Show how to use AI to chat with your customers"
|
|
||||||
},
|
|
||||||
"video": {
|
"video": {
|
||||||
"title": "AI Video",
|
"title": "AI Video",
|
||||||
"description": "Show how to use AI to generate amazing videos"
|
"description": "Show how to use AI to generate amazing videos"
|
||||||
@ -591,7 +574,7 @@
|
|||||||
},
|
},
|
||||||
"price": "Price:",
|
"price": "Price:",
|
||||||
"periodStartDate": "Period start date:",
|
"periodStartDate": "Period start date:",
|
||||||
"periodEndDate": "Period end date:",
|
"nextBillingDate": "Next billing date:",
|
||||||
"trialEnds": "Trial ends:",
|
"trialEnds": "Trial ends:",
|
||||||
"freePlanMessage": "You are currently on the free plan with limited features",
|
"freePlanMessage": "You are currently on the free plan with limited features",
|
||||||
"lifetimeMessage": "You have lifetime access to all premium features",
|
"lifetimeMessage": "You have lifetime access to all premium features",
|
||||||
@ -605,10 +588,6 @@
|
|||||||
"credits": {
|
"credits": {
|
||||||
"title": "Credits",
|
"title": "Credits",
|
||||||
"description": "Manage your credit transactions",
|
"description": "Manage your credit transactions",
|
||||||
"tabs": {
|
|
||||||
"balance": "Balance",
|
|
||||||
"transactions": "Transactions"
|
|
||||||
},
|
|
||||||
"balance": {
|
"balance": {
|
||||||
"title": "Credit Balance",
|
"title": "Credit Balance",
|
||||||
"description": "Your credit balance",
|
"description": "Your credit balance",
|
||||||
@ -618,7 +597,9 @@
|
|||||||
"creditsAdded": "Credits have been added to your account",
|
"creditsAdded": "Credits have been added to your account",
|
||||||
"viewTransactions": "View Credit Transactions",
|
"viewTransactions": "View Credit Transactions",
|
||||||
"retry": "Retry",
|
"retry": "Retry",
|
||||||
"expiringCredits": "{credits} credits expiring in the next {days} days"
|
"subscriptionCredits": "{credits} credits from subscription this month",
|
||||||
|
"lifetimeCredits": "{credits} credits from lifetime plan this month",
|
||||||
|
"expiringCredits": "{credits} credits expiring on {date}"
|
||||||
},
|
},
|
||||||
"packages": {
|
"packages": {
|
||||||
"title": "Credit Packages",
|
"title": "Credit Packages",
|
||||||
@ -1057,18 +1038,17 @@
|
|||||||
},
|
},
|
||||||
"AIImagePage": {
|
"AIImagePage": {
|
||||||
"title": "AI Image",
|
"title": "AI Image",
|
||||||
"description": "MkSaaS lets you make AI SaaS in days, simply and effortlessly"
|
"description": "MkSaaS lets you make AI SaaS in days, simply and effortlessly",
|
||||||
},
|
"content": "Working in progress"
|
||||||
"AIChatPage": {
|
|
||||||
"title": "AI Chat",
|
|
||||||
"description": "MkSaaS lets you make AI SaaS in days, simply and effortlessly"
|
|
||||||
},
|
},
|
||||||
"AIVideoPage": {
|
"AIVideoPage": {
|
||||||
"title": "AI Video",
|
"title": "AI Video",
|
||||||
"description": "MkSaaS lets you make AI SaaS in days, simply and effortlessly"
|
"description": "MkSaaS lets you make AI SaaS in days, simply and effortlessly",
|
||||||
|
"content": "Working in progress"
|
||||||
},
|
},
|
||||||
"AIAudioPage": {
|
"AIAudioPage": {
|
||||||
"title": "AI Audio",
|
"title": "AI Audio",
|
||||||
"description": "MkSaaS lets you make AI SaaS in days, simply and effortlessly"
|
"description": "MkSaaS lets you make AI SaaS in days, simply and effortlessly",
|
||||||
|
"content": "Working in progress"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,7 +5,6 @@
|
|||||||
"description": "MkSaaS 是构建 AI SaaS 的最佳模板,使用 MkSaaS 可以在几天内轻松构建您的 AI SaaS,简单且毫不费力。"
|
"description": "MkSaaS 是构建 AI SaaS 的最佳模板,使用 MkSaaS 可以在几天内轻松构建您的 AI SaaS,简单且毫不费力。"
|
||||||
},
|
},
|
||||||
"Common": {
|
"Common": {
|
||||||
"premium": "付费文章",
|
|
||||||
"login": "登录",
|
"login": "登录",
|
||||||
"logout": "退出",
|
"logout": "退出",
|
||||||
"signUp": "注册",
|
"signUp": "注册",
|
||||||
@ -293,20 +292,8 @@
|
|||||||
"nextPage": "下一页",
|
"nextPage": "下一页",
|
||||||
"chooseLanguage": "选择语言",
|
"chooseLanguage": "选择语言",
|
||||||
"title": "MkSaaS文档",
|
"title": "MkSaaS文档",
|
||||||
"homepage": "首页"
|
"homepage": "首页",
|
||||||
},
|
"blog": "博客"
|
||||||
"PremiumContent": {
|
|
||||||
"title": "解锁付费内容",
|
|
||||||
"description": "订阅我们的付费计划,访问所有付费内容和独家内容。",
|
|
||||||
"upgradeCta": "立即升级",
|
|
||||||
"benefit1": "所有内容",
|
|
||||||
"benefit2": "独家内容",
|
|
||||||
"benefit3": "随时取消",
|
|
||||||
"signIn": "登录",
|
|
||||||
"loginRequired": "登录以继续阅读",
|
|
||||||
"loginDescription": "这是一篇付费内容,请登录您的账户以访问完整内容。",
|
|
||||||
"checkingAccess": "检查阅读权限...",
|
|
||||||
"loadingContent": "加载完整内容..."
|
|
||||||
},
|
},
|
||||||
"Marketing": {
|
"Marketing": {
|
||||||
"navbar": {
|
"navbar": {
|
||||||
@ -333,10 +320,6 @@
|
|||||||
"title": "AI 图像",
|
"title": "AI 图像",
|
||||||
"description": "展示如何使用 AI 生成精美图像"
|
"description": "展示如何使用 AI 生成精美图像"
|
||||||
},
|
},
|
||||||
"chat": {
|
|
||||||
"title": "AI 聊天",
|
|
||||||
"description": "展示如何使用 AI 与客户聊天"
|
|
||||||
},
|
|
||||||
"video": {
|
"video": {
|
||||||
"title": "AI 视频",
|
"title": "AI 视频",
|
||||||
"description": "展示如何使用 AI 生成惊人视频"
|
"description": "展示如何使用 AI 生成惊人视频"
|
||||||
@ -591,7 +574,7 @@
|
|||||||
},
|
},
|
||||||
"price": "价格:",
|
"price": "价格:",
|
||||||
"periodStartDate": "周期开始日期:",
|
"periodStartDate": "周期开始日期:",
|
||||||
"periodEndDate": "周期结束日期:",
|
"nextBillingDate": "下次账单日期:",
|
||||||
"trialEnds": "试用结束日期:",
|
"trialEnds": "试用结束日期:",
|
||||||
"freePlanMessage": "您当前使用的是功能有限的免费方案",
|
"freePlanMessage": "您当前使用的是功能有限的免费方案",
|
||||||
"lifetimeMessage": "您拥有所有高级功能的终身使用权限",
|
"lifetimeMessage": "您拥有所有高级功能的终身使用权限",
|
||||||
@ -605,10 +588,6 @@
|
|||||||
"credits": {
|
"credits": {
|
||||||
"title": "积分",
|
"title": "积分",
|
||||||
"description": "管理您的积分交易",
|
"description": "管理您的积分交易",
|
||||||
"tabs": {
|
|
||||||
"balance": "积分余额",
|
|
||||||
"transactions": "交易记录"
|
|
||||||
},
|
|
||||||
"balance": {
|
"balance": {
|
||||||
"title": "积分余额",
|
"title": "积分余额",
|
||||||
"description": "您的积分余额",
|
"description": "您的积分余额",
|
||||||
@ -618,7 +597,9 @@
|
|||||||
"creditsAdded": "积分已添加到您的账户",
|
"creditsAdded": "积分已添加到您的账户",
|
||||||
"viewTransactions": "查看积分记录",
|
"viewTransactions": "查看积分记录",
|
||||||
"retry": "重试",
|
"retry": "重试",
|
||||||
"expiringCredits": "{credits} 积分将在 {days} 天内过期"
|
"subscriptionCredits": "本月订阅获得 {credits} 积分",
|
||||||
|
"lifetimeCredits": "本月终身会员获得 {credits} 积分",
|
||||||
|
"expiringCredits": "{credits} 积分将在 {date} 过期"
|
||||||
},
|
},
|
||||||
"packages": {
|
"packages": {
|
||||||
"title": "积分套餐",
|
"title": "积分套餐",
|
||||||
@ -1057,18 +1038,17 @@
|
|||||||
},
|
},
|
||||||
"AIImagePage": {
|
"AIImagePage": {
|
||||||
"title": "AI 图片",
|
"title": "AI 图片",
|
||||||
"description": "MkSaaS 让您在几天内轻松构建您的 AI SaaS,简单且毫不费力"
|
"description": "MkSaaS 让您在几天内轻松构建您的 AI SaaS,简单且毫不费力",
|
||||||
},
|
"content": "正在开发中"
|
||||||
"AIChatPage": {
|
|
||||||
"title": "AI 聊天",
|
|
||||||
"description": "MkSaaS 让您在几天内轻松构建您的 AI SaaS,简单且毫不费力"
|
|
||||||
},
|
},
|
||||||
"AIVideoPage": {
|
"AIVideoPage": {
|
||||||
"title": "AI 视频",
|
"title": "AI 视频",
|
||||||
"description": "MkSaaS 让您在几天内轻松构建您的 AI SaaS,简单且毫不费力"
|
"description": "MkSaaS 让您在几天内轻松构建您的 AI SaaS,简单且毫不费力",
|
||||||
|
"content": "正在开发中"
|
||||||
},
|
},
|
||||||
"AIAudioPage": {
|
"AIAudioPage": {
|
||||||
"title": "AI 音频",
|
"title": "AI 音频",
|
||||||
"description": "MkSaaS 让您在几天内轻松构建您的 AI SaaS,简单且毫不费力"
|
"description": "MkSaaS 让您在几天内轻松构建您的 AI SaaS,简单且毫不费力",
|
||||||
|
"content": "正在开发中"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,18 +18,6 @@ const nextConfig: NextConfig = {
|
|||||||
// removeConsole: process.env.NODE_ENV === 'production',
|
// removeConsole: process.env.NODE_ENV === 'production',
|
||||||
},
|
},
|
||||||
|
|
||||||
// https://github.com/vercel/next.js/discussions/50177#discussioncomment-6006702
|
|
||||||
// fix build error: Module build failed: UnhandledSchemeError:
|
|
||||||
// Reading from "cloudflare:sockets" is not handled by plugins (Unhandled scheme).
|
|
||||||
webpack: (config, { webpack }) => {
|
|
||||||
config.plugins.push(
|
|
||||||
new webpack.IgnorePlugin({
|
|
||||||
resourceRegExp: /^pg-native$|^cloudflare:sockets$/,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
return config;
|
|
||||||
},
|
|
||||||
|
|
||||||
images: {
|
images: {
|
||||||
// https://vercel.com/docs/image-optimization/managing-image-optimization-costs#minimizing-image-optimization-costs
|
// https://vercel.com/docs/image-optimization/managing-image-optimization-costs#minimizing-image-optimization-costs
|
||||||
// https://nextjs.org/docs/app/api-reference/components/image#unoptimized
|
// https://nextjs.org/docs/app/api-reference/components/image#unoptimized
|
||||||
@ -60,10 +48,6 @@ const nextConfig: NextConfig = {
|
|||||||
protocol: 'https',
|
protocol: 'https',
|
||||||
hostname: 'html.tailus.io',
|
hostname: 'html.tailus.io',
|
||||||
},
|
},
|
||||||
{
|
|
||||||
protocol: 'https',
|
|
||||||
hostname: 'service.firecrawl.dev',
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@ -82,9 +66,3 @@ const withNextIntl = createNextIntlPlugin();
|
|||||||
const withMDX = createMDX();
|
const withMDX = createMDX();
|
||||||
|
|
||||||
export default withMDX(withNextIntl(nextConfig));
|
export default withMDX(withNextIntl(nextConfig));
|
||||||
|
|
||||||
// https://opennext.js.org/cloudflare/get-started#12-develop-locally
|
|
||||||
import { initOpenNextCloudflareForDev } from '@opennextjs/cloudflare';
|
|
||||||
|
|
||||||
// during local development, to access in any of your server code, local versions of Cloudflare bindings
|
|
||||||
initOpenNextCloudflareForDev();
|
|
||||||
|
@ -1,6 +0,0 @@
|
|||||||
import { defineCloudflareConfig } from "@opennextjs/cloudflare";
|
|
||||||
|
|
||||||
|
|
||||||
export default defineCloudflareConfig({
|
|
||||||
|
|
||||||
});
|
|
45
package.json
45
package.json
@ -4,7 +4,6 @@
|
|||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
"cf-dev": "next dev -p 8787",
|
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"postinstall": "fumadocs-mdx",
|
"postinstall": "fumadocs-mdx",
|
||||||
@ -16,7 +15,6 @@
|
|||||||
"db:push": "drizzle-kit push",
|
"db:push": "drizzle-kit push",
|
||||||
"db:studio": "drizzle-kit studio",
|
"db:studio": "drizzle-kit studio",
|
||||||
"list-contacts": "tsx scripts/list-contacts.ts",
|
"list-contacts": "tsx scripts/list-contacts.ts",
|
||||||
"list-users": "tsx scripts/list-users.ts",
|
|
||||||
"content": "fumadocs-mdx",
|
"content": "fumadocs-mdx",
|
||||||
"email": "email dev --dir src/mail/templates --port 3333",
|
"email": "email dev --dir src/mail/templates --port 3333",
|
||||||
"preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
|
"preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",
|
||||||
@ -26,25 +24,22 @@
|
|||||||
"knip": "knip"
|
"knip": "knip"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@ai-sdk/deepseek": "^1.0.0",
|
"@ai-sdk/fal": "^0.1.12",
|
||||||
"@ai-sdk/fal": "^1.0.0",
|
"@ai-sdk/fireworks": "^0.2.14",
|
||||||
"@ai-sdk/fireworks": "^1.0.0",
|
"@ai-sdk/google-vertex": "^2.2.24",
|
||||||
"@ai-sdk/google": "^2.0.0",
|
"@ai-sdk/openai": "^1.1.13",
|
||||||
"@ai-sdk/openai": "^2.0.0",
|
"@ai-sdk/replicate": "^0.2.8",
|
||||||
"@ai-sdk/react": "^2.0.22",
|
|
||||||
"@ai-sdk/replicate": "^1.0.0",
|
|
||||||
"@base-ui-components/react": "1.0.0-beta.0",
|
"@base-ui-components/react": "1.0.0-beta.0",
|
||||||
"@better-fetch/fetch": "^1.1.18",
|
"@better-fetch/fetch": "^1.1.18",
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@dnd-kit/modifiers": "^9.0.0",
|
"@dnd-kit/modifiers": "^9.0.0",
|
||||||
"@dnd-kit/sortable": "^10.0.0",
|
"@dnd-kit/sortable": "^10.0.0",
|
||||||
"@dnd-kit/utilities": "^3.2.2",
|
"@dnd-kit/utilities": "^3.2.2",
|
||||||
"@hookform/resolvers": "^5.2.1",
|
"@hookform/resolvers": "^4.1.0",
|
||||||
"@marsidev/react-turnstile": "^1.1.0",
|
"@marsidev/react-turnstile": "^1.1.0",
|
||||||
"@mendable/firecrawl-js": "^1.29.1",
|
"@mendable/firecrawl-js": "^1.29.1",
|
||||||
"@next/third-parties": "^15.3.0",
|
"@next/third-parties": "^15.3.0",
|
||||||
"@openpanel/nextjs": "^1.0.7",
|
"@openpanel/nextjs": "^1.0.7",
|
||||||
"@openrouter/ai-sdk-provider": "^1.0.0-beta.6",
|
|
||||||
"@orama/orama": "^3.1.4",
|
"@orama/orama": "^3.1.4",
|
||||||
"@orama/tokenizers": "^3.1.4",
|
"@orama/tokenizers": "^3.1.4",
|
||||||
"@radix-ui/react-accordion": "^1.2.3",
|
"@radix-ui/react-accordion": "^1.2.3",
|
||||||
@ -76,18 +71,16 @@
|
|||||||
"@radix-ui/react-toggle": "^1.1.2",
|
"@radix-ui/react-toggle": "^1.1.2",
|
||||||
"@radix-ui/react-toggle-group": "^1.1.2",
|
"@radix-ui/react-toggle-group": "^1.1.2",
|
||||||
"@radix-ui/react-tooltip": "^1.1.8",
|
"@radix-ui/react-tooltip": "^1.1.8",
|
||||||
"@radix-ui/react-use-controllable-state": "^1.2.2",
|
|
||||||
"@react-email/components": "0.0.33",
|
"@react-email/components": "0.0.33",
|
||||||
"@react-email/render": "1.0.5",
|
"@react-email/render": "1.0.5",
|
||||||
"@stripe/stripe-js": "^5.6.0",
|
"@stripe/stripe-js": "^5.6.0",
|
||||||
"@tabler/icons-react": "^3.31.0",
|
"@tabler/icons-react": "^3.31.0",
|
||||||
"@tanstack/react-query": "^5.85.5",
|
|
||||||
"@tanstack/react-query-devtools": "^5.85.5",
|
|
||||||
"@tanstack/react-table": "^8.21.2",
|
"@tanstack/react-table": "^8.21.2",
|
||||||
"@types/canvas-confetti": "^1.9.0",
|
"@types/canvas-confetti": "^1.9.0",
|
||||||
"@vercel/analytics": "^1.5.0",
|
"@vercel/analytics": "^1.5.0",
|
||||||
"@vercel/speed-insights": "^1.2.0",
|
"@vercel/speed-insights": "^1.2.0",
|
||||||
"ai": "^5.0.0",
|
"@widgetbot/react-embed": "^1.9.0",
|
||||||
|
"ai": "^4.1.45",
|
||||||
"better-auth": "^1.1.19",
|
"better-auth": "^1.1.19",
|
||||||
"canvas-confetti": "^1.9.3",
|
"canvas-confetti": "^1.9.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
@ -102,9 +95,10 @@
|
|||||||
"drizzle-orm": "^0.39.3",
|
"drizzle-orm": "^0.39.3",
|
||||||
"embla-carousel-react": "^8.5.2",
|
"embla-carousel-react": "^8.5.2",
|
||||||
"framer-motion": "^12.4.7",
|
"framer-motion": "^12.4.7",
|
||||||
"fumadocs-core": "^15.6.7",
|
"fumadocs-core": "^15.5.3",
|
||||||
"fumadocs-mdx": "^11.7.3",
|
"fumadocs-mdx": "^11.6.8",
|
||||||
"fumadocs-ui": "^15.6.7",
|
"fumadocs-ui": "^15.5.3",
|
||||||
|
"inngest": "^3.40.1",
|
||||||
"input-otp": "^1.4.2",
|
"input-otp": "^1.4.2",
|
||||||
"lucide-react": "^0.483.0",
|
"lucide-react": "^0.483.0",
|
||||||
"motion": "^12.4.3",
|
"motion": "^12.4.3",
|
||||||
@ -112,17 +106,14 @@
|
|||||||
"next-intl": "^4.0.0",
|
"next-intl": "^4.0.0",
|
||||||
"next-safe-action": "^7.10.4",
|
"next-safe-action": "^7.10.4",
|
||||||
"next-themes": "^0.4.4",
|
"next-themes": "^0.4.4",
|
||||||
"pg": "^8.16.0",
|
|
||||||
"nuqs": "^2.5.1",
|
|
||||||
"postgres": "^3.4.5",
|
"postgres": "^3.4.5",
|
||||||
"radix-ui": "^1.4.2",
|
"radix-ui": "^1.4.2",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-day-picker": "8.10.1",
|
"react-day-picker": "8.10.1",
|
||||||
"react-dom": "^19.0.0",
|
"react-dom": "^19.0.0",
|
||||||
"react-hook-form": "^7.62.0",
|
"react-hook-form": "^7.54.2",
|
||||||
"react-remove-scroll": "^2.6.3",
|
"react-remove-scroll": "^2.6.3",
|
||||||
"react-resizable-panels": "^2.1.7",
|
"react-resizable-panels": "^2.1.7",
|
||||||
"react-syntax-highlighter": "^15.6.3",
|
|
||||||
"react-tweet": "^3.2.2",
|
"react-tweet": "^3.2.2",
|
||||||
"react-use-measure": "^2.1.7",
|
"react-use-measure": "^2.1.7",
|
||||||
"recharts": "^2.15.1",
|
"recharts": "^2.15.1",
|
||||||
@ -130,7 +121,6 @@
|
|||||||
"s3mini": "^0.2.0",
|
"s3mini": "^0.2.0",
|
||||||
"shiki": "^2.4.2",
|
"shiki": "^2.4.2",
|
||||||
"sonner": "^2.0.0",
|
"sonner": "^2.0.0",
|
||||||
"streamdown": "^1.0.12",
|
|
||||||
"stripe": "^17.6.0",
|
"stripe": "^17.6.0",
|
||||||
"swiper": "^11.2.5",
|
"swiper": "^11.2.5",
|
||||||
"tailwind-merge": "^3.0.2",
|
"tailwind-merge": "^3.0.2",
|
||||||
@ -138,29 +128,24 @@
|
|||||||
"tw-animate-css": "^1.2.4",
|
"tw-animate-css": "^1.2.4",
|
||||||
"use-intl": "^3.26.5",
|
"use-intl": "^3.26.5",
|
||||||
"use-media": "^1.5.0",
|
"use-media": "^1.5.0",
|
||||||
"use-stick-to-bottom": "^1.1.1",
|
|
||||||
"vaul": "^1.1.2",
|
"vaul": "^1.1.2",
|
||||||
"zod": "^4.0.17",
|
"zod": "^3.24.2",
|
||||||
"zustand": "^5.0.3"
|
"zustand": "^5.0.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@biomejs/biome": "1.9.4",
|
"@biomejs/biome": "1.9.4",
|
||||||
"@opennextjs/cloudflare": "^1.6.5",
|
|
||||||
"@tailwindcss/postcss": "^4.0.14",
|
"@tailwindcss/postcss": "^4.0.14",
|
||||||
"@tanstack/eslint-plugin-query": "^5.83.1",
|
|
||||||
"@types/mdx": "^2.0.13",
|
"@types/mdx": "^2.0.13",
|
||||||
"@types/node": "^20.19.0",
|
"@types/node": "^20.19.0",
|
||||||
"@types/pg": "^8.11.11",
|
"@types/pg": "^8.11.11",
|
||||||
"@types/react": "^19",
|
"@types/react": "^19",
|
||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"@types/react-syntax-highlighter": "^15.5.13",
|
|
||||||
"drizzle-kit": "^0.30.4",
|
"drizzle-kit": "^0.30.4",
|
||||||
"knip": "^5.61.2",
|
"knip": "^5.61.2",
|
||||||
"postcss": "^8",
|
"postcss": "^8",
|
||||||
"react-email": "3.0.7",
|
"react-email": "3.0.7",
|
||||||
"tailwindcss": "^4.0.14",
|
"tailwindcss": "^4.0.14",
|
||||||
"tsx": "^4.19.3",
|
"tsx": "^4.19.3",
|
||||||
"typescript": "^5.8.3",
|
"typescript": "^5.8.3"
|
||||||
"wrangler": "^4.28.1"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
7863
pnpm-lock.yaml
generated
7863
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@ -1,2 +0,0 @@
|
|||||||
/_next/static/*
|
|
||||||
Cache-Control: public,max-age=31536000,immutable
|
|
129
public/sw.js
Normal file
129
public/sw.js
Normal file
@ -0,0 +1,129 @@
|
|||||||
|
// Service Worker for caching iframe content
|
||||||
|
const CACHE_NAME = 'cnblocks-iframe-cache-v1'
|
||||||
|
|
||||||
|
// Add iframe URLs to this list to prioritize caching
|
||||||
|
const URLS_TO_CACHE = [
|
||||||
|
// Default assets that should be cached
|
||||||
|
'/favicon.ico',
|
||||||
|
// Images used in iframes
|
||||||
|
'/payments.png',
|
||||||
|
'/payments-light.png',
|
||||||
|
'/origin-cal.png',
|
||||||
|
'/origin-cal-dark.png',
|
||||||
|
'/exercice.png',
|
||||||
|
'/exercice-dark.png',
|
||||||
|
'/charts-light.png',
|
||||||
|
'/charts.png',
|
||||||
|
'/music-light.png',
|
||||||
|
'/music.png',
|
||||||
|
'/mail-back-light.png',
|
||||||
|
'/mail-upper.png',
|
||||||
|
'/mail-back.png',
|
||||||
|
'/card.png',
|
||||||
|
'/dark-card.webp',
|
||||||
|
]
|
||||||
|
|
||||||
|
// Install event - cache resources
|
||||||
|
self.addEventListener('install', (event) => {
|
||||||
|
event.waitUntil(
|
||||||
|
caches
|
||||||
|
.open(CACHE_NAME)
|
||||||
|
.then((cache) => {
|
||||||
|
console.log('Opened cache')
|
||||||
|
return cache.addAll(URLS_TO_CACHE)
|
||||||
|
})
|
||||||
|
.then(() => self.skipWaiting()) // Activate SW immediately
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Activate event - clean up old caches
|
||||||
|
self.addEventListener('activate', (event) => {
|
||||||
|
const currentCaches = [CACHE_NAME]
|
||||||
|
event.waitUntil(
|
||||||
|
caches
|
||||||
|
.keys()
|
||||||
|
.then((cacheNames) => {
|
||||||
|
return cacheNames.filter((cacheName) => !currentCaches.includes(cacheName))
|
||||||
|
})
|
||||||
|
.then((cachesToDelete) => {
|
||||||
|
return Promise.all(
|
||||||
|
cachesToDelete.map((cacheToDelete) => {
|
||||||
|
return caches.delete(cacheToDelete)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.then(() => self.clients.claim()) // Take control of clients immediately
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Fetch event - serve from cache or fetch from network and cache
|
||||||
|
self.addEventListener('fetch', (event) => {
|
||||||
|
// Check if this is an iframe request - typically they'll be HTML or have 'preview' in the URL
|
||||||
|
const isIframeRequest = event.request.url.includes('/preview/') || event.request.url.includes('/examples/')
|
||||||
|
|
||||||
|
if (isIframeRequest) {
|
||||||
|
event.respondWith(
|
||||||
|
caches.match(event.request, { ignoreSearch: true }).then((response) => {
|
||||||
|
// Return cached response if found
|
||||||
|
if (response) {
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clone the request (requests are one-time use)
|
||||||
|
const fetchRequest = event.request.clone()
|
||||||
|
|
||||||
|
return fetch(fetchRequest).then((response) => {
|
||||||
|
// Check if we received a valid response
|
||||||
|
if (!response || response.status !== 200 || response.type !== 'basic') {
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clone the response (responses are one-time use)
|
||||||
|
const responseToCache = response.clone()
|
||||||
|
|
||||||
|
caches.open(CACHE_NAME).then((cache) => {
|
||||||
|
cache.put(event.request, responseToCache)
|
||||||
|
})
|
||||||
|
|
||||||
|
return response
|
||||||
|
})
|
||||||
|
})
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
// For non-iframe requests, use a standard cache-first strategy
|
||||||
|
event.respondWith(
|
||||||
|
caches.match(event.request).then((response) => {
|
||||||
|
if (response) {
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
return fetch(event.request)
|
||||||
|
})
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Listen for messages from clients (to force cache update, etc)
|
||||||
|
self.addEventListener('message', (event) => {
|
||||||
|
if (event.data && event.data.type === 'SKIP_WAITING') {
|
||||||
|
self.skipWaiting()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle cache clearing
|
||||||
|
if (event.data && event.data.type === 'CLEAR_IFRAME_CACHE') {
|
||||||
|
const url = event.data.url
|
||||||
|
|
||||||
|
if (url) {
|
||||||
|
// Clear specific URL from cache
|
||||||
|
caches.open(CACHE_NAME).then((cache) => {
|
||||||
|
cache.delete(url).then(() => {
|
||||||
|
console.log(`Cleared cache for: ${url}`)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
// Clear the entire cache
|
||||||
|
caches.delete(CACHE_NAME).then(() => {
|
||||||
|
console.log('Cleared entire iframe cache')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
@ -1,24 +0,0 @@
|
|||||||
import dotenv from 'dotenv';
|
|
||||||
import { getDb } from '../src/db/index.js';
|
|
||||||
import { user } from '../src/db/schema.js';
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
export default async function listUsers() {
|
|
||||||
const db = await getDb();
|
|
||||||
|
|
||||||
try {
|
|
||||||
const users = await db.select({ email: user.email }).from(user);
|
|
||||||
|
|
||||||
// Extract emails from users
|
|
||||||
const emails: string[] = users.map((user) => user.email);
|
|
||||||
|
|
||||||
console.log(`Total users: ${emails.length}`);
|
|
||||||
|
|
||||||
// Output all emails joined with comma
|
|
||||||
console.log(emails.join(', '));
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching users:', error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
listUsers();
|
|
@ -15,7 +15,6 @@ export const docs = defineDocs({
|
|||||||
schema: frontmatterSchema.extend({
|
schema: frontmatterSchema.extend({
|
||||||
preview: z.string().optional(),
|
preview: z.string().optional(),
|
||||||
index: z.boolean().default(false),
|
index: z.boolean().default(false),
|
||||||
premium: z.boolean().optional(),
|
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
meta: {
|
meta: {
|
||||||
@ -86,7 +85,7 @@ export const category = defineCollections({
|
|||||||
/**
|
/**
|
||||||
* Blog posts
|
* Blog posts
|
||||||
*
|
*
|
||||||
* title is required, but description is optional in frontmatter
|
* dtitle is required, but description is optional in frontmatter
|
||||||
*/
|
*/
|
||||||
export const blog = defineCollections({
|
export const blog = defineCollections({
|
||||||
type: 'doc',
|
type: 'doc',
|
||||||
@ -95,7 +94,6 @@ export const blog = defineCollections({
|
|||||||
image: z.string(),
|
image: z.string(),
|
||||||
date: z.string().date(),
|
date: z.string().date(),
|
||||||
published: z.boolean().default(true),
|
published: z.boolean().default(true),
|
||||||
premium: z.boolean().optional(),
|
|
||||||
categories: z.array(z.string()),
|
categories: z.array(z.string()),
|
||||||
author: z.string(),
|
author: z.string(),
|
||||||
}),
|
}),
|
||||||
|
@ -1,16 +1,19 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
|
||||||
import { isSubscribed } from '@/newsletter';
|
import { isSubscribed } from '@/newsletter';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Newsletter schema for validation
|
// Newsletter schema for validation
|
||||||
const newsletterSchema = z.object({
|
const newsletterSchema = z.object({
|
||||||
email: z.email({ error: 'Please enter a valid email address' }),
|
email: z.string().email({ message: 'Please enter a valid email address' }),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create a safe action to check if a user is subscribed to the newsletter
|
// Create a safe action to check if a user is subscribed to the newsletter
|
||||||
export const checkNewsletterStatusAction = userActionClient
|
export const checkNewsletterStatusAction = actionClient
|
||||||
.schema(newsletterSchema)
|
.schema(newsletterSchema)
|
||||||
.action(async ({ parsedInput: { email } }) => {
|
.action(async ({ parsedInput: { email } }) => {
|
||||||
try {
|
try {
|
||||||
|
45
src/actions/check-web-content-analysis-credits.ts
Normal file
45
src/actions/check-web-content-analysis-credits.ts
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
'use server';
|
||||||
|
|
||||||
|
import { getWebContentAnalysisCost } from '@/ai/text/utils/web-content-analyzer-config';
|
||||||
|
import { getUserCredits, hasEnoughCredits } from '@/credits/credits';
|
||||||
|
import { getSession } from '@/lib/server';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
|
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if user has enough credits for web content analysis
|
||||||
|
*/
|
||||||
|
export const checkWebContentAnalysisCreditsAction = actionClient.action(
|
||||||
|
async () => {
|
||||||
|
const session = await getSession();
|
||||||
|
if (!session) {
|
||||||
|
console.warn(
|
||||||
|
'unauthorized request to check web content analysis credits'
|
||||||
|
);
|
||||||
|
return { success: false, error: 'Unauthorized' };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const requiredCredits = getWebContentAnalysisCost();
|
||||||
|
const currentCredits = await getUserCredits(session.user.id);
|
||||||
|
const hasCredits = await hasEnoughCredits({
|
||||||
|
userId: session.user.id,
|
||||||
|
requiredCredits,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
hasEnoughCredits: hasCredits,
|
||||||
|
currentCredits,
|
||||||
|
requiredCredits,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('check web content analysis credits error:', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Something went wrong',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
@ -1,10 +1,12 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { consumeCredits } from '@/credits/credits';
|
import { consumeCredits } from '@/credits/credits';
|
||||||
import type { User } from '@/lib/auth-types';
|
import { getSession } from '@/lib/server';
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// consume credits schema
|
// consume credits schema
|
||||||
const consumeSchema = z.object({
|
const consumeSchema = z.object({
|
||||||
amount: z.number().min(1),
|
amount: z.number().min(1),
|
||||||
@ -14,17 +16,21 @@ const consumeSchema = z.object({
|
|||||||
/**
|
/**
|
||||||
* Consume credits
|
* Consume credits
|
||||||
*/
|
*/
|
||||||
export const consumeCreditsAction = userActionClient
|
export const consumeCreditsAction = actionClient
|
||||||
.schema(consumeSchema)
|
.schema(consumeSchema)
|
||||||
.action(async ({ parsedInput, ctx }) => {
|
.action(async ({ parsedInput }) => {
|
||||||
const { amount, description } = parsedInput;
|
const session = await getSession();
|
||||||
const currentUser = (ctx as { user: User }).user;
|
if (!session) {
|
||||||
|
console.warn('unauthorized request to consume credits');
|
||||||
|
return { success: false, error: 'Unauthorized' };
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await consumeCredits({
|
await consumeCredits({
|
||||||
userId: currentUser.id,
|
userId: session.user.id,
|
||||||
amount,
|
amount: parsedInput.amount,
|
||||||
description: description || `Consume credits: ${amount}`,
|
description:
|
||||||
|
parsedInput.description || `Consume credits: ${parsedInput.amount}`,
|
||||||
});
|
});
|
||||||
return { success: true };
|
return { success: true };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
@ -1,34 +1,59 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { websiteConfig } from '@/config/website';
|
import { websiteConfig } from '@/config/website';
|
||||||
import type { User } from '@/lib/auth-types';
|
|
||||||
import { findPlanByPlanId } from '@/lib/price-plan';
|
import { findPlanByPlanId } from '@/lib/price-plan';
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
import { getSession } from '@/lib/server';
|
||||||
import { getUrlWithLocale } from '@/lib/urls/urls';
|
import { getUrlWithLocale } from '@/lib/urls/urls';
|
||||||
import { createCheckout } from '@/payment';
|
import { createCheckout } from '@/payment';
|
||||||
import type { CreateCheckoutParams } from '@/payment/types';
|
import type { CreateCheckoutParams } from '@/payment/types';
|
||||||
import { Routes } from '@/routes';
|
import { Routes } from '@/routes';
|
||||||
import { getLocale } from 'next-intl/server';
|
import { getLocale } from 'next-intl/server';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { cookies } from 'next/headers';
|
import { cookies } from 'next/headers';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Checkout schema for validation
|
// Checkout schema for validation
|
||||||
// metadata is optional, and may contain referral information if you need
|
// metadata is optional, and may contain referral information if you need
|
||||||
const checkoutSchema = z.object({
|
const checkoutSchema = z.object({
|
||||||
userId: z.string().min(1, { error: 'User ID is required' }),
|
userId: z.string().min(1, { message: 'User ID is required' }),
|
||||||
planId: z.string().min(1, { error: 'Plan ID is required' }),
|
planId: z.string().min(1, { message: 'Plan ID is required' }),
|
||||||
priceId: z.string().min(1, { error: 'Price ID is required' }),
|
priceId: z.string().min(1, { message: 'Price ID is required' }),
|
||||||
metadata: z.record(z.string(), z.string()).optional(),
|
metadata: z.record(z.string()).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a checkout session for a price plan
|
* Create a checkout session for a price plan
|
||||||
*/
|
*/
|
||||||
export const createCheckoutAction = userActionClient
|
export const createCheckoutAction = actionClient
|
||||||
.schema(checkoutSchema)
|
.schema(checkoutSchema)
|
||||||
.action(async ({ parsedInput, ctx }) => {
|
.action(async ({ parsedInput }) => {
|
||||||
const { planId, priceId, metadata } = parsedInput;
|
const { userId, planId, priceId, metadata } = parsedInput;
|
||||||
const currentUser = (ctx as { user: User }).user;
|
|
||||||
|
// Get the current user session for authorization
|
||||||
|
const session = await getSession();
|
||||||
|
if (!session) {
|
||||||
|
console.warn(
|
||||||
|
`unauthorized request to create checkout session for user ${userId}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only allow users to create their own checkout session
|
||||||
|
if (session.user.id !== userId) {
|
||||||
|
console.warn(
|
||||||
|
`current user ${session.user.id} is not authorized to create checkout session for user ${userId}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Not authorized to do this action',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get the current locale from the request
|
// Get the current locale from the request
|
||||||
@ -46,8 +71,8 @@ export const createCheckoutAction = userActionClient
|
|||||||
// Add user id to metadata, so we can get it in the webhook event
|
// Add user id to metadata, so we can get it in the webhook event
|
||||||
const customMetadata: Record<string, string> = {
|
const customMetadata: Record<string, string> = {
|
||||||
...metadata,
|
...metadata,
|
||||||
userId: currentUser.id,
|
userId: session.user.id,
|
||||||
userName: currentUser.name,
|
userName: session.user.name,
|
||||||
};
|
};
|
||||||
|
|
||||||
// https://datafa.st/docs/stripe-checkout-api
|
// https://datafa.st/docs/stripe-checkout-api
|
||||||
@ -69,7 +94,7 @@ export const createCheckoutAction = userActionClient
|
|||||||
const params: CreateCheckoutParams = {
|
const params: CreateCheckoutParams = {
|
||||||
planId,
|
planId,
|
||||||
priceId,
|
priceId,
|
||||||
customerEmail: currentUser.email,
|
customerEmail: session.user.email,
|
||||||
metadata: customMetadata,
|
metadata: customMetadata,
|
||||||
successUrl,
|
successUrl,
|
||||||
cancelUrl,
|
cancelUrl,
|
||||||
|
@ -2,33 +2,58 @@
|
|||||||
|
|
||||||
import { websiteConfig } from '@/config/website';
|
import { websiteConfig } from '@/config/website';
|
||||||
import { getCreditPackageById } from '@/credits/server';
|
import { getCreditPackageById } from '@/credits/server';
|
||||||
import type { User } from '@/lib/auth-types';
|
import { getSession } from '@/lib/server';
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
|
||||||
import { getUrlWithLocale } from '@/lib/urls/urls';
|
import { getUrlWithLocale } from '@/lib/urls/urls';
|
||||||
import { createCreditCheckout } from '@/payment';
|
import { createCreditCheckout } from '@/payment';
|
||||||
import type { CreateCreditCheckoutParams } from '@/payment/types';
|
import type { CreateCreditCheckoutParams } from '@/payment/types';
|
||||||
import { Routes } from '@/routes';
|
import { Routes } from '@/routes';
|
||||||
import { getLocale } from 'next-intl/server';
|
import { getLocale } from 'next-intl/server';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { cookies } from 'next/headers';
|
import { cookies } from 'next/headers';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Credit checkout schema for validation
|
// Credit checkout schema for validation
|
||||||
// metadata is optional, and may contain referral information if you need
|
// metadata is optional, and may contain referral information if you need
|
||||||
const creditCheckoutSchema = z.object({
|
const creditCheckoutSchema = z.object({
|
||||||
userId: z.string().min(1, { error: 'User ID is required' }),
|
userId: z.string().min(1, { message: 'User ID is required' }),
|
||||||
packageId: z.string().min(1, { error: 'Package ID is required' }),
|
packageId: z.string().min(1, { message: 'Package ID is required' }),
|
||||||
priceId: z.string().min(1, { error: 'Price ID is required' }),
|
priceId: z.string().min(1, { message: 'Price ID is required' }),
|
||||||
metadata: z.record(z.string(), z.string()).optional(),
|
metadata: z.record(z.string()).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a checkout session for a credit package
|
* Create a checkout session for a credit package
|
||||||
*/
|
*/
|
||||||
export const createCreditCheckoutSession = userActionClient
|
export const createCreditCheckoutSession = actionClient
|
||||||
.schema(creditCheckoutSchema)
|
.schema(creditCheckoutSchema)
|
||||||
.action(async ({ parsedInput, ctx }) => {
|
.action(async ({ parsedInput }) => {
|
||||||
const { packageId, priceId, metadata } = parsedInput;
|
const { userId, packageId, priceId, metadata } = parsedInput;
|
||||||
const currentUser = (ctx as { user: User }).user;
|
|
||||||
|
// Get the current user session for authorization
|
||||||
|
const session = await getSession();
|
||||||
|
if (!session) {
|
||||||
|
console.warn(
|
||||||
|
`unauthorized request to create credit checkout session for user ${userId}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only allow users to create their own checkout session
|
||||||
|
if (session.user.id !== userId) {
|
||||||
|
console.warn(
|
||||||
|
`current user ${session.user.id} is not authorized to create credit checkout session for user ${userId}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Not authorized to do this action',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get the current locale from the request
|
// Get the current locale from the request
|
||||||
@ -48,9 +73,9 @@ export const createCreditCheckoutSession = userActionClient
|
|||||||
...metadata,
|
...metadata,
|
||||||
type: 'credit_purchase',
|
type: 'credit_purchase',
|
||||||
packageId,
|
packageId,
|
||||||
credits: creditPackage.amount.toString(),
|
credits: creditPackage.credits.toString(),
|
||||||
userId: currentUser.id,
|
userId: session.user.id,
|
||||||
userName: currentUser.name,
|
userName: session.user.name,
|
||||||
};
|
};
|
||||||
|
|
||||||
// https://datafa.st/docs/stripe-checkout-api
|
// https://datafa.st/docs/stripe-checkout-api
|
||||||
@ -65,15 +90,15 @@ export const createCreditCheckoutSession = userActionClient
|
|||||||
|
|
||||||
// Create checkout session with credit-specific URLs
|
// Create checkout session with credit-specific URLs
|
||||||
const successUrl = getUrlWithLocale(
|
const successUrl = getUrlWithLocale(
|
||||||
`${Routes.SettingsCredits}?credits_session_id={CHECKOUT_SESSION_ID}`,
|
`${Routes.SettingsBilling}?credits_session_id={CHECKOUT_SESSION_ID}`,
|
||||||
locale
|
locale
|
||||||
);
|
);
|
||||||
const cancelUrl = getUrlWithLocale(Routes.SettingsCredits, locale);
|
const cancelUrl = getUrlWithLocale(Routes.SettingsBilling, locale);
|
||||||
|
|
||||||
const params: CreateCreditCheckoutParams = {
|
const params: CreateCreditCheckoutParams = {
|
||||||
packageId,
|
packageId,
|
||||||
priceId,
|
priceId,
|
||||||
customerEmail: currentUser.email,
|
customerEmail: session.user.email,
|
||||||
metadata: customMetadata,
|
metadata: customMetadata,
|
||||||
successUrl,
|
successUrl,
|
||||||
cancelUrl,
|
cancelUrl,
|
||||||
|
@ -2,32 +2,57 @@
|
|||||||
|
|
||||||
import { getDb } from '@/db';
|
import { getDb } from '@/db';
|
||||||
import { user } from '@/db/schema';
|
import { user } from '@/db/schema';
|
||||||
import type { User } from '@/lib/auth-types';
|
import { getSession } from '@/lib/server';
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
|
||||||
import { getUrlWithLocale } from '@/lib/urls/urls';
|
import { getUrlWithLocale } from '@/lib/urls/urls';
|
||||||
import { createCustomerPortal } from '@/payment';
|
import { createCustomerPortal } from '@/payment';
|
||||||
import type { CreatePortalParams } from '@/payment/types';
|
import type { CreatePortalParams } from '@/payment/types';
|
||||||
import { eq } from 'drizzle-orm';
|
import { eq } from 'drizzle-orm';
|
||||||
import { getLocale } from 'next-intl/server';
|
import { getLocale } from 'next-intl/server';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Portal schema for validation
|
// Portal schema for validation
|
||||||
const portalSchema = z.object({
|
const portalSchema = z.object({
|
||||||
userId: z.string().min(1, { error: 'User ID is required' }),
|
userId: z.string().min(1, { message: 'User ID is required' }),
|
||||||
returnUrl: z
|
returnUrl: z
|
||||||
.string()
|
.string()
|
||||||
.url({ error: 'Return URL must be a valid URL' })
|
.url({ message: 'Return URL must be a valid URL' })
|
||||||
.optional(),
|
.optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a customer portal session
|
* Create a customer portal session
|
||||||
*/
|
*/
|
||||||
export const createPortalAction = userActionClient
|
export const createPortalAction = actionClient
|
||||||
.schema(portalSchema)
|
.schema(portalSchema)
|
||||||
.action(async ({ parsedInput, ctx }) => {
|
.action(async ({ parsedInput }) => {
|
||||||
const { returnUrl } = parsedInput;
|
const { userId, returnUrl } = parsedInput;
|
||||||
const currentUser = (ctx as { user: User }).user;
|
|
||||||
|
// Get the current user session for authorization
|
||||||
|
const session = await getSession();
|
||||||
|
if (!session) {
|
||||||
|
console.warn(
|
||||||
|
`unauthorized request to create portal session for user ${userId}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only allow users to create their own portal session
|
||||||
|
if (session.user.id !== userId) {
|
||||||
|
console.warn(
|
||||||
|
`current user ${session.user.id} is not authorized to create portal session for user ${userId}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Not authorized to do this action',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get the user's customer ID from the database
|
// Get the user's customer ID from the database
|
||||||
@ -35,11 +60,11 @@ export const createPortalAction = userActionClient
|
|||||||
const customerResult = await db
|
const customerResult = await db
|
||||||
.select({ customerId: user.customerId })
|
.select({ customerId: user.customerId })
|
||||||
.from(user)
|
.from(user)
|
||||||
.where(eq(user.id, currentUser.id))
|
.where(eq(user.id, session.user.id))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (customerResult.length <= 0 || !customerResult[0].customerId) {
|
if (customerResult.length <= 0 || !customerResult[0].customerId) {
|
||||||
console.error(`No customer found for user ${currentUser.id}`);
|
console.error(`No customer found for user ${session.user.id}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: 'No customer found for user',
|
error: 'No customer found for user',
|
||||||
|
@ -1,13 +1,16 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import type { User } from '@/lib/auth-types';
|
import { getSession } from '@/lib/server';
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
|
||||||
import { getSubscriptions } from '@/payment';
|
import { getSubscriptions } from '@/payment';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Input schema
|
// Input schema
|
||||||
const schema = z.object({
|
const schema = z.object({
|
||||||
userId: z.string().min(1, { error: 'User ID is required' }),
|
userId: z.string().min(1, { message: 'User ID is required' }),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -16,27 +19,38 @@ const schema = z.object({
|
|||||||
* If the user has multiple subscriptions,
|
* If the user has multiple subscriptions,
|
||||||
* it returns the most recent active or trialing one
|
* it returns the most recent active or trialing one
|
||||||
*/
|
*/
|
||||||
export const getActiveSubscriptionAction = userActionClient
|
export const getActiveSubscriptionAction = actionClient
|
||||||
.schema(schema)
|
.schema(schema)
|
||||||
.action(async ({ ctx }) => {
|
.action(async ({ parsedInput }) => {
|
||||||
const currentUser = (ctx as { user: User }).user;
|
const { userId } = parsedInput;
|
||||||
|
|
||||||
// Check if Stripe environment variables are configured
|
// Get the current user session for authorization
|
||||||
const stripeSecretKey = process.env.STRIPE_SECRET_KEY;
|
const session = await getSession();
|
||||||
const stripeWebhookSecret = process.env.STRIPE_WEBHOOK_SECRET;
|
if (!session) {
|
||||||
|
console.warn(
|
||||||
if (!stripeSecretKey || !stripeWebhookSecret) {
|
`unauthorized request to get active subscription for user ${userId}`
|
||||||
console.log('Stripe environment variables not configured, return');
|
);
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: false,
|
||||||
data: null, // No subscription = free plan
|
error: 'Unauthorized',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only allow users to check their own status unless they're admins
|
||||||
|
if (session.user.id !== userId && session.user.role !== 'admin') {
|
||||||
|
console.warn(
|
||||||
|
`current user ${session.user.id} is not authorized to get active subscription for user ${userId}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Not authorized to do this action',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Find the user's most recent active subscription
|
// Find the user's most recent active subscription
|
||||||
const subscriptions = await getSubscriptions({
|
const subscriptions = await getSubscriptions({
|
||||||
userId: currentUser.id,
|
userId: session.user.id,
|
||||||
});
|
});
|
||||||
// console.log('get user subscriptions:', subscriptions);
|
// console.log('get user subscriptions:', subscriptions);
|
||||||
|
|
||||||
@ -50,16 +64,16 @@ export const getActiveSubscriptionAction = userActionClient
|
|||||||
|
|
||||||
// If found, use it
|
// If found, use it
|
||||||
if (activeSubscription) {
|
if (activeSubscription) {
|
||||||
console.log('find active subscription for userId:', currentUser.id);
|
console.log('find active subscription for userId:', session.user.id);
|
||||||
subscriptionData = activeSubscription;
|
subscriptionData = activeSubscription;
|
||||||
} else {
|
} else {
|
||||||
console.log(
|
console.log(
|
||||||
'no active subscription found for userId:',
|
'no active subscription found for userId:',
|
||||||
currentUser.id
|
session.user.id
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.log('no subscriptions found for userId:', currentUser.id);
|
console.log('no subscriptions found for userId:', session.user.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
@ -1,27 +1,21 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { getUserCredits } from '@/credits/credits';
|
import { getUserCredits } from '@/credits/credits';
|
||||||
import type { User } from '@/lib/auth-types';
|
import { getSession } from '@/lib/server';
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
|
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get current user's credits
|
* Get current user's credits
|
||||||
*/
|
*/
|
||||||
export const getCreditBalanceAction = userActionClient.action(
|
export const getCreditBalanceAction = actionClient.action(async () => {
|
||||||
async ({ ctx }) => {
|
const session = await getSession();
|
||||||
try {
|
if (!session) {
|
||||||
const currentUser = (ctx as { user: User }).user;
|
console.warn('unauthorized request to get credit balance');
|
||||||
const credits = await getUserCredits(currentUser.id);
|
return { success: false, error: 'Unauthorized' };
|
||||||
return { success: true, credits };
|
|
||||||
} catch (error) {
|
|
||||||
console.error('get credit balance error:', error);
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
error:
|
|
||||||
error instanceof Error
|
|
||||||
? error.message
|
|
||||||
: 'Failed to fetch credit balance',
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
const credits = await getUserCredits(session.user.id);
|
||||||
|
return { success: true, credits };
|
||||||
|
});
|
||||||
|
@ -1,30 +1,42 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
|
import { CREDIT_TRANSACTION_TYPE } from '@/credits/types';
|
||||||
import { getDb } from '@/db';
|
import { getDb } from '@/db';
|
||||||
import { creditTransaction } from '@/db/schema';
|
import { creditTransaction } from '@/db/schema';
|
||||||
import type { User } from '@/lib/auth-types';
|
import { getSession } from '@/lib/server';
|
||||||
import { CREDITS_EXPIRATION_DAYS } from '@/lib/constants';
|
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
|
||||||
import { addDays } from 'date-fns';
|
import { addDays } from 'date-fns';
|
||||||
import { and, eq, gt, gte, isNotNull, lte, sum } from 'drizzle-orm';
|
import { and, eq, gte, isNotNull, lte, sql, sum } from 'drizzle-orm';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
|
|
||||||
|
const CREDITS_EXPIRATION_DAYS = 31;
|
||||||
|
const CREDITS_MONTHLY_DAYS = 31;
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get credit statistics for a user
|
* Get credit statistics for a user
|
||||||
*/
|
*/
|
||||||
export const getCreditStatsAction = userActionClient.action(async ({ ctx }) => {
|
export const getCreditStatsAction = actionClient.action(async () => {
|
||||||
try {
|
try {
|
||||||
const currentUser = (ctx as { user: User }).user;
|
const session = await getSession();
|
||||||
const userId = currentUser.id;
|
if (!session) {
|
||||||
|
console.warn('unauthorized request to get credit stats');
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const db = await getDb();
|
const db = await getDb();
|
||||||
const now = new Date();
|
const userId = session.user.id;
|
||||||
// Get credits expiring in the next 30 days
|
|
||||||
const expirationDaysFromNow = addDays(now, CREDITS_EXPIRATION_DAYS);
|
|
||||||
|
|
||||||
// Get total credits expiring in the next 30 days
|
// Get credits expiring in the next CREDITS_EXPIRATION_DAYS days
|
||||||
const expiringCreditsResult = await db
|
const expirationDaysFromNow = addDays(new Date(), CREDITS_EXPIRATION_DAYS);
|
||||||
|
const expiringCredits = await db
|
||||||
.select({
|
.select({
|
||||||
totalAmount: sum(creditTransaction.remainingAmount),
|
amount: sum(creditTransaction.remainingAmount),
|
||||||
|
earliestExpiration: sql<Date>`MIN(${creditTransaction.expirationDate})`,
|
||||||
})
|
})
|
||||||
.from(creditTransaction)
|
.from(creditTransaction)
|
||||||
.where(
|
.where(
|
||||||
@ -32,20 +44,56 @@ export const getCreditStatsAction = userActionClient.action(async ({ ctx }) => {
|
|||||||
eq(creditTransaction.userId, userId),
|
eq(creditTransaction.userId, userId),
|
||||||
isNotNull(creditTransaction.expirationDate),
|
isNotNull(creditTransaction.expirationDate),
|
||||||
isNotNull(creditTransaction.remainingAmount),
|
isNotNull(creditTransaction.remainingAmount),
|
||||||
gt(creditTransaction.remainingAmount, 0),
|
gte(creditTransaction.remainingAmount, 1),
|
||||||
lte(creditTransaction.expirationDate, expirationDaysFromNow),
|
lte(creditTransaction.expirationDate, expirationDaysFromNow),
|
||||||
gte(creditTransaction.expirationDate, now)
|
gte(creditTransaction.expirationDate, new Date())
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
const totalExpiringCredits =
|
// Get credits from subscription renewals (recent CREDITS_MONTHLY_DAYS days)
|
||||||
Number(expiringCreditsResult[0]?.totalAmount) || 0;
|
const monthlyRefreshDaysAgo = addDays(new Date(), -CREDITS_MONTHLY_DAYS);
|
||||||
|
const subscriptionCredits = await db
|
||||||
|
.select({
|
||||||
|
amount: sum(creditTransaction.amount),
|
||||||
|
})
|
||||||
|
.from(creditTransaction)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(creditTransaction.userId, userId),
|
||||||
|
eq(
|
||||||
|
creditTransaction.type,
|
||||||
|
CREDIT_TRANSACTION_TYPE.SUBSCRIPTION_RENEWAL
|
||||||
|
),
|
||||||
|
gte(creditTransaction.createdAt, monthlyRefreshDaysAgo)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Get credits from monthly lifetime distribution (recent CREDITS_MONTHLY_DAYS days)
|
||||||
|
const lifetimeCredits = await db
|
||||||
|
.select({
|
||||||
|
amount: sum(creditTransaction.amount),
|
||||||
|
})
|
||||||
|
.from(creditTransaction)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(creditTransaction.userId, userId),
|
||||||
|
eq(creditTransaction.type, CREDIT_TRANSACTION_TYPE.LIFETIME_MONTHLY),
|
||||||
|
gte(creditTransaction.createdAt, monthlyRefreshDaysAgo)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
data: {
|
data: {
|
||||||
expiringCredits: {
|
expiringCredits: {
|
||||||
amount: totalExpiringCredits,
|
amount: Number(expiringCredits[0]?.amount) || 0,
|
||||||
|
earliestExpiration: expiringCredits[0]?.earliestExpiration || null,
|
||||||
|
},
|
||||||
|
subscriptionCredits: {
|
||||||
|
amount: Number(subscriptionCredits[0]?.amount) || 0,
|
||||||
|
},
|
||||||
|
lifetimeCredits: {
|
||||||
|
amount: Number(lifetimeCredits[0]?.amount) || 0,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
@ -2,11 +2,14 @@
|
|||||||
|
|
||||||
import { getDb } from '@/db';
|
import { getDb } from '@/db';
|
||||||
import { creditTransaction } from '@/db/schema';
|
import { creditTransaction } from '@/db/schema';
|
||||||
import type { User } from '@/lib/auth-types';
|
import { getSession } from '@/lib/server';
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
|
||||||
import { and, asc, desc, eq, ilike, or, sql } from 'drizzle-orm';
|
import { and, asc, desc, eq, ilike, or, sql } from 'drizzle-orm';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Define the schema for getCreditTransactions parameters
|
// Define the schema for getCreditTransactions parameters
|
||||||
const getCreditTransactionsSchema = z.object({
|
const getCreditTransactionsSchema = z.object({
|
||||||
pageIndex: z.number().min(0).default(0),
|
pageIndex: z.number().min(0).default(0),
|
||||||
@ -37,39 +40,32 @@ const sortFieldMap = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
// Create a safe action for getting credit transactions
|
// Create a safe action for getting credit transactions
|
||||||
export const getCreditTransactionsAction = userActionClient
|
export const getCreditTransactionsAction = actionClient
|
||||||
.schema(getCreditTransactionsSchema)
|
.schema(getCreditTransactionsSchema)
|
||||||
.action(async ({ parsedInput, ctx }) => {
|
.action(async ({ parsedInput }) => {
|
||||||
try {
|
try {
|
||||||
const { pageIndex, pageSize, search, sorting } = parsedInput;
|
const session = await getSession();
|
||||||
const currentUser = (ctx as { user: User }).user;
|
if (!session) {
|
||||||
|
return {
|
||||||
// Search logic: text fields use ilike, and if search is a number, also search amount fields
|
success: false,
|
||||||
const searchConditions = [];
|
error: 'Unauthorized',
|
||||||
if (search) {
|
};
|
||||||
// Always search text fields
|
|
||||||
searchConditions.push(
|
|
||||||
ilike(creditTransaction.type, `%${search}%`),
|
|
||||||
ilike(creditTransaction.paymentId, `%${search}%`),
|
|
||||||
ilike(creditTransaction.description, `%${search}%`)
|
|
||||||
);
|
|
||||||
|
|
||||||
// If search is a valid number, also search numeric fields
|
|
||||||
const numericSearch = Number.parseInt(search, 10);
|
|
||||||
if (!Number.isNaN(numericSearch)) {
|
|
||||||
searchConditions.push(
|
|
||||||
eq(creditTransaction.amount, numericSearch),
|
|
||||||
eq(creditTransaction.remainingAmount, numericSearch)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
const { pageIndex, pageSize, search, sorting } = parsedInput;
|
||||||
|
|
||||||
|
// search by type, amount, paymentId, description, and restrict to current user
|
||||||
const where = search
|
const where = search
|
||||||
? and(
|
? and(
|
||||||
eq(creditTransaction.userId, currentUser.id),
|
eq(creditTransaction.userId, session.user.id),
|
||||||
or(...searchConditions)
|
or(
|
||||||
|
ilike(creditTransaction.type, `%${search}%`),
|
||||||
|
ilike(creditTransaction.amount, `%${search}%`),
|
||||||
|
ilike(creditTransaction.remainingAmount, `%${search}%`),
|
||||||
|
ilike(creditTransaction.paymentId, `%${search}%`),
|
||||||
|
ilike(creditTransaction.description, `%${search}%`)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
: eq(creditTransaction.userId, currentUser.id);
|
: eq(creditTransaction.userId, session.user.id);
|
||||||
|
|
||||||
const offset = pageIndex * pageSize;
|
const offset = pageIndex * pageSize;
|
||||||
|
|
||||||
|
@ -2,16 +2,19 @@
|
|||||||
|
|
||||||
import { getDb } from '@/db';
|
import { getDb } from '@/db';
|
||||||
import { payment } from '@/db/schema';
|
import { payment } from '@/db/schema';
|
||||||
import type { User } from '@/lib/auth-types';
|
|
||||||
import { findPlanByPriceId, getAllPricePlans } from '@/lib/price-plan';
|
import { findPlanByPriceId, getAllPricePlans } from '@/lib/price-plan';
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
import { getSession } from '@/lib/server';
|
||||||
import { PaymentTypes } from '@/payment/types';
|
import { PaymentTypes } from '@/payment/types';
|
||||||
import { and, eq } from 'drizzle-orm';
|
import { and, eq } from 'drizzle-orm';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Input schema
|
// Input schema
|
||||||
const schema = z.object({
|
const schema = z.object({
|
||||||
userId: z.string().min(1, { error: 'User ID is required' }),
|
userId: z.string().min(1, { message: 'User ID is required' }),
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -22,11 +25,33 @@ const schema = z.object({
|
|||||||
* in order to do this, you have to update the logic to check the lifetime status,
|
* in order to do this, you have to update the logic to check the lifetime status,
|
||||||
* for example, just check the planId is `lifetime` or not.
|
* for example, just check the planId is `lifetime` or not.
|
||||||
*/
|
*/
|
||||||
export const getLifetimeStatusAction = userActionClient
|
export const getLifetimeStatusAction = actionClient
|
||||||
.schema(schema)
|
.schema(schema)
|
||||||
.action(async ({ ctx }) => {
|
.action(async ({ parsedInput }) => {
|
||||||
const currentUser = (ctx as { user: User }).user;
|
const { userId } = parsedInput;
|
||||||
const userId = currentUser.id;
|
|
||||||
|
// Get the current user session for authorization
|
||||||
|
const session = await getSession();
|
||||||
|
if (!session) {
|
||||||
|
console.warn(
|
||||||
|
`unauthorized request to get lifetime status for user ${userId}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only allow users to check their own status unless they're admins
|
||||||
|
if (session.user.id !== userId && session.user.role !== 'admin') {
|
||||||
|
console.warn(
|
||||||
|
`current user ${session.user.id} is not authorized to get lifetime status for user ${userId}`
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Not authorized to do this action',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get lifetime plans
|
// Get lifetime plans
|
||||||
|
@ -2,11 +2,13 @@
|
|||||||
|
|
||||||
import { getDb } from '@/db';
|
import { getDb } from '@/db';
|
||||||
import { user } from '@/db/schema';
|
import { user } from '@/db/schema';
|
||||||
import { isDemoWebsite } from '@/lib/demo';
|
|
||||||
import { adminActionClient } from '@/lib/safe-action';
|
|
||||||
import { asc, desc, ilike, or, sql } from 'drizzle-orm';
|
import { asc, desc, ilike, or, sql } from 'drizzle-orm';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Define the schema for getUsers parameters
|
// Define the schema for getUsers parameters
|
||||||
const getUsersSchema = z.object({
|
const getUsersSchema = z.object({
|
||||||
pageIndex: z.number().min(0).default(0),
|
pageIndex: z.number().min(0).default(0),
|
||||||
@ -36,7 +38,7 @@ const sortFieldMap = {
|
|||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
// Create a safe action for getting users
|
// Create a safe action for getting users
|
||||||
export const getUsersAction = adminActionClient
|
export const getUsersAction = actionClient
|
||||||
.schema(getUsersSchema)
|
.schema(getUsersSchema)
|
||||||
.action(async ({ parsedInput }) => {
|
.action(async ({ parsedInput }) => {
|
||||||
try {
|
try {
|
||||||
@ -73,8 +75,7 @@ export const getUsersAction = adminActionClient
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
// hide user data in demo website
|
// hide user data in demo website
|
||||||
const isDemo = isDemoWebsite();
|
if (process.env.NEXT_PUBLIC_DEMO_WEBSITE === 'true') {
|
||||||
if (isDemo) {
|
|
||||||
items = items.map((item) => ({
|
items = items.map((item) => ({
|
||||||
...item,
|
...item,
|
||||||
name: 'Demo User',
|
name: 'Demo User',
|
||||||
|
@ -1,11 +1,14 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { websiteConfig } from '@/config/website';
|
import { websiteConfig } from '@/config/website';
|
||||||
import { actionClient } from '@/lib/safe-action';
|
|
||||||
import { sendEmail } from '@/mail';
|
import { sendEmail } from '@/mail';
|
||||||
import { getLocale } from 'next-intl/server';
|
import { getLocale } from 'next-intl/server';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DOC: When using Zod for validation, how can I localize error messages?
|
* DOC: When using Zod for validation, how can I localize error messages?
|
||||||
* https://next-intl.dev/docs/environments/actions-metadata-route-handlers#server-actions
|
* https://next-intl.dev/docs/environments/actions-metadata-route-handlers#server-actions
|
||||||
@ -14,13 +17,13 @@ import { z } from 'zod';
|
|||||||
const contactFormSchema = z.object({
|
const contactFormSchema = z.object({
|
||||||
name: z
|
name: z
|
||||||
.string()
|
.string()
|
||||||
.min(3, { error: 'Name must be at least 3 characters' })
|
.min(3, { message: 'Name must be at least 3 characters' })
|
||||||
.max(30, { error: 'Name must not exceed 30 characters' }),
|
.max(30, { message: 'Name must not exceed 30 characters' }),
|
||||||
email: z.email({ error: 'Please enter a valid email address' }),
|
email: z.string().email({ message: 'Please enter a valid email address' }),
|
||||||
message: z
|
message: z
|
||||||
.string()
|
.string()
|
||||||
.min(10, { error: 'Message must be at least 10 characters' })
|
.min(10, { message: 'Message must be at least 10 characters' })
|
||||||
.max(500, { error: 'Message must not exceed 500 characters' }),
|
.max(500, { message: 'Message must not exceed 500 characters' }),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create a safe action for contact form submission
|
// Create a safe action for contact form submission
|
||||||
|
@ -1,14 +1,17 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { actionClient } from '@/lib/safe-action';
|
|
||||||
import { sendEmail } from '@/mail';
|
import { sendEmail } from '@/mail';
|
||||||
import { subscribe } from '@/newsletter';
|
import { subscribe } from '@/newsletter';
|
||||||
import { getLocale } from 'next-intl/server';
|
import { getLocale } from 'next-intl/server';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Newsletter schema for validation
|
// Newsletter schema for validation
|
||||||
const newsletterSchema = z.object({
|
const newsletterSchema = z.object({
|
||||||
email: z.email({ error: 'Please enter a valid email address' }),
|
email: z.string().email({ message: 'Please enter a valid email address' }),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create a safe action for newsletter subscription
|
// Create a safe action for newsletter subscription
|
||||||
|
@ -1,18 +1,30 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { userActionClient } from '@/lib/safe-action';
|
import { getSession } from '@/lib/server';
|
||||||
import { unsubscribe } from '@/newsletter';
|
import { unsubscribe } from '@/newsletter';
|
||||||
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Newsletter schema for validation
|
// Newsletter schema for validation
|
||||||
const newsletterSchema = z.object({
|
const newsletterSchema = z.object({
|
||||||
email: z.email({ error: 'Please enter a valid email address' }),
|
email: z.string().email({ message: 'Please enter a valid email address' }),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create a safe action for newsletter unsubscription
|
// Create a safe action for newsletter unsubscription
|
||||||
export const unsubscribeNewsletterAction = userActionClient
|
export const unsubscribeNewsletterAction = actionClient
|
||||||
.schema(newsletterSchema)
|
.schema(newsletterSchema)
|
||||||
.action(async ({ parsedInput: { email } }) => {
|
.action(async ({ parsedInput: { email } }) => {
|
||||||
|
const session = await getSession();
|
||||||
|
if (!session) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const unsubscribed = await unsubscribe(email);
|
const unsubscribed = await unsubscribe(email);
|
||||||
|
|
||||||
|
@ -1,12 +1,15 @@
|
|||||||
'use server';
|
'use server';
|
||||||
|
|
||||||
import { validateTurnstileToken } from '@/lib/captcha';
|
import { validateTurnstileToken } from '@/lib/captcha';
|
||||||
import { actionClient } from '@/lib/safe-action';
|
import { createSafeActionClient } from 'next-safe-action';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
// Create a safe action client
|
||||||
|
const actionClient = createSafeActionClient();
|
||||||
|
|
||||||
// Captcha validation schema
|
// Captcha validation schema
|
||||||
const captchaSchema = z.object({
|
const captchaSchema = z.object({
|
||||||
captchaToken: z.string().min(1, { error: 'Captcha token is required' }),
|
captchaToken: z.string().min(1, { message: 'Captcha token is required' }),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create a safe action for captcha validation
|
// Create a safe action for captcha validation
|
||||||
|
@ -1,181 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import {
|
|
||||||
Conversation,
|
|
||||||
ConversationContent,
|
|
||||||
ConversationScrollButton,
|
|
||||||
} from '@/components/ai-elements/conversation';
|
|
||||||
import { Loader } from '@/components/ai-elements/loader';
|
|
||||||
import { Message, MessageContent } from '@/components/ai-elements/message';
|
|
||||||
import {
|
|
||||||
PromptInput,
|
|
||||||
PromptInputButton,
|
|
||||||
PromptInputModelSelect,
|
|
||||||
PromptInputModelSelectContent,
|
|
||||||
PromptInputModelSelectItem,
|
|
||||||
PromptInputModelSelectTrigger,
|
|
||||||
PromptInputModelSelectValue,
|
|
||||||
PromptInputSubmit,
|
|
||||||
PromptInputTextarea,
|
|
||||||
PromptInputToolbar,
|
|
||||||
PromptInputTools,
|
|
||||||
} from '@/components/ai-elements/prompt-input';
|
|
||||||
import {
|
|
||||||
Reasoning,
|
|
||||||
ReasoningContent,
|
|
||||||
ReasoningTrigger,
|
|
||||||
} from '@/components/ai-elements/reasoning';
|
|
||||||
import { Response } from '@/components/ai-elements/response';
|
|
||||||
import {
|
|
||||||
Source,
|
|
||||||
Sources,
|
|
||||||
SourcesContent,
|
|
||||||
SourcesTrigger,
|
|
||||||
} from '@/components/ai-elements/source';
|
|
||||||
import { useChat } from '@ai-sdk/react';
|
|
||||||
import { GlobeIcon } from 'lucide-react';
|
|
||||||
import { useState } from 'react';
|
|
||||||
|
|
||||||
const models = [
|
|
||||||
{
|
|
||||||
name: 'GPT 4o',
|
|
||||||
value: 'openai/gpt-4o',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'Deepseek R1',
|
|
||||||
value: 'deepseek/deepseek-r1',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export default function ChatBot() {
|
|
||||||
const [input, setInput] = useState('');
|
|
||||||
const [model, setModel] = useState<string>(models[0].value);
|
|
||||||
const [webSearch, setWebSearch] = useState(false);
|
|
||||||
const { messages, sendMessage, status } = useChat();
|
|
||||||
|
|
||||||
const handleSubmit = (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
if (input.trim()) {
|
|
||||||
sendMessage(
|
|
||||||
{ text: input },
|
|
||||||
{
|
|
||||||
body: {
|
|
||||||
model: model,
|
|
||||||
webSearch: webSearch,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
setInput('');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="mx-auto p-6 relative size-full h-screen rounded-lg bg-muted">
|
|
||||||
<div className="flex flex-col h-full">
|
|
||||||
<Conversation className="h-full">
|
|
||||||
<ConversationContent>
|
|
||||||
{messages.map((message) => (
|
|
||||||
<div key={message.id}>
|
|
||||||
{message.role === 'assistant' && (
|
|
||||||
<Sources>
|
|
||||||
{message.parts.map((part, i) => {
|
|
||||||
switch (part.type) {
|
|
||||||
case 'source-url':
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<SourcesTrigger
|
|
||||||
count={
|
|
||||||
message.parts.filter(
|
|
||||||
(part) => part.type === 'source-url'
|
|
||||||
).length
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
<SourcesContent key={`${message.id}-${i}`}>
|
|
||||||
<Source
|
|
||||||
key={`${message.id}-${i}`}
|
|
||||||
href={part.url}
|
|
||||||
title={part.url}
|
|
||||||
/>
|
|
||||||
</SourcesContent>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
})}
|
|
||||||
</Sources>
|
|
||||||
)}
|
|
||||||
<Message from={message.role} key={message.id}>
|
|
||||||
<MessageContent>
|
|
||||||
{message.parts.map((part, i) => {
|
|
||||||
switch (part.type) {
|
|
||||||
case 'text':
|
|
||||||
return (
|
|
||||||
<Response key={`${message.id}-${i}`}>
|
|
||||||
{part.text}
|
|
||||||
</Response>
|
|
||||||
);
|
|
||||||
case 'reasoning':
|
|
||||||
return (
|
|
||||||
<Reasoning
|
|
||||||
key={`${message.id}-${i}`}
|
|
||||||
className="w-full"
|
|
||||||
isStreaming={status === 'streaming'}
|
|
||||||
>
|
|
||||||
<ReasoningTrigger />
|
|
||||||
<ReasoningContent>{part.text}</ReasoningContent>
|
|
||||||
</Reasoning>
|
|
||||||
);
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
})}
|
|
||||||
</MessageContent>
|
|
||||||
</Message>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
{status === 'submitted' && <Loader />}
|
|
||||||
</ConversationContent>
|
|
||||||
<ConversationScrollButton />
|
|
||||||
</Conversation>
|
|
||||||
|
|
||||||
<PromptInput onSubmit={handleSubmit} className="mt-4">
|
|
||||||
<PromptInputTextarea
|
|
||||||
onChange={(e) => setInput(e.target.value)}
|
|
||||||
value={input}
|
|
||||||
/>
|
|
||||||
<PromptInputToolbar>
|
|
||||||
<PromptInputTools>
|
|
||||||
<PromptInputButton
|
|
||||||
variant={webSearch ? 'default' : 'ghost'}
|
|
||||||
onClick={() => setWebSearch(!webSearch)}
|
|
||||||
>
|
|
||||||
<GlobeIcon size={16} />
|
|
||||||
<span>Search</span>
|
|
||||||
</PromptInputButton>
|
|
||||||
<PromptInputModelSelect
|
|
||||||
onValueChange={(value) => {
|
|
||||||
setModel(value);
|
|
||||||
}}
|
|
||||||
value={model}
|
|
||||||
>
|
|
||||||
<PromptInputModelSelectTrigger>
|
|
||||||
<PromptInputModelSelectValue />
|
|
||||||
</PromptInputModelSelectTrigger>
|
|
||||||
<PromptInputModelSelectContent>
|
|
||||||
{models.map((model) => (
|
|
||||||
<PromptInputModelSelectItem
|
|
||||||
key={model.value}
|
|
||||||
value={model.value}
|
|
||||||
>
|
|
||||||
{model.name}
|
|
||||||
</PromptInputModelSelectItem>
|
|
||||||
))}
|
|
||||||
</PromptInputModelSelectContent>
|
|
||||||
</PromptInputModelSelect>
|
|
||||||
</PromptInputTools>
|
|
||||||
<PromptInputSubmit disabled={!input} status={status} />
|
|
||||||
</PromptInputToolbar>
|
|
||||||
</PromptInput>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
@ -61,6 +61,7 @@ export function ImagePlayground({
|
|||||||
|
|
||||||
const providerToModel = {
|
const providerToModel = {
|
||||||
replicate: selectedModels.replicate,
|
replicate: selectedModels.replicate,
|
||||||
|
// vertex: selectedModels.vertex,
|
||||||
openai: selectedModels.openai,
|
openai: selectedModels.openai,
|
||||||
fireworks: selectedModels.fireworks,
|
fireworks: selectedModels.fireworks,
|
||||||
fal: selectedModels.fal,
|
fal: selectedModels.fal,
|
||||||
@ -76,9 +77,9 @@ export function ImagePlayground({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="rounded-lg bg-background py-8 px-4 sm:px-6 lg:px-8">
|
<div className="rounded-lg bg-background py-8 px-4 sm:px-6 lg:px-8">
|
||||||
<div className="mx-auto">
|
<div className="max-w-7xl mx-auto">
|
||||||
{/* header */}
|
{/* header */}
|
||||||
{/* <ImageGeneratorHeader /> */}
|
<ImageGeneratorHeader />
|
||||||
|
|
||||||
{/* input prompt */}
|
{/* input prompt */}
|
||||||
<PromptInput
|
<PromptInput
|
||||||
|
@ -15,6 +15,7 @@ import {
|
|||||||
FireworksIcon,
|
FireworksIcon,
|
||||||
OpenAIIcon,
|
OpenAIIcon,
|
||||||
ReplicateIcon,
|
ReplicateIcon,
|
||||||
|
// VertexIcon,
|
||||||
falAILogo,
|
falAILogo,
|
||||||
} from '../lib/logos';
|
} from '../lib/logos';
|
||||||
import type { ProviderKey } from '../lib/provider-config';
|
import type { ProviderKey } from '../lib/provider-config';
|
||||||
@ -39,6 +40,7 @@ interface ModelSelectProps {
|
|||||||
const PROVIDER_ICONS = {
|
const PROVIDER_ICONS = {
|
||||||
openai: OpenAIIcon,
|
openai: OpenAIIcon,
|
||||||
replicate: ReplicateIcon,
|
replicate: ReplicateIcon,
|
||||||
|
// vertex: VertexIcon,
|
||||||
fireworks: FireworksIcon,
|
fireworks: FireworksIcon,
|
||||||
fal: falAILogo,
|
fal: falAILogo,
|
||||||
} as const;
|
} as const;
|
||||||
@ -46,6 +48,7 @@ const PROVIDER_ICONS = {
|
|||||||
const PROVIDER_LINKS = {
|
const PROVIDER_LINKS = {
|
||||||
openai: 'openai',
|
openai: 'openai',
|
||||||
replicate: 'replicate',
|
replicate: 'replicate',
|
||||||
|
// vertex: 'google-vertex',
|
||||||
fireworks: 'fireworks',
|
fireworks: 'fireworks',
|
||||||
fal: 'fal',
|
fal: 'fal',
|
||||||
} as const;
|
} as const;
|
||||||
|
@ -62,6 +62,55 @@ export const ReplicateIcon = ({ size = 16 }) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const VertexIcon = ({ size = 16 }) => {
|
||||||
|
return (
|
||||||
|
<svg
|
||||||
|
height={size}
|
||||||
|
width={size}
|
||||||
|
viewBox="0 0 512 512"
|
||||||
|
xmlns="http://www.w3.org/2000/svg"
|
||||||
|
style={{ color: 'currentcolor' }}
|
||||||
|
>
|
||||||
|
<g transform="scale(0.8) translate(65,65)">
|
||||||
|
<path
|
||||||
|
d="M128,249c-8.8,0-16-7.2-16-16v-105c0-8.8,7.2-16,16-16s16,7.2,16,16v105c0,8.8-7.2,16-16,16Z"
|
||||||
|
fill="white"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M256,464c-3,0-6-.8-8.6-2.5l-176-112c-7.5-4.7-9.7-14.6-4.9-22.1,4.8-7.5,14.6-9.6,22.1-4.9l167.4,106.5,167.4-106.5c7.5-4.7,17.3-2.5,22.1,4.9,4.7,7.5,2.5,17.3-4.9,22.1l-176,112c-2.6,1.7-5.6,2.5-8.6,2.5h0Z"
|
||||||
|
fill="white"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d="M256,394c-8.8,0-16-7.2-16-16v-73.1c0-8.8,7.2-16,16-16s16,7.2,16,16v73.1c0,8.8-7.2,16-16,16Z"
|
||||||
|
fill="white"
|
||||||
|
/>
|
||||||
|
<circle cx="128" cy="64" r="16" fill="white" />
|
||||||
|
<circle cx="128" cy="297" r="16" fill="white" />
|
||||||
|
<path
|
||||||
|
d="M384.2,314c-8.8,0-16-7.1-16-16l-.2-106c0-8.8,7.1-16,16-16h0c8.8,0,16,7.1,16,16l.2,106c0,8.8-7.1,16-16,16h0Z"
|
||||||
|
fill="white"
|
||||||
|
/>
|
||||||
|
<circle cx="384" cy="64" r="16" fill="white" />
|
||||||
|
<circle cx="384" cy="128" r="16" fill="white" />
|
||||||
|
<path
|
||||||
|
d="M320,225c-8.8,0-16-7.2-16-16v-103c0-8.8,7.2-16,16-16s16,7.2,16,16v103c0,8.8-7.2,16-16,16Z"
|
||||||
|
fill="white"
|
||||||
|
/>
|
||||||
|
<circle cx="256" cy="177" r="16" fill="white" />
|
||||||
|
<circle cx="256" cy="241" r="16" fill="white" />
|
||||||
|
<circle cx="320" cy="273" r="16" fill="white" />
|
||||||
|
<circle cx="320" cy="337" r="16" fill="white" />
|
||||||
|
<path
|
||||||
|
d="M192,225c-8.8,0-16-7.2-16-16v-103c0-8.8,7.2-16,16-16s16,7.2,16,16v103c0,8.8-7.2,16-16,16Z"
|
||||||
|
fill="white"
|
||||||
|
/>
|
||||||
|
<circle cx="192" cy="273" r="16" fill="white" />
|
||||||
|
<circle cx="192" cy="337" r="16" fill="white" />
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export const falAILogo = ({ size = 16 }: { size: number }) => {
|
export const falAILogo = ({ size = 16 }: { size: number }) => {
|
||||||
return (
|
return (
|
||||||
<svg
|
<svg
|
||||||
|
@ -1,4 +1,9 @@
|
|||||||
export type ProviderKey = 'replicate' | 'openai' | 'fireworks' | 'fal';
|
export type ProviderKey =
|
||||||
|
| 'replicate'
|
||||||
|
// | 'vertex'
|
||||||
|
| 'openai'
|
||||||
|
| 'fireworks'
|
||||||
|
| 'fal';
|
||||||
export type ModelMode = 'performance' | 'quality';
|
export type ModelMode = 'performance' | 'quality';
|
||||||
|
|
||||||
export const PROVIDERS: Record<
|
export const PROVIDERS: Record<
|
||||||
@ -32,6 +37,12 @@ export const PROVIDERS: Record<
|
|||||||
'stability-ai/stable-diffusion-3.5-large-turbo',
|
'stability-ai/stable-diffusion-3.5-large-turbo',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
// vertex: {
|
||||||
|
// displayName: 'Vertex AI',
|
||||||
|
// iconPath: '/provider-icons/vertex.svg',
|
||||||
|
// color: 'from-green-500 to-emerald-500',
|
||||||
|
// models: ['imagen-3.0-generate-001', 'imagen-3.0-fast-generate-001'],
|
||||||
|
// },
|
||||||
// https://ai-sdk.dev/providers/ai-sdk-providers/openai#image-models
|
// https://ai-sdk.dev/providers/ai-sdk-providers/openai#image-models
|
||||||
openai: {
|
openai: {
|
||||||
displayName: 'OpenAI',
|
displayName: 'OpenAI',
|
||||||
@ -81,12 +92,14 @@ export const PROVIDERS: Record<
|
|||||||
export const MODEL_CONFIGS: Record<ModelMode, Record<ProviderKey, string>> = {
|
export const MODEL_CONFIGS: Record<ModelMode, Record<ProviderKey, string>> = {
|
||||||
performance: {
|
performance: {
|
||||||
replicate: 'black-forest-labs/flux-1.1-pro',
|
replicate: 'black-forest-labs/flux-1.1-pro',
|
||||||
|
// vertex: 'imagen-3.0-fast-generate-001',
|
||||||
openai: 'dall-e-3',
|
openai: 'dall-e-3',
|
||||||
fireworks: 'accounts/fireworks/models/flux-1-schnell-fp8',
|
fireworks: 'accounts/fireworks/models/flux-1-schnell-fp8',
|
||||||
fal: 'fal-ai/flux/dev',
|
fal: 'fal-ai/flux/dev',
|
||||||
},
|
},
|
||||||
quality: {
|
quality: {
|
||||||
replicate: 'stability-ai/stable-diffusion-3.5-large',
|
replicate: 'stability-ai/stable-diffusion-3.5-large',
|
||||||
|
// vertex: 'imagen-3.0-generate-001',
|
||||||
openai: 'dall-e-3',
|
openai: 'dall-e-3',
|
||||||
fireworks: 'accounts/fireworks/models/flux-1-dev-fp8',
|
fireworks: 'accounts/fireworks/models/flux-1-dev-fp8',
|
||||||
fal: 'fal-ai/flux-pro/v1.1-ultra',
|
fal: 'fal-ai/flux-pro/v1.1-ultra',
|
||||||
@ -95,6 +108,7 @@ export const MODEL_CONFIGS: Record<ModelMode, Record<ProviderKey, string>> = {
|
|||||||
|
|
||||||
export const PROVIDER_ORDER: ProviderKey[] = [
|
export const PROVIDER_ORDER: ProviderKey[] = [
|
||||||
'replicate',
|
'replicate',
|
||||||
|
// 'vertex',
|
||||||
'openai',
|
'openai',
|
||||||
'fireworks',
|
'fireworks',
|
||||||
'fal',
|
'fal',
|
||||||
|
51
src/ai/text/components/consume-credit-card.tsx
Normal file
51
src/ai/text/components/consume-credit-card.tsx
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { CreditsBalanceButton } from '@/components/layout/credits-balance-button';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { useCredits } from '@/hooks/use-credits';
|
||||||
|
import { CoinsIcon } from 'lucide-react';
|
||||||
|
import { useState } from 'react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
const CONSUME_CREDITS = 50;
|
||||||
|
|
||||||
|
export function ConsumeCreditCard() {
|
||||||
|
const { consumeCredits, hasEnoughCredits, isLoading } = useCredits();
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
|
||||||
|
const handleConsume = async () => {
|
||||||
|
if (!hasEnoughCredits(CONSUME_CREDITS)) {
|
||||||
|
toast.error('Insufficient credits, please buy more credits.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
const success = await consumeCredits(
|
||||||
|
CONSUME_CREDITS,
|
||||||
|
`AI Text Credit Consumption (${CONSUME_CREDITS} credits)`
|
||||||
|
);
|
||||||
|
setLoading(false);
|
||||||
|
if (success) {
|
||||||
|
toast.success(`${CONSUME_CREDITS} credits have been consumed.`);
|
||||||
|
} else {
|
||||||
|
toast.error('Failed to consume credits, please try again later.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col items-center gap-8 p-4 border rounded-lg">
|
||||||
|
<div className="w-full flex flex-row items-center justify-end">
|
||||||
|
<CreditsBalanceButton />
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={handleConsume}
|
||||||
|
disabled={isLoading || loading}
|
||||||
|
className="w-full cursor-pointer"
|
||||||
|
>
|
||||||
|
<CoinsIcon className="size-4" />
|
||||||
|
<span>Consume {CONSUME_CREDITS} credits</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
@ -34,6 +34,7 @@ interface ErrorDisplayProps {
|
|||||||
const errorIcons = {
|
const errorIcons = {
|
||||||
[ErrorType.VALIDATION]: AlertCircleIcon,
|
[ErrorType.VALIDATION]: AlertCircleIcon,
|
||||||
[ErrorType.NETWORK]: WifiOffIcon,
|
[ErrorType.NETWORK]: WifiOffIcon,
|
||||||
|
[ErrorType.CREDITS]: CreditCardIcon,
|
||||||
[ErrorType.SCRAPING]: ServerIcon,
|
[ErrorType.SCRAPING]: ServerIcon,
|
||||||
[ErrorType.ANALYSIS]: HelpCircleIcon,
|
[ErrorType.ANALYSIS]: HelpCircleIcon,
|
||||||
[ErrorType.TIMEOUT]: ClockIcon,
|
[ErrorType.TIMEOUT]: ClockIcon,
|
||||||
@ -83,6 +84,7 @@ const severityColors = {
|
|||||||
const errorTitles = {
|
const errorTitles = {
|
||||||
[ErrorType.VALIDATION]: 'Invalid Input',
|
[ErrorType.VALIDATION]: 'Invalid Input',
|
||||||
[ErrorType.NETWORK]: 'Connection Error',
|
[ErrorType.NETWORK]: 'Connection Error',
|
||||||
|
[ErrorType.CREDITS]: 'Insufficient Credits',
|
||||||
[ErrorType.SCRAPING]: 'Unable to Access Website',
|
[ErrorType.SCRAPING]: 'Unable to Access Website',
|
||||||
[ErrorType.ANALYSIS]: 'Analysis Failed',
|
[ErrorType.ANALYSIS]: 'Analysis Failed',
|
||||||
[ErrorType.TIMEOUT]: 'Request Timed Out',
|
[ErrorType.TIMEOUT]: 'Request Timed Out',
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
export { AnalysisResults } from './analysis-results';
|
export { AnalysisResults } from './analysis-results';
|
||||||
|
export { ConsumeCreditCard } from './consume-credit-card';
|
||||||
export { LoadingStates } from './loading-states';
|
export { LoadingStates } from './loading-states';
|
||||||
export { UrlInputForm } from './url-input-form';
|
export { UrlInputForm } from './url-input-form';
|
||||||
export { WebContentAnalyzer } from './web-content-analyzer';
|
export { WebContentAnalyzer } from './web-content-analyzer';
|
||||||
|
@ -1,7 +1,12 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import type { UrlInputFormProps } from '@/ai/text/utils/web-content-analyzer';
|
import { checkWebContentAnalysisCreditsAction } from '@/actions/check-web-content-analysis-credits';
|
||||||
|
import {
|
||||||
|
type UrlInputFormProps,
|
||||||
|
urlSchema,
|
||||||
|
} from '@/ai/text/utils/web-content-analyzer';
|
||||||
import { webContentAnalyzerConfig } from '@/ai/text/utils/web-content-analyzer-config';
|
import { webContentAnalyzerConfig } from '@/ai/text/utils/web-content-analyzer-config';
|
||||||
|
import { LoginWrapper } from '@/components/auth/login-wrapper';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import {
|
import {
|
||||||
Form,
|
Form,
|
||||||
@ -11,23 +16,27 @@ import {
|
|||||||
FormMessage,
|
FormMessage,
|
||||||
} from '@/components/ui/form';
|
} from '@/components/ui/form';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import {
|
import { useLocalePathname } from '@/i18n/navigation';
|
||||||
Select,
|
import { authClient } from '@/lib/auth-client';
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from '@/components/ui/select';
|
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
import { LinkIcon, Loader2Icon, SparklesIcon } from 'lucide-react';
|
import {
|
||||||
|
AlertCircleIcon,
|
||||||
|
CoinsIcon,
|
||||||
|
LinkIcon,
|
||||||
|
Loader2Icon,
|
||||||
|
LogInIcon,
|
||||||
|
SparklesIcon,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { useAction } from 'next-safe-action/hooks';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
import { useForm } from 'react-hook-form';
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { toast } from 'sonner';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { useDebounce } from '../utils/performance';
|
import { useDebounce } from '../utils/performance';
|
||||||
|
|
||||||
// Form schema for URL input
|
// Form schema for URL input
|
||||||
const urlFormSchema = z.object({
|
const urlFormSchema = z.object({
|
||||||
url: z.url().optional(), // Allow empty string for initial state
|
url: urlSchema,
|
||||||
});
|
});
|
||||||
|
|
||||||
type UrlFormData = z.infer<typeof urlFormSchema>;
|
type UrlFormData = z.infer<typeof urlFormSchema>;
|
||||||
@ -36,12 +45,20 @@ export function UrlInputForm({
|
|||||||
onSubmit,
|
onSubmit,
|
||||||
isLoading,
|
isLoading,
|
||||||
disabled = false,
|
disabled = false,
|
||||||
modelProvider,
|
|
||||||
setModelProvider,
|
|
||||||
}: UrlInputFormProps) {
|
}: UrlInputFormProps) {
|
||||||
|
const [creditInfo, setCreditInfo] = useState<{
|
||||||
|
hasEnoughCredits: boolean;
|
||||||
|
currentCredits: number;
|
||||||
|
requiredCredits: number;
|
||||||
|
} | null>(null);
|
||||||
const [mounted, setMounted] = useState(false);
|
const [mounted, setMounted] = useState(false);
|
||||||
|
|
||||||
// Prevent hydration mismatch by only rendering content after mount
|
// Get authentication status and current path for callback
|
||||||
|
const { data: session, isPending: isAuthLoading } = authClient.useSession();
|
||||||
|
const isAuthenticated = !!session?.user;
|
||||||
|
const currentPath = useLocalePathname();
|
||||||
|
|
||||||
|
// Prevent hydration mismatch by only rendering auth-dependent content after mount
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setMounted(true);
|
setMounted(true);
|
||||||
}, []);
|
}, []);
|
||||||
@ -61,6 +78,42 @@ export function UrlInputForm({
|
|||||||
webContentAnalyzerConfig.performance.urlInputDebounceMs
|
webContentAnalyzerConfig.performance.urlInputDebounceMs
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const { execute: checkCredits, isExecuting: isCheckingCredits } = useAction(
|
||||||
|
checkWebContentAnalysisCreditsAction,
|
||||||
|
{
|
||||||
|
onSuccess: (result) => {
|
||||||
|
if (result.data?.success) {
|
||||||
|
setCreditInfo({
|
||||||
|
hasEnoughCredits: result.data.hasEnoughCredits ?? false,
|
||||||
|
currentCredits: result.data.currentCredits ?? 0,
|
||||||
|
requiredCredits: result.data.requiredCredits ?? 0,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
// Only show error toast if it's not an auth error
|
||||||
|
if (result.data?.error !== 'Unauthorized') {
|
||||||
|
setTimeout(() => {
|
||||||
|
toast.error(result.data?.error || 'Failed to check credits');
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error('Credit check error:', error);
|
||||||
|
// Only show error toast for non-auth errors
|
||||||
|
setTimeout(() => {
|
||||||
|
toast.error('Failed to check credits');
|
||||||
|
}, 0);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Check credits only when user is authenticated
|
||||||
|
useEffect(() => {
|
||||||
|
if (isAuthenticated && !isAuthLoading) {
|
||||||
|
checkCredits();
|
||||||
|
}
|
||||||
|
}, [isAuthenticated, isAuthLoading, checkCredits]);
|
||||||
|
|
||||||
// Debounced URL validation effect
|
// Debounced URL validation effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (debouncedUrl && debouncedUrl !== urlValue) {
|
if (debouncedUrl && debouncedUrl !== urlValue) {
|
||||||
@ -70,34 +123,27 @@ export function UrlInputForm({
|
|||||||
}, [debouncedUrl, urlValue, form]);
|
}, [debouncedUrl, urlValue, form]);
|
||||||
|
|
||||||
const handleSubmit = (data: UrlFormData) => {
|
const handleSubmit = (data: UrlFormData) => {
|
||||||
onSubmit(data.url ?? '', modelProvider);
|
// For authenticated users, check credits before submitting
|
||||||
|
if (creditInfo && !creditInfo.hasEnoughCredits) {
|
||||||
|
// Defer toast to avoid flushSync during render
|
||||||
|
setTimeout(() => {
|
||||||
|
toast.error(
|
||||||
|
`Insufficient credits. You need ${creditInfo.requiredCredits} credits but only have ${creditInfo.currentCredits}.`
|
||||||
|
);
|
||||||
|
}, 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onSubmit(data.url);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleFormSubmit = form.handleSubmit(handleSubmit);
|
const handleFormSubmit = form.handleSubmit(handleSubmit);
|
||||||
|
|
||||||
const isFormDisabled = isLoading || disabled;
|
const isInsufficientCredits = creditInfo && !creditInfo.hasEnoughCredits;
|
||||||
|
const isFormDisabled = isLoading || disabled || !!isInsufficientCredits;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="w-full max-w-2xl mx-auto">
|
<div className="w-full max-w-2xl mx-auto">
|
||||||
{/* Model Provider Selection (for mobile/smaller screens, optional) */}
|
|
||||||
<div className="flex justify-end items-center mb-4">
|
|
||||||
<Select
|
|
||||||
value={modelProvider}
|
|
||||||
onValueChange={setModelProvider}
|
|
||||||
disabled={isLoading || disabled}
|
|
||||||
>
|
|
||||||
<SelectTrigger id="model-provider-select-form" className="w-40">
|
|
||||||
<SelectValue placeholder="Select model" />
|
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent>
|
|
||||||
<SelectItem value="openrouter">OpenRouter</SelectItem>
|
|
||||||
<SelectItem value="openai">OpenAI GPT-4o</SelectItem>
|
|
||||||
<SelectItem value="gemini">Google Gemini</SelectItem>
|
|
||||||
<SelectItem value="deepseek">DeepSeek R1</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
</div>
|
|
||||||
<Form {...form}>
|
<Form {...form}>
|
||||||
<form onSubmit={handleFormSubmit} className="space-y-4">
|
<form onSubmit={handleFormSubmit} className="space-y-4">
|
||||||
<FormField
|
<FormField
|
||||||
@ -124,20 +170,67 @@ export function UrlInputForm({
|
|||||||
)}
|
)}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
{/* Credit Information - Only show for authenticated users */}
|
||||||
|
{isAuthenticated && creditInfo && (
|
||||||
|
<div className="flex items-center justify-between p-3 bg-muted/50 rounded-lg text-sm">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<CoinsIcon className="size-4 text-muted-foreground" />
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
Cost: {creditInfo.requiredCredits} credits
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span
|
||||||
|
className={
|
||||||
|
creditInfo.hasEnoughCredits
|
||||||
|
? 'text-green-600 dark:text-green-400'
|
||||||
|
: 'text-red-600 dark:text-red-400'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
Balance: {creditInfo.currentCredits}
|
||||||
|
</span>
|
||||||
|
{!creditInfo.hasEnoughCredits && (
|
||||||
|
<AlertCircleIcon className="size-4 text-red-600 dark:text-red-400" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Insufficient Credits Warning */}
|
||||||
|
{isAuthenticated && isInsufficientCredits && (
|
||||||
|
<div className="flex items-center gap-2 p-3 bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-700 dark:text-red-400">
|
||||||
|
<AlertCircleIcon className="size-4 flex-shrink-0" />
|
||||||
|
<span>
|
||||||
|
Insufficient credits. You need {creditInfo.requiredCredits}{' '}
|
||||||
|
credits but only have {creditInfo.currentCredits}.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{!mounted ? (
|
{!mounted ? (
|
||||||
// Show loading state during hydration to prevent mismatch
|
// Show loading state during hydration to prevent mismatch
|
||||||
<Button type="button" disabled className="w-full" size="lg">
|
<Button type="button" disabled className="w-full" size="lg">
|
||||||
<Loader2Icon className="size-4 animate-spin" />
|
<Loader2Icon className="size-4 animate-spin" />
|
||||||
<span>Loading...</span>
|
<span>Loading...</span>
|
||||||
</Button>
|
</Button>
|
||||||
) : (
|
) : isAuthenticated ? (
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={isFormDisabled || !urlValue?.trim()}
|
disabled={isFormDisabled || !urlValue.trim()}
|
||||||
className="w-full"
|
className="w-full"
|
||||||
size="lg"
|
size="lg"
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isAuthLoading ? (
|
||||||
|
<>
|
||||||
|
<Loader2Icon className="size-4 animate-spin" />
|
||||||
|
<span>Loading...</span>
|
||||||
|
</>
|
||||||
|
) : isCheckingCredits ? (
|
||||||
|
<>
|
||||||
|
<Loader2Icon className="size-4 animate-spin" />
|
||||||
|
<span>Checking Credits...</span>
|
||||||
|
</>
|
||||||
|
) : isLoading ? (
|
||||||
<>
|
<>
|
||||||
<Loader2Icon className="size-4 animate-spin" />
|
<Loader2Icon className="size-4 animate-spin" />
|
||||||
<span>Analyzing...</span>
|
<span>Analyzing...</span>
|
||||||
@ -145,10 +238,24 @@ export function UrlInputForm({
|
|||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<SparklesIcon className="size-4" />
|
<SparklesIcon className="size-4" />
|
||||||
<span>Analyze Website</span>
|
<span>
|
||||||
|
Analyze Website
|
||||||
|
{creditInfo && ` (${creditInfo.requiredCredits} credits)`}
|
||||||
|
</span>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
) : (
|
||||||
|
<LoginWrapper mode="modal" asChild callbackUrl={currentPath}>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
className="w-full cursor-pointer"
|
||||||
|
size="lg"
|
||||||
|
>
|
||||||
|
<LogInIcon className="size-4" />
|
||||||
|
<span>Sign In First</span>
|
||||||
|
</Button>
|
||||||
|
</LoginWrapper>
|
||||||
)}
|
)}
|
||||||
</form>
|
</form>
|
||||||
</Form>
|
</Form>
|
||||||
|
@ -3,7 +3,6 @@
|
|||||||
import type {
|
import type {
|
||||||
AnalysisState,
|
AnalysisState,
|
||||||
AnalyzeContentResponse,
|
AnalyzeContentResponse,
|
||||||
ModelProvider,
|
|
||||||
WebContentAnalyzerProps,
|
WebContentAnalyzerProps,
|
||||||
} from '@/ai/text/utils/web-content-analyzer';
|
} from '@/ai/text/utils/web-content-analyzer';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
@ -193,152 +192,150 @@ export function WebContentAnalyzer({ className }: WebContentAnalyzerProps) {
|
|||||||
// Use reducer for better state management and performance
|
// Use reducer for better state management and performance
|
||||||
const [state, dispatch] = useReducer(analysisReducer, initialState);
|
const [state, dispatch] = useReducer(analysisReducer, initialState);
|
||||||
|
|
||||||
// Model provider state
|
|
||||||
const [modelProvider, setModelProvider] =
|
|
||||||
useState<ModelProvider>('openrouter');
|
|
||||||
|
|
||||||
// Enhanced error state
|
// Enhanced error state
|
||||||
const [analyzedError, setAnalyzedError] =
|
const [analyzedError, setAnalyzedError] =
|
||||||
useState<WebContentAnalyzerError | null>(null);
|
useState<WebContentAnalyzerError | null>(null);
|
||||||
|
|
||||||
// Handle analysis submission with enhanced error handling
|
// Handle analysis submission with enhanced error handling
|
||||||
const handleAnalyzeUrl = useCallback(
|
const handleAnalyzeUrl = useCallback(async (url: string) => {
|
||||||
async (url: string, provider: ModelProvider) => {
|
// Reset state and start analysis
|
||||||
// Reset state and start analysis
|
dispatch({ type: 'START_ANALYSIS', payload: { url } });
|
||||||
dispatch({ type: 'START_ANALYSIS', payload: { url } });
|
setAnalyzedError(null);
|
||||||
setAnalyzedError(null);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Use retry mechanism for the API call
|
// Use retry mechanism for the API call
|
||||||
const result = await withRetry(async () => {
|
const result = await withRetry(async () => {
|
||||||
const response = await fetch('/api/analyze-content', {
|
const response = await fetch('/api/analyze-content', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
|
||||||
body: JSON.stringify({ url, modelProvider: provider }),
|
|
||||||
});
|
|
||||||
|
|
||||||
const data: AnalyzeContentResponse = await response.json();
|
|
||||||
|
|
||||||
// Handle HTTP errors
|
|
||||||
if (!response.ok) {
|
|
||||||
// Create specific error based on status code
|
|
||||||
let errorType = ErrorType.UNKNOWN;
|
|
||||||
let severity = ErrorSeverity.MEDIUM;
|
|
||||||
let retryable = true;
|
|
||||||
|
|
||||||
switch (response.status) {
|
|
||||||
case 400:
|
|
||||||
errorType = ErrorType.VALIDATION;
|
|
||||||
retryable = false;
|
|
||||||
break;
|
|
||||||
case 408:
|
|
||||||
errorType = ErrorType.TIMEOUT;
|
|
||||||
break;
|
|
||||||
case 422:
|
|
||||||
errorType = ErrorType.SCRAPING;
|
|
||||||
break;
|
|
||||||
case 429:
|
|
||||||
errorType = ErrorType.RATE_LIMIT;
|
|
||||||
break;
|
|
||||||
case 503:
|
|
||||||
errorType = ErrorType.SERVICE_UNAVAILABLE;
|
|
||||||
severity = ErrorSeverity.HIGH;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
errorType = ErrorType.NETWORK;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw new WebContentAnalyzerError(
|
|
||||||
errorType,
|
|
||||||
data.error || `HTTP ${response.status}: ${response.statusText}`,
|
|
||||||
data.error || 'Failed to analyze website. Please try again.',
|
|
||||||
severity,
|
|
||||||
retryable
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!data.success || !data.data) {
|
|
||||||
throw new WebContentAnalyzerError(
|
|
||||||
ErrorType.ANALYSIS,
|
|
||||||
data.error || 'Analysis failed',
|
|
||||||
data.error ||
|
|
||||||
'Failed to analyze website content. Please try again.',
|
|
||||||
ErrorSeverity.MEDIUM,
|
|
||||||
true
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return data;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Update state to analyzing stage
|
|
||||||
dispatch({
|
|
||||||
type: 'SET_LOADING_STAGE',
|
|
||||||
payload: { stage: 'analyzing' },
|
|
||||||
});
|
|
||||||
|
|
||||||
// Simulate a brief delay for analyzing stage to show progress
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
||||||
|
|
||||||
// Set results and complete analysis
|
|
||||||
dispatch({
|
|
||||||
type: 'SET_RESULTS',
|
|
||||||
payload: {
|
|
||||||
results: result.data!.analysis,
|
|
||||||
screenshot: result.data!.screenshot,
|
|
||||||
},
|
},
|
||||||
|
body: JSON.stringify({ url }),
|
||||||
});
|
});
|
||||||
|
|
||||||
// Show success toast - defer to avoid flushSync during render
|
const data: AnalyzeContentResponse = await response.json();
|
||||||
setTimeout(() => {
|
|
||||||
toast.success('Website analysis completed successfully!', {
|
|
||||||
description: `Analyzed ${new URL(url).hostname}`,
|
|
||||||
});
|
|
||||||
}, 0);
|
|
||||||
} catch (error) {
|
|
||||||
// Classify the error
|
|
||||||
const analyzedError =
|
|
||||||
error instanceof WebContentAnalyzerError
|
|
||||||
? error
|
|
||||||
: classifyError(error);
|
|
||||||
|
|
||||||
// Log the error
|
// Handle HTTP errors
|
||||||
logError(analyzedError, { url, component: 'WebContentAnalyzer' });
|
if (!response.ok) {
|
||||||
|
// Create specific error based on status code
|
||||||
|
let errorType = ErrorType.UNKNOWN;
|
||||||
|
let severity = ErrorSeverity.MEDIUM;
|
||||||
|
let retryable = true;
|
||||||
|
|
||||||
// Update state with error
|
switch (response.status) {
|
||||||
dispatch({
|
case 400:
|
||||||
type: 'SET_ERROR',
|
errorType = ErrorType.VALIDATION;
|
||||||
payload: { error: analyzedError.userMessage },
|
retryable = false;
|
||||||
});
|
|
||||||
|
|
||||||
// Set the analyzed error for the ErrorDisplay component
|
|
||||||
setAnalyzedError(analyzedError);
|
|
||||||
|
|
||||||
// Show error toast with appropriate severity - defer to avoid flushSync during render
|
|
||||||
const toastOptions = {
|
|
||||||
description: analyzedError.userMessage,
|
|
||||||
};
|
|
||||||
|
|
||||||
setTimeout(() => {
|
|
||||||
switch (analyzedError.severity) {
|
|
||||||
case ErrorSeverity.CRITICAL:
|
|
||||||
case ErrorSeverity.HIGH:
|
|
||||||
toast.error('Analysis Failed', toastOptions);
|
|
||||||
break;
|
break;
|
||||||
case ErrorSeverity.MEDIUM:
|
case 401:
|
||||||
toast.warning('Analysis Failed', toastOptions);
|
errorType = ErrorType.AUTHENTICATION;
|
||||||
|
severity = ErrorSeverity.HIGH;
|
||||||
|
retryable = false;
|
||||||
break;
|
break;
|
||||||
case ErrorSeverity.LOW:
|
case 402:
|
||||||
toast.info('Analysis Issue', toastOptions);
|
errorType = ErrorType.CREDITS;
|
||||||
|
severity = ErrorSeverity.HIGH;
|
||||||
|
retryable = false;
|
||||||
break;
|
break;
|
||||||
|
case 408:
|
||||||
|
errorType = ErrorType.TIMEOUT;
|
||||||
|
break;
|
||||||
|
case 422:
|
||||||
|
errorType = ErrorType.SCRAPING;
|
||||||
|
break;
|
||||||
|
case 429:
|
||||||
|
errorType = ErrorType.RATE_LIMIT;
|
||||||
|
break;
|
||||||
|
case 503:
|
||||||
|
errorType = ErrorType.SERVICE_UNAVAILABLE;
|
||||||
|
severity = ErrorSeverity.HIGH;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
errorType = ErrorType.NETWORK;
|
||||||
}
|
}
|
||||||
}, 0);
|
|
||||||
}
|
throw new WebContentAnalyzerError(
|
||||||
},
|
errorType,
|
||||||
[]
|
data.error || `HTTP ${response.status}: ${response.statusText}`,
|
||||||
);
|
data.error || 'Failed to analyze website. Please try again.',
|
||||||
|
severity,
|
||||||
|
retryable
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!data.success || !data.data) {
|
||||||
|
throw new WebContentAnalyzerError(
|
||||||
|
ErrorType.ANALYSIS,
|
||||||
|
data.error || 'Analysis failed',
|
||||||
|
data.error ||
|
||||||
|
'Failed to analyze website content. Please try again.',
|
||||||
|
ErrorSeverity.MEDIUM,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update state to analyzing stage
|
||||||
|
dispatch({ type: 'SET_LOADING_STAGE', payload: { stage: 'analyzing' } });
|
||||||
|
|
||||||
|
// Simulate a brief delay for analyzing stage to show progress
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||||
|
|
||||||
|
// Set results and complete analysis
|
||||||
|
dispatch({
|
||||||
|
type: 'SET_RESULTS',
|
||||||
|
payload: {
|
||||||
|
results: result.data!.analysis,
|
||||||
|
screenshot: result.data!.screenshot,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Show success toast - defer to avoid flushSync during render
|
||||||
|
setTimeout(() => {
|
||||||
|
toast.success('Website analysis completed successfully!', {
|
||||||
|
description: `Analyzed ${new URL(url).hostname}`,
|
||||||
|
});
|
||||||
|
}, 0);
|
||||||
|
} catch (error) {
|
||||||
|
// Classify the error
|
||||||
|
const analyzedError =
|
||||||
|
error instanceof WebContentAnalyzerError ? error : classifyError(error);
|
||||||
|
|
||||||
|
// Log the error
|
||||||
|
logError(analyzedError, { url, component: 'WebContentAnalyzer' });
|
||||||
|
|
||||||
|
// Update state with error
|
||||||
|
dispatch({
|
||||||
|
type: 'SET_ERROR',
|
||||||
|
payload: { error: analyzedError.userMessage },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set the analyzed error for the ErrorDisplay component
|
||||||
|
setAnalyzedError(analyzedError);
|
||||||
|
|
||||||
|
// Show error toast with appropriate severity - defer to avoid flushSync during render
|
||||||
|
const toastOptions = {
|
||||||
|
description: analyzedError.userMessage,
|
||||||
|
};
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
switch (analyzedError.severity) {
|
||||||
|
case ErrorSeverity.CRITICAL:
|
||||||
|
case ErrorSeverity.HIGH:
|
||||||
|
toast.error('Analysis Failed', toastOptions);
|
||||||
|
break;
|
||||||
|
case ErrorSeverity.MEDIUM:
|
||||||
|
toast.warning('Analysis Failed', toastOptions);
|
||||||
|
break;
|
||||||
|
case ErrorSeverity.LOW:
|
||||||
|
toast.info('Analysis Issue', toastOptions);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Handle starting a new analysis
|
// Handle starting a new analysis
|
||||||
const handleNewAnalysis = useCallback(() => {
|
const handleNewAnalysis = useCallback(() => {
|
||||||
@ -377,8 +374,6 @@ export function WebContentAnalyzer({ className }: WebContentAnalyzerProps) {
|
|||||||
onSubmit={handleAnalyzeUrl}
|
onSubmit={handleAnalyzeUrl}
|
||||||
isLoading={state.isLoading}
|
isLoading={state.isLoading}
|
||||||
disabled={state.isLoading}
|
disabled={state.isLoading}
|
||||||
modelProvider={modelProvider}
|
|
||||||
setModelProvider={setModelProvider}
|
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
@ -9,6 +9,7 @@ import { webContentAnalyzerConfig } from '@/ai/text/utils/web-content-analyzer-c
|
|||||||
export enum ErrorType {
|
export enum ErrorType {
|
||||||
VALIDATION = 'validation',
|
VALIDATION = 'validation',
|
||||||
NETWORK = 'network',
|
NETWORK = 'network',
|
||||||
|
CREDITS = 'credits',
|
||||||
SCRAPING = 'scraping',
|
SCRAPING = 'scraping',
|
||||||
ANALYSIS = 'analysis',
|
ANALYSIS = 'analysis',
|
||||||
TIMEOUT = 'timeout',
|
TIMEOUT = 'timeout',
|
||||||
@ -95,6 +96,22 @@ export function classifyError(error: unknown): WebContentAnalyzerError {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Credit errors
|
||||||
|
if (
|
||||||
|
message.includes('credit') ||
|
||||||
|
message.includes('insufficient') ||
|
||||||
|
message.includes('balance')
|
||||||
|
) {
|
||||||
|
return new WebContentAnalyzerError(
|
||||||
|
ErrorType.CREDITS,
|
||||||
|
error.message,
|
||||||
|
'Insufficient credits to perform analysis. Please purchase more credits.',
|
||||||
|
ErrorSeverity.HIGH,
|
||||||
|
false,
|
||||||
|
error
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Scraping errors
|
// Scraping errors
|
||||||
if (
|
if (
|
||||||
message.includes('scrape') ||
|
message.includes('scrape') ||
|
||||||
@ -261,6 +278,16 @@ export function getRecoveryActions(error: WebContentAnalyzerError): Array<{
|
|||||||
{ label: 'Try Simpler URL', action: 'simplify_url' },
|
{ label: 'Try Simpler URL', action: 'simplify_url' },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
case ErrorType.CREDITS:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
label: 'Purchase Credits',
|
||||||
|
action: 'purchase_credits',
|
||||||
|
primary: true,
|
||||||
|
},
|
||||||
|
{ label: 'Check Balance', action: 'check_balance' },
|
||||||
|
];
|
||||||
|
|
||||||
case ErrorType.SCRAPING:
|
case ErrorType.SCRAPING:
|
||||||
return [
|
return [
|
||||||
{ label: 'Try Again', action: 'retry', primary: true },
|
{ label: 'Try Again', action: 'retry', primary: true },
|
||||||
|
@ -6,6 +6,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
export const webContentAnalyzerConfig = {
|
export const webContentAnalyzerConfig = {
|
||||||
|
/**
|
||||||
|
* Credit cost for performing a web content analysis
|
||||||
|
*/
|
||||||
|
creditsCost: 100,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Maximum content length for AI analysis (in characters)
|
* Maximum content length for AI analysis (in characters)
|
||||||
* Optimized to prevent token limit issues while maintaining quality
|
* Optimized to prevent token limit issues while maintaining quality
|
||||||
@ -95,33 +100,25 @@ export const webContentAnalyzerConfig = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* AI model providers
|
* OpenAI analysis options
|
||||||
*/
|
*/
|
||||||
openai: {
|
openai: {
|
||||||
model: 'gpt-4o-mini',
|
model: 'gpt-4o-mini',
|
||||||
temperature: 0.1, // Low temperature for consistent results
|
temperature: 0.1, // Low temperature for consistent results
|
||||||
|
/**
|
||||||
|
* Token optimization settings
|
||||||
|
*/
|
||||||
maxTokens: 2000, // Limit response tokens for performance
|
maxTokens: 2000, // Limit response tokens for performance
|
||||||
},
|
},
|
||||||
gemini: {
|
|
||||||
model: 'gemini-2.0-flash',
|
|
||||||
temperature: 0.1,
|
|
||||||
maxTokens: 2000,
|
|
||||||
},
|
|
||||||
deepseek: {
|
|
||||||
model: 'deepseek-chat',
|
|
||||||
temperature: 0.1,
|
|
||||||
maxTokens: 2000,
|
|
||||||
},
|
|
||||||
openrouter: {
|
|
||||||
// model: 'openrouter/horizon-beta',
|
|
||||||
// model: 'x-ai/grok-3-beta',
|
|
||||||
// model: 'openai/gpt-4o-mini',
|
|
||||||
model: 'deepseek/deepseek-r1:free',
|
|
||||||
temperature: 0.1,
|
|
||||||
maxTokens: 2000,
|
|
||||||
},
|
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the credit cost for web content analysis
|
||||||
|
*/
|
||||||
|
export function getWebContentAnalysisCost(): number {
|
||||||
|
return webContentAnalyzerConfig.creditsCost;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates if the Firecrawl API key is configured
|
* Validates if the Firecrawl API key is configured
|
||||||
*/
|
*/
|
||||||
@ -140,6 +137,8 @@ export function validateFirecrawlConfig(): boolean {
|
|||||||
*/
|
*/
|
||||||
export function validateWebContentAnalyzerConfig(): boolean {
|
export function validateWebContentAnalyzerConfig(): boolean {
|
||||||
return (
|
return (
|
||||||
|
typeof webContentAnalyzerConfig.creditsCost === 'number' &&
|
||||||
|
webContentAnalyzerConfig.creditsCost > 0 &&
|
||||||
typeof webContentAnalyzerConfig.maxContentLength === 'number' &&
|
typeof webContentAnalyzerConfig.maxContentLength === 'number' &&
|
||||||
webContentAnalyzerConfig.maxContentLength > 0 &&
|
webContentAnalyzerConfig.maxContentLength > 0 &&
|
||||||
typeof webContentAnalyzerConfig.timeoutMillis === 'number' &&
|
typeof webContentAnalyzerConfig.timeoutMillis === 'number' &&
|
||||||
|
@ -15,7 +15,6 @@ export interface AnalysisResults {
|
|||||||
// API Request/Response Interfaces
|
// API Request/Response Interfaces
|
||||||
export interface AnalyzeContentRequest {
|
export interface AnalyzeContentRequest {
|
||||||
url: string;
|
url: string;
|
||||||
modelProvider: ModelProvider;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AnalyzeContentResponse {
|
export interface AnalyzeContentResponse {
|
||||||
@ -67,19 +66,14 @@ export interface AnalysisState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Component Props Interfaces
|
// Component Props Interfaces
|
||||||
export type ModelProvider = 'openai' | 'gemini' | 'deepseek' | 'openrouter';
|
|
||||||
|
|
||||||
export interface WebContentAnalyzerProps {
|
export interface WebContentAnalyzerProps {
|
||||||
className?: string;
|
className?: string;
|
||||||
modelProvider?: ModelProvider;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UrlInputFormProps {
|
export interface UrlInputFormProps {
|
||||||
onSubmit: (url: string, modelProvider: ModelProvider) => void;
|
onSubmit: (url: string) => void;
|
||||||
isLoading: boolean;
|
isLoading: boolean;
|
||||||
disabled?: boolean;
|
disabled?: boolean;
|
||||||
modelProvider: ModelProvider;
|
|
||||||
setModelProvider: (provider: ModelProvider) => void;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AnalysisResultsProps {
|
export interface AnalysisResultsProps {
|
||||||
@ -97,8 +91,9 @@ export interface LoadingStatesProps {
|
|||||||
|
|
||||||
// URL Validation Schema
|
// URL Validation Schema
|
||||||
export const urlSchema = z
|
export const urlSchema = z
|
||||||
.url()
|
.string()
|
||||||
.min(1, 'URL is required')
|
.min(1, 'URL is required')
|
||||||
|
.url('Please enter a valid URL')
|
||||||
.refine(
|
.refine(
|
||||||
(url) => url.startsWith('http://') || url.startsWith('https://'),
|
(url) => url.startsWith('http://') || url.startsWith('https://'),
|
||||||
'URL must start with http:// or https://'
|
'URL must start with http:// or https://'
|
||||||
@ -113,13 +108,12 @@ export const analysisResultsSchema = z.object({
|
|||||||
pricing: z.string().default('Not specified'),
|
pricing: z.string().default('Not specified'),
|
||||||
useCases: z.array(z.string()).default([]),
|
useCases: z.array(z.string()).default([]),
|
||||||
url: urlSchema,
|
url: urlSchema,
|
||||||
analyzedAt: z.iso.datetime(),
|
analyzedAt: z.string().datetime(),
|
||||||
});
|
});
|
||||||
|
|
||||||
// API Request Schema
|
// API Request Schema
|
||||||
export const analyzeContentRequestSchema = z.object({
|
export const analyzeContentRequestSchema = z.object({
|
||||||
url: urlSchema,
|
url: urlSchema,
|
||||||
modelProvider: z.enum(['openai', 'gemini', 'deepseek', 'openrouter']),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// API Response Schema
|
// API Response Schema
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import Container from '@/components/layout/container';
|
import Container from '@/components/layout/container';
|
||||||
|
import { BlurFadeDemo } from '@/components/magicui/example/blur-fade-example';
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||||
import { Button, buttonVariants } from '@/components/ui/button';
|
import { Button, buttonVariants } from '@/components/ui/button';
|
||||||
import { websiteConfig } from '@/config/website';
|
import { websiteConfig } from '@/config/website';
|
||||||
@ -97,6 +98,9 @@ export default async function AboutPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* image section */}
|
||||||
|
<BlurFadeDemo />
|
||||||
</div>
|
</div>
|
||||||
</Container>
|
</Container>
|
||||||
);
|
);
|
||||||
|
@ -1,13 +0,0 @@
|
|||||||
import Container from '@/components/layout/container';
|
|
||||||
import { ConsumeCreditsCard } from '@/components/test/consume-credits-card';
|
|
||||||
|
|
||||||
export default async function TestPage() {
|
|
||||||
return (
|
|
||||||
<Container className="py-16 px-4">
|
|
||||||
<div className="max-w-4xl mx-auto space-y-8">
|
|
||||||
{/* credits test */}
|
|
||||||
<ConsumeCreditsCard />
|
|
||||||
</div>
|
|
||||||
</Container>
|
|
||||||
);
|
|
||||||
}
|
|
@ -42,6 +42,10 @@ export default async function AIAudioPage() {
|
|||||||
<div className="size-32 text-muted-foreground" />
|
<div className="size-32 text-muted-foreground" />
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h1 className="text-4xl text-foreground">{t('content')}</h1>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -1,46 +0,0 @@
|
|||||||
import ChatBot from '@/ai/chat/components/ChatBot';
|
|
||||||
import { constructMetadata } from '@/lib/metadata';
|
|
||||||
import { getUrlWithLocale } from '@/lib/urls/urls';
|
|
||||||
import { ZapIcon } from 'lucide-react';
|
|
||||||
import type { Metadata } from 'next';
|
|
||||||
import type { Locale } from 'next-intl';
|
|
||||||
import { getTranslations } from 'next-intl/server';
|
|
||||||
|
|
||||||
export async function generateMetadata({
|
|
||||||
params,
|
|
||||||
}: {
|
|
||||||
params: Promise<{ locale: Locale }>;
|
|
||||||
}): Promise<Metadata | undefined> {
|
|
||||||
const { locale } = await params;
|
|
||||||
const t = await getTranslations({ locale, namespace: 'Metadata' });
|
|
||||||
const pt = await getTranslations({ locale, namespace: 'AIChatPage' });
|
|
||||||
|
|
||||||
return constructMetadata({
|
|
||||||
title: pt('title') + ' | ' + t('title'),
|
|
||||||
description: pt('description'),
|
|
||||||
canonicalUrl: getUrlWithLocale('/ai/chat', locale),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function AIChatPage() {
|
|
||||||
const t = await getTranslations('AIChatPage');
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="min-h-screen bg-muted/50 rounded-lg">
|
|
||||||
<div className="container mx-auto px-4 py-8 md:py-16">
|
|
||||||
{/* Header Section */}
|
|
||||||
<div className="text-center space-y-6 mb-12">
|
|
||||||
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-primary/10 text-primary text-sm font-medium">
|
|
||||||
<ZapIcon className="size-4" />
|
|
||||||
{t('title')}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Chat Bot */}
|
|
||||||
<div className="max-w-6xl mx-auto">
|
|
||||||
<ChatBot />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
@ -2,7 +2,6 @@ import { ImagePlayground } from '@/ai/image/components/ImagePlayground';
|
|||||||
import { getRandomSuggestions } from '@/ai/image/lib/suggestions';
|
import { getRandomSuggestions } from '@/ai/image/lib/suggestions';
|
||||||
import { constructMetadata } from '@/lib/metadata';
|
import { constructMetadata } from '@/lib/metadata';
|
||||||
import { getUrlWithLocale } from '@/lib/urls/urls';
|
import { getUrlWithLocale } from '@/lib/urls/urls';
|
||||||
import { ImageIcon } from 'lucide-react';
|
|
||||||
import type { Metadata } from 'next';
|
import type { Metadata } from 'next';
|
||||||
import type { Locale } from 'next-intl';
|
import type { Locale } from 'next-intl';
|
||||||
import { getTranslations } from 'next-intl/server';
|
import { getTranslations } from 'next-intl/server';
|
||||||
@ -27,21 +26,8 @@ export default async function AIImagePage() {
|
|||||||
const t = await getTranslations('AIImagePage');
|
const t = await getTranslations('AIImagePage');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-muted/50 rounded-lg">
|
<div className="mx-auto space-y-8">
|
||||||
<div className="container mx-auto px-4 py-8 md:py-16">
|
<ImagePlayground suggestions={getRandomSuggestions(5)} />
|
||||||
{/* Header Section */}
|
|
||||||
<div className="text-center space-y-6 mb-12">
|
|
||||||
<div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-primary/10 text-primary text-sm font-medium">
|
|
||||||
<ImageIcon className="size-4" />
|
|
||||||
{t('title')}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Image Playground Component */}
|
|
||||||
<div className="max-w-6xl mx-auto">
|
|
||||||
<ImagePlayground suggestions={getRandomSuggestions(5)} />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -26,7 +26,7 @@ export default async function AITextPage() {
|
|||||||
const t = await getTranslations('AITextPage');
|
const t = await getTranslations('AITextPage');
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-muted/50 rounded-lg">
|
<div className="min-h-screen bg-background rounded-lg">
|
||||||
<div className="container mx-auto px-4 py-8 md:py-16">
|
<div className="container mx-auto px-4 py-8 md:py-16">
|
||||||
{/* Header Section */}
|
{/* Header Section */}
|
||||||
<div className="text-center space-y-6 mb-12">
|
<div className="text-center space-y-6 mb-12">
|
||||||
|
@ -42,6 +42,10 @@ export default async function AIVideoPage() {
|
|||||||
<div className="size-32 text-muted-foreground" />
|
<div className="size-32 text-muted-foreground" />
|
||||||
</AvatarFallback>
|
</AvatarFallback>
|
||||||
</Avatar>
|
</Avatar>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<h1 className="text-4xl text-foreground">{t('content')}</h1>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
16
src/app/[locale]/(marketing)/blocks/[category]/layout.tsx
Normal file
16
src/app/[locale]/(marketing)/blocks/[category]/layout.tsx
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
import { categories } from '@/components/tailark/blocks';
|
||||||
|
import BlocksNav from '@/components/tailark/blocks-nav';
|
||||||
|
import type { PropsWithChildren } from 'react';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The locale inconsistency issue has been fixed in the BlocksNav component
|
||||||
|
*/
|
||||||
|
export default function BlockCategoryLayout({ children }: PropsWithChildren) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<BlocksNav categories={categories} />
|
||||||
|
|
||||||
|
<main>{children}</main>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
54
src/app/[locale]/(marketing)/blocks/[category]/page.tsx
Normal file
54
src/app/[locale]/(marketing)/blocks/[category]/page.tsx
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
import BlockPreview from '@/components/tailark/block-preview';
|
||||||
|
import { blocks, categories } from '@/components/tailark/blocks';
|
||||||
|
import { constructMetadata } from '@/lib/metadata';
|
||||||
|
import { getUrlWithLocale } from '@/lib/urls/urls';
|
||||||
|
import type { Metadata } from 'next';
|
||||||
|
import type { Locale } from 'next-intl';
|
||||||
|
import { getTranslations } from 'next-intl/server';
|
||||||
|
import { notFound } from 'next/navigation';
|
||||||
|
|
||||||
|
export const dynamic = 'force-static';
|
||||||
|
export const revalidate = 3600;
|
||||||
|
|
||||||
|
export async function generateStaticParams() {
|
||||||
|
return categories.map((category) => ({
|
||||||
|
category: category,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function generateMetadata({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ locale: Locale; category: string }>;
|
||||||
|
}): Promise<Metadata | undefined> {
|
||||||
|
const { locale, category } = await params;
|
||||||
|
const t = await getTranslations({ locale, namespace: 'Metadata' });
|
||||||
|
return constructMetadata({
|
||||||
|
title: category + ' | ' + t('title'),
|
||||||
|
description: t('description'),
|
||||||
|
canonicalUrl: getUrlWithLocale(`/blocks/${category}`, locale),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BlockCategoryPageProps {
|
||||||
|
params: Promise<{ category: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function BlockCategoryPage({
|
||||||
|
params,
|
||||||
|
}: BlockCategoryPageProps) {
|
||||||
|
const { category } = await params;
|
||||||
|
const categoryBlocks = blocks.filter((b) => b.category === category);
|
||||||
|
|
||||||
|
if (categoryBlocks.length === 0) {
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
{categoryBlocks.map((block, index) => (
|
||||||
|
<BlockPreview {...block} key={index} />
|
||||||
|
))}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
@ -2,14 +2,10 @@ import AllPostsButton from '@/components/blog/all-posts-button';
|
|||||||
import BlogGrid from '@/components/blog/blog-grid';
|
import BlogGrid from '@/components/blog/blog-grid';
|
||||||
import { getMDXComponents } from '@/components/docs/mdx-components';
|
import { getMDXComponents } from '@/components/docs/mdx-components';
|
||||||
import { NewsletterCard } from '@/components/newsletter/newsletter-card';
|
import { NewsletterCard } from '@/components/newsletter/newsletter-card';
|
||||||
import { PremiumBadge } from '@/components/premium/premium-badge';
|
|
||||||
import { PremiumGuard } from '@/components/premium/premium-guard';
|
|
||||||
import { websiteConfig } from '@/config/website';
|
import { websiteConfig } from '@/config/website';
|
||||||
import { LocaleLink } from '@/i18n/navigation';
|
import { LocaleLink } from '@/i18n/navigation';
|
||||||
import { formatDate } from '@/lib/formatter';
|
import { formatDate } from '@/lib/formatter';
|
||||||
import { constructMetadata } from '@/lib/metadata';
|
import { constructMetadata } from '@/lib/metadata';
|
||||||
import { checkPremiumAccess } from '@/lib/premium-access';
|
|
||||||
import { getSession } from '@/lib/server';
|
|
||||||
import {
|
import {
|
||||||
type BlogType,
|
type BlogType,
|
||||||
authorSource,
|
authorSource,
|
||||||
@ -17,7 +13,6 @@ import {
|
|||||||
categorySource,
|
categorySource,
|
||||||
} from '@/lib/source';
|
} from '@/lib/source';
|
||||||
import { getUrlWithLocale } from '@/lib/urls/urls';
|
import { getUrlWithLocale } from '@/lib/urls/urls';
|
||||||
import { InlineTOC } from 'fumadocs-ui/components/inline-toc';
|
|
||||||
import { CalendarIcon, FileTextIcon } from 'lucide-react';
|
import { CalendarIcon, FileTextIcon } from 'lucide-react';
|
||||||
import type { Metadata } from 'next';
|
import type { Metadata } from 'next';
|
||||||
import type { Locale } from 'next-intl';
|
import type { Locale } from 'next-intl';
|
||||||
@ -26,6 +21,7 @@ import Image from 'next/image';
|
|||||||
import { notFound } from 'next/navigation';
|
import { notFound } from 'next/navigation';
|
||||||
|
|
||||||
import '@/styles/mdx.css';
|
import '@/styles/mdx.css';
|
||||||
|
import { InlineTOC } from 'fumadocs-ui/components/inline-toc';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* get related posts, random pick from all posts with same locale, different slug,
|
* get related posts, random pick from all posts with same locale, different slug,
|
||||||
@ -87,8 +83,7 @@ export default async function BlogPostPage(props: BlogPostPageProps) {
|
|||||||
notFound();
|
notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
const { date, title, description, image, author, categories, premium } =
|
const { date, title, description, image, author, categories } = post.data;
|
||||||
post.data;
|
|
||||||
const publishDate = formatDate(new Date(date));
|
const publishDate = formatDate(new Date(date));
|
||||||
|
|
||||||
const blogAuthor = authorSource.getPage([author], locale);
|
const blogAuthor = authorSource.getPage([author], locale);
|
||||||
@ -96,13 +91,6 @@ export default async function BlogPostPage(props: BlogPostPageProps) {
|
|||||||
.getPages(locale)
|
.getPages(locale)
|
||||||
.filter((category) => categories.includes(category.slugs[0] ?? ''));
|
.filter((category) => categories.includes(category.slugs[0] ?? ''));
|
||||||
|
|
||||||
// Check premium access for premium posts
|
|
||||||
const session = await getSession();
|
|
||||||
const hasPremiumAccess =
|
|
||||||
premium && session?.user?.id
|
|
||||||
? await checkPremiumAccess(session.user.id)
|
|
||||||
: !premium; // Non-premium posts are always accessible
|
|
||||||
|
|
||||||
const MDX = post.data.body;
|
const MDX = post.data.body;
|
||||||
|
|
||||||
// getTranslations may cause error DYNAMIC_SERVER_USAGE, so we set dynamic to force-static
|
// getTranslations may cause error DYNAMIC_SERVER_USAGE, so we set dynamic to force-static
|
||||||
@ -133,7 +121,7 @@ export default async function BlogPostPage(props: BlogPostPageProps) {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* blog post date and premium badge */}
|
{/* blog post date */}
|
||||||
<div className="flex items-center justify-between gap-2">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<CalendarIcon className="size-4 text-muted-foreground" />
|
<CalendarIcon className="size-4 text-muted-foreground" />
|
||||||
@ -141,8 +129,6 @@ export default async function BlogPostPage(props: BlogPostPageProps) {
|
|||||||
{publishDate}
|
{publishDate}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{premium && <PremiumBadge size="sm" />}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* blog post title */}
|
{/* blog post title */}
|
||||||
@ -155,14 +141,8 @@ export default async function BlogPostPage(props: BlogPostPageProps) {
|
|||||||
{/* blog post content */}
|
{/* blog post content */}
|
||||||
{/* in order to make the mdx.css work, we need to add the className prose to the div */}
|
{/* in order to make the mdx.css work, we need to add the className prose to the div */}
|
||||||
{/* https://github.com/tailwindlabs/tailwindcss-typography */}
|
{/* https://github.com/tailwindlabs/tailwindcss-typography */}
|
||||||
<div className="mt-8">
|
<div className="mt-8 max-w-none prose prose-neutral dark:prose-invert prose-img:rounded-lg">
|
||||||
<PremiumGuard
|
<MDX components={getMDXComponents()} />
|
||||||
isPremium={!!premium}
|
|
||||||
canAccess={hasPremiumAccess}
|
|
||||||
className="max-w-none"
|
|
||||||
>
|
|
||||||
<MDX components={getMDXComponents()} />
|
|
||||||
</PremiumGuard>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex items-center justify-start my-16">
|
<div className="flex items-center justify-start my-16">
|
||||||
@ -232,8 +212,8 @@ export default async function BlogPostPage(props: BlogPostPageProps) {
|
|||||||
{relatedPosts && relatedPosts.length > 0 && (
|
{relatedPosts && relatedPosts.length > 0 && (
|
||||||
<div className="flex flex-col gap-8 mt-8">
|
<div className="flex flex-col gap-8 mt-8">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<FileTextIcon className="size-4 text-primary" />
|
<FileTextIcon className="size-4 text-muted-foreground" />
|
||||||
<h2 className="text-lg tracking-wider font-semibold text-primary">
|
<h2 className="text-lg tracking-wider font-semibold text-gradient_indigo-purple">
|
||||||
{t('morePosts')}
|
{t('morePosts')}
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import { DashboardHeader } from '@/components/dashboard/dashboard-header';
|
import { DashboardHeader } from '@/components/dashboard/dashboard-header';
|
||||||
import { isDemoWebsite } from '@/lib/demo';
|
|
||||||
import { getSession } from '@/lib/server';
|
import { getSession } from '@/lib/server';
|
||||||
import { getTranslations } from 'next-intl/server';
|
import { getTranslations } from 'next-intl/server';
|
||||||
import { notFound } from 'next/navigation';
|
import { notFound } from 'next/navigation';
|
||||||
@ -10,7 +9,7 @@ interface UsersLayoutProps {
|
|||||||
|
|
||||||
export default async function UsersLayout({ children }: UsersLayoutProps) {
|
export default async function UsersLayout({ children }: UsersLayoutProps) {
|
||||||
// if is demo website, allow user to access admin and user pages, but data is fake
|
// if is demo website, allow user to access admin and user pages, but data is fake
|
||||||
const isDemo = isDemoWebsite();
|
const isDemo = process.env.NEXT_PUBLIC_DEMO_WEBSITE === 'true';
|
||||||
// Check if user is admin
|
// Check if user is admin
|
||||||
const session = await getSession();
|
const session = await getSession();
|
||||||
if (!session || (session.user.role !== 'admin' && !isDemo)) {
|
if (!session || (session.user.role !== 'admin' && !isDemo)) {
|
||||||
|
5
src/app/[locale]/(protected)/admin/users/loading.tsx
Normal file
5
src/app/[locale]/(protected)/admin/users/loading.tsx
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { Loader2Icon } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <Loader2Icon className="my-32 mx-auto size-6 animate-spin" />;
|
||||||
|
}
|
5
src/app/[locale]/(protected)/loading.tsx
Normal file
5
src/app/[locale]/(protected)/loading.tsx
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
import { Loader2Icon } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <Loader2Icon className="my-32 mx-auto size-6 animate-spin" />;
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
import { Loader2Icon } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <Loader2Icon className="my-32 mx-auto size-6 animate-spin" />;
|
||||||
|
}
|
@ -1,14 +1,23 @@
|
|||||||
import BillingCard from '@/components/settings/billing/billing-card';
|
import BillingCard from '@/components/settings/billing/billing-card';
|
||||||
|
import CreditsBalanceCard from '@/components/settings/billing/credits-balance-card';
|
||||||
|
import { CreditPackages } from '@/components/settings/credits/credit-packages';
|
||||||
|
import { websiteConfig } from '@/config/website';
|
||||||
|
|
||||||
/**
|
|
||||||
* Billing page, show billing information
|
|
||||||
*/
|
|
||||||
export default function BillingPage() {
|
export default function BillingPage() {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-8">
|
<div className="space-y-8">
|
||||||
|
{/* Billing and Credits Balance Cards */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
<BillingCard />
|
<BillingCard />
|
||||||
|
{websiteConfig.credits.enableCredits && <CreditsBalanceCard />}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Credit Packages */}
|
||||||
|
{websiteConfig.credits.enableCredits && (
|
||||||
|
<div className="w-full">
|
||||||
|
<CreditPackages />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,5 @@
|
|||||||
|
import { Loader2Icon } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <Loader2Icon className="my-32 mx-auto size-6 animate-spin" />;
|
||||||
|
}
|
@ -1,10 +1,10 @@
|
|||||||
import CreditsPageClient from '@/components/settings/credits/credits-page-client';
|
import { CreditTransactionsPageClient } from '@/components/settings/credits/credit-transactions-page';
|
||||||
import { websiteConfig } from '@/config/website';
|
import { websiteConfig } from '@/config/website';
|
||||||
import { Routes } from '@/routes';
|
import { Routes } from '@/routes';
|
||||||
import { redirect } from 'next/navigation';
|
import { redirect } from 'next/navigation';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Credits page, show credit balance and transactions
|
* Credits page, show credit transactions
|
||||||
*/
|
*/
|
||||||
export default function CreditsPage() {
|
export default function CreditsPage() {
|
||||||
// If credits are disabled, redirect to billing page
|
// If credits are disabled, redirect to billing page
|
||||||
@ -12,5 +12,5 @@ export default function CreditsPage() {
|
|||||||
redirect(Routes.SettingsBilling);
|
redirect(Routes.SettingsBilling);
|
||||||
}
|
}
|
||||||
|
|
||||||
return <CreditsPageClient />;
|
return <CreditTransactionsPageClient />;
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,5 @@
|
|||||||
|
import { Loader2Icon } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <Loader2Icon className="my-32 mx-auto size-6 animate-spin" />;
|
||||||
|
}
|
@ -0,0 +1,5 @@
|
|||||||
|
import { Loader2Icon } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <Loader2Icon className="my-32 mx-auto size-6 animate-spin" />;
|
||||||
|
}
|
@ -5,10 +5,10 @@ export default function ProfilePage() {
|
|||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-8">
|
<div className="flex flex-col gap-8">
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
<UpdateNameCard />
|
<UpdateAvatarCard />
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
<UpdateAvatarCard />
|
<UpdateNameCard />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
@ -0,0 +1,5 @@
|
|||||||
|
import { Loader2Icon } from 'lucide-react';
|
||||||
|
|
||||||
|
export default function Loading() {
|
||||||
|
return <Loader2Icon className="my-32 mx-auto size-6 animate-spin" />;
|
||||||
|
}
|
@ -1,7 +1,5 @@
|
|||||||
import * as Preview from '@/components/docs';
|
import * as Preview from '@/components/docs';
|
||||||
import { getMDXComponents } from '@/components/docs/mdx-components';
|
import { getMDXComponents } from '@/components/docs/mdx-components';
|
||||||
import { PremiumBadge } from '@/components/premium/premium-badge';
|
|
||||||
import { PremiumGuard } from '@/components/premium/premium-guard';
|
|
||||||
import {
|
import {
|
||||||
HoverCard,
|
HoverCard,
|
||||||
HoverCardContent,
|
HoverCardContent,
|
||||||
@ -9,8 +7,6 @@ import {
|
|||||||
} from '@/components/ui/hover-card';
|
} from '@/components/ui/hover-card';
|
||||||
import { LOCALES } from '@/i18n/routing';
|
import { LOCALES } from '@/i18n/routing';
|
||||||
import { constructMetadata } from '@/lib/metadata';
|
import { constructMetadata } from '@/lib/metadata';
|
||||||
import { checkPremiumAccess } from '@/lib/premium-access';
|
|
||||||
import { getSession } from '@/lib/server';
|
|
||||||
import { source } from '@/lib/source';
|
import { source } from '@/lib/source';
|
||||||
import { getUrlWithLocale } from '@/lib/urls/urls';
|
import { getUrlWithLocale } from '@/lib/urls/urls';
|
||||||
import Link from 'fumadocs-core/link';
|
import Link from 'fumadocs-core/link';
|
||||||
@ -90,14 +86,6 @@ export default async function DocPage({ params }: DocPageProps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const preview = page.data.preview;
|
const preview = page.data.preview;
|
||||||
const { premium } = page.data;
|
|
||||||
|
|
||||||
// Check premium access for premium docs
|
|
||||||
const session = await getSession();
|
|
||||||
const hasPremiumAccess =
|
|
||||||
premium && session?.user?.id
|
|
||||||
? await checkPremiumAccess(session.user.id)
|
|
||||||
: !premium; // Non-premium docs are always accessible
|
|
||||||
|
|
||||||
const MDX = page.data.body;
|
const MDX = page.data.body;
|
||||||
|
|
||||||
@ -110,54 +98,44 @@ export default async function DocPage({ params }: DocPageProps) {
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<DocsTitle>{page.data.title}</DocsTitle>
|
<DocsTitle>{page.data.title}</DocsTitle>
|
||||||
{premium && <PremiumBadge size="sm" className="mt-2" />}
|
|
||||||
<DocsDescription>{page.data.description}</DocsDescription>
|
<DocsDescription>{page.data.description}</DocsDescription>
|
||||||
<DocsBody>
|
<DocsBody>
|
||||||
{/* Preview Rendered Component */}
|
{/* Preview Rendered Component */}
|
||||||
{preview ? <PreviewRenderer preview={preview} /> : null}
|
{preview ? <PreviewRenderer preview={preview} /> : null}
|
||||||
|
|
||||||
{/* MDX Content */}
|
{/* MDX Content */}
|
||||||
<PremiumGuard
|
<MDX
|
||||||
isPremium={!!premium}
|
components={getMDXComponents({
|
||||||
canAccess={hasPremiumAccess}
|
a: ({ href, ...props }: { href?: string; [key: string]: any }) => {
|
||||||
className="max-w-none"
|
const found = source.getPageByHref(href ?? '', {
|
||||||
>
|
dir: page.file.dirname,
|
||||||
<MDX
|
});
|
||||||
components={getMDXComponents({
|
|
||||||
a: ({
|
|
||||||
href,
|
|
||||||
...props
|
|
||||||
}: { href?: string; [key: string]: any }) => {
|
|
||||||
const found = source.getPageByHref(href ?? '', {
|
|
||||||
dir: page.file.dirname,
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!found) return <Link href={href} {...props} />;
|
if (!found) return <Link href={href} {...props} />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<HoverCard>
|
<HoverCard>
|
||||||
<HoverCardTrigger asChild>
|
<HoverCardTrigger asChild>
|
||||||
<Link
|
<Link
|
||||||
href={
|
href={
|
||||||
found.hash
|
found.hash
|
||||||
? `${found.page.url}#${found.hash}`
|
? `${found.page.url}#${found.hash}`
|
||||||
: found.page.url
|
: found.page.url
|
||||||
}
|
}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
</HoverCardTrigger>
|
</HoverCardTrigger>
|
||||||
<HoverCardContent className="text-sm">
|
<HoverCardContent className="text-sm">
|
||||||
<p className="font-medium">{found.page.data.title}</p>
|
<p className="font-medium">{found.page.data.title}</p>
|
||||||
<p className="text-fd-muted-foreground">
|
<p className="text-fd-muted-foreground">
|
||||||
{found.page.data.description}
|
{found.page.data.description}
|
||||||
</p>
|
</p>
|
||||||
</HoverCardContent>
|
</HoverCardContent>
|
||||||
</HoverCard>
|
</HoverCard>
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
})}
|
})}
|
||||||
/>
|
/>
|
||||||
</PremiumGuard>
|
|
||||||
</DocsBody>
|
</DocsBody>
|
||||||
</DocsPage>
|
</DocsPage>
|
||||||
);
|
);
|
||||||
|
@ -12,7 +12,6 @@ import { routing } from '@/i18n/routing';
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { type Locale, NextIntlClientProvider, hasLocale } from 'next-intl';
|
import { type Locale, NextIntlClientProvider, hasLocale } from 'next-intl';
|
||||||
import { notFound } from 'next/navigation';
|
import { notFound } from 'next/navigation';
|
||||||
import { NuqsAdapter } from 'nuqs/adapters/next/app';
|
|
||||||
import type { ReactNode } from 'react';
|
import type { ReactNode } from 'react';
|
||||||
import { Toaster } from 'sonner';
|
import { Toaster } from 'sonner';
|
||||||
import { Providers } from './providers';
|
import { Providers } from './providers';
|
||||||
@ -58,17 +57,15 @@ export default async function LocaleLayout({
|
|||||||
fontBricolageGrotesque.variable
|
fontBricolageGrotesque.variable
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<NuqsAdapter>
|
<NextIntlClientProvider>
|
||||||
<NextIntlClientProvider>
|
<Providers locale={locale}>
|
||||||
<Providers locale={locale}>
|
{children}
|
||||||
{children}
|
|
||||||
|
|
||||||
<Toaster richColors position="top-right" offset={64} />
|
<Toaster richColors position="top-right" offset={64} />
|
||||||
<TailwindIndicator />
|
<TailwindIndicator />
|
||||||
<Analytics />
|
<Analytics />
|
||||||
</Providers>
|
</Providers>
|
||||||
</NextIntlClientProvider>
|
</NextIntlClientProvider>
|
||||||
</NuqsAdapter>
|
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
);
|
);
|
||||||
|
@ -1,9 +1,10 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { ActiveThemeProvider } from '@/components/layout/active-theme-provider';
|
import { ActiveThemeProvider } from '@/components/layout/active-theme-provider';
|
||||||
import { QueryProvider } from '@/components/providers/query-provider';
|
import { PaymentProvider } from '@/components/layout/payment-provider';
|
||||||
import { TooltipProvider } from '@/components/ui/tooltip';
|
import { TooltipProvider } from '@/components/ui/tooltip';
|
||||||
import { websiteConfig } from '@/config/website';
|
import { websiteConfig } from '@/config/website';
|
||||||
|
import { CreditsProvider } from '@/providers/credits-provider';
|
||||||
import type { Translations } from 'fumadocs-ui/i18n';
|
import type { Translations } from 'fumadocs-ui/i18n';
|
||||||
import { RootProvider } from 'fumadocs-ui/provider';
|
import { RootProvider } from 'fumadocs-ui/provider';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
@ -29,7 +30,7 @@ interface ProvidersProps {
|
|||||||
*/
|
*/
|
||||||
export function Providers({ children, locale }: ProvidersProps) {
|
export function Providers({ children, locale }: ProvidersProps) {
|
||||||
const theme = useTheme();
|
const theme = useTheme();
|
||||||
const defaultMode = websiteConfig.ui.mode?.defaultMode ?? 'system';
|
const defaultMode = websiteConfig.metadata.mode?.defaultMode ?? 'system';
|
||||||
|
|
||||||
// available languages that will be displayed in the docs UI
|
// available languages that will be displayed in the docs UI
|
||||||
// make sure `locale` is consistent with your i18n config
|
// make sure `locale` is consistent with your i18n config
|
||||||
@ -53,19 +54,21 @@ export function Providers({ children, locale }: ProvidersProps) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<QueryProvider>
|
<ThemeProvider
|
||||||
<ThemeProvider
|
attribute="class"
|
||||||
attribute="class"
|
defaultTheme={defaultMode}
|
||||||
defaultTheme={defaultMode}
|
enableSystem={true}
|
||||||
enableSystem={true}
|
disableTransitionOnChange
|
||||||
disableTransitionOnChange
|
>
|
||||||
>
|
<ActiveThemeProvider>
|
||||||
<ActiveThemeProvider>
|
<RootProvider theme={theme} i18n={{ locale, locales, translations }}>
|
||||||
<RootProvider theme={theme} i18n={{ locale, locales, translations }}>
|
<TooltipProvider>
|
||||||
<TooltipProvider>{children}</TooltipProvider>
|
<PaymentProvider>
|
||||||
</RootProvider>
|
<CreditsProvider>{children}</CreditsProvider>
|
||||||
</ActiveThemeProvider>
|
</PaymentProvider>
|
||||||
</ThemeProvider>
|
</TooltipProvider>
|
||||||
</QueryProvider>
|
</RootProvider>
|
||||||
|
</ActiveThemeProvider>
|
||||||
|
</ThemeProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -13,20 +13,21 @@ import {
|
|||||||
validateUrl,
|
validateUrl,
|
||||||
} from '@/ai/text/utils/web-content-analyzer';
|
} from '@/ai/text/utils/web-content-analyzer';
|
||||||
import {
|
import {
|
||||||
|
getWebContentAnalysisCost,
|
||||||
validateFirecrawlConfig,
|
validateFirecrawlConfig,
|
||||||
webContentAnalyzerConfig,
|
webContentAnalyzerConfig,
|
||||||
} from '@/ai/text/utils/web-content-analyzer-config';
|
} from '@/ai/text/utils/web-content-analyzer-config';
|
||||||
import { createDeepSeek } from '@ai-sdk/deepseek';
|
import { consumeCredits, hasEnoughCredits } from '@/credits/credits';
|
||||||
import { createGoogleGenerativeAI } from '@ai-sdk/google';
|
import { getSession } from '@/lib/server';
|
||||||
import { createOpenAI } from '@ai-sdk/openai';
|
import { openai } from '@ai-sdk/openai';
|
||||||
import FirecrawlApp from '@mendable/firecrawl-js';
|
import FirecrawlApp from '@mendable/firecrawl-js';
|
||||||
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
|
|
||||||
import { generateObject } from 'ai';
|
import { generateObject } from 'ai';
|
||||||
import { type NextRequest, NextResponse } from 'next/server';
|
import { type NextRequest, NextResponse } from 'next/server';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
|
|
||||||
// Constants from configuration
|
// Constants from configuration
|
||||||
const TIMEOUT_MILLIS = webContentAnalyzerConfig.timeoutMillis;
|
const TIMEOUT_MILLIS = webContentAnalyzerConfig.timeoutMillis;
|
||||||
|
const CREDITS_COST = getWebContentAnalysisCost();
|
||||||
const MAX_CONTENT_LENGTH = webContentAnalyzerConfig.maxContentLength;
|
const MAX_CONTENT_LENGTH = webContentAnalyzerConfig.maxContentLength;
|
||||||
|
|
||||||
// Initialize Firecrawl client
|
// Initialize Firecrawl client
|
||||||
@ -194,57 +195,15 @@ async function scrapeWebpage(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Analyze content using selected provider with retry logic
|
// Analyze content using OpenAI with retry logic
|
||||||
async function analyzeContent(
|
async function analyzeContent(
|
||||||
content: string,
|
content: string,
|
||||||
url: string,
|
url: string
|
||||||
provider: string
|
|
||||||
): Promise<AnalysisResults> {
|
): Promise<AnalysisResults> {
|
||||||
return withRetry(async () => {
|
return withRetry(async () => {
|
||||||
try {
|
try {
|
||||||
let model: any;
|
|
||||||
let temperature: number | undefined;
|
|
||||||
let maxTokens: number | undefined;
|
|
||||||
switch (provider) {
|
|
||||||
case 'openai':
|
|
||||||
model = createOpenAI({
|
|
||||||
apiKey: process.env.OPENAI_API_KEY,
|
|
||||||
}).chat(webContentAnalyzerConfig.openai.model);
|
|
||||||
temperature = webContentAnalyzerConfig.openai.temperature;
|
|
||||||
maxTokens = webContentAnalyzerConfig.openai.maxTokens;
|
|
||||||
break;
|
|
||||||
case 'gemini':
|
|
||||||
model = createGoogleGenerativeAI({
|
|
||||||
apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY,
|
|
||||||
}).chat(webContentAnalyzerConfig.gemini.model);
|
|
||||||
temperature = webContentAnalyzerConfig.gemini.temperature;
|
|
||||||
maxTokens = webContentAnalyzerConfig.gemini.maxTokens;
|
|
||||||
break;
|
|
||||||
case 'deepseek':
|
|
||||||
model = createDeepSeek({
|
|
||||||
apiKey: process.env.DEEPSEEK_API_KEY,
|
|
||||||
}).chat(webContentAnalyzerConfig.deepseek.model);
|
|
||||||
temperature = webContentAnalyzerConfig.deepseek.temperature;
|
|
||||||
maxTokens = webContentAnalyzerConfig.deepseek.maxTokens;
|
|
||||||
break;
|
|
||||||
case 'openrouter':
|
|
||||||
model = createOpenRouter({
|
|
||||||
apiKey: process.env.OPENROUTER_API_KEY,
|
|
||||||
}).chat(webContentAnalyzerConfig.openrouter.model);
|
|
||||||
temperature = webContentAnalyzerConfig.openrouter.temperature;
|
|
||||||
maxTokens = webContentAnalyzerConfig.openrouter.maxTokens;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
throw new WebContentAnalyzerError(
|
|
||||||
ErrorType.VALIDATION,
|
|
||||||
'Invalid model provider',
|
|
||||||
'Please select a valid model provider.',
|
|
||||||
ErrorSeverity.MEDIUM,
|
|
||||||
false
|
|
||||||
);
|
|
||||||
}
|
|
||||||
const { object } = await generateObject({
|
const { object } = await generateObject({
|
||||||
model,
|
model: openai(webContentAnalyzerConfig.openai.model),
|
||||||
schema: analysisSchema,
|
schema: analysisSchema,
|
||||||
prompt: `
|
prompt: `
|
||||||
Analyze the following webpage content and extract structured information.
|
Analyze the following webpage content and extract structured information.
|
||||||
@ -257,8 +216,8 @@ async function analyzeContent(
|
|||||||
- For features and use cases: provide empty arrays if none are found
|
- For features and use cases: provide empty arrays if none are found
|
||||||
- Ensure the title and description are meaningful and based on the actual content
|
- Ensure the title and description are meaningful and based on the actual content
|
||||||
`,
|
`,
|
||||||
temperature,
|
temperature: webContentAnalyzerConfig.openai.temperature,
|
||||||
maxOutputTokens: maxTokens,
|
maxTokens: webContentAnalyzerConfig.openai.maxTokens,
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -270,9 +229,11 @@ async function analyzeContent(
|
|||||||
if (error instanceof WebContentAnalyzerError) {
|
if (error instanceof WebContentAnalyzerError) {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for specific OpenAI/AI errors
|
// Check for specific OpenAI/AI errors
|
||||||
if (error instanceof Error) {
|
if (error instanceof Error) {
|
||||||
const message = error.message.toLowerCase();
|
const message = error.message.toLowerCase();
|
||||||
|
|
||||||
if (message.includes('rate limit') || message.includes('quota')) {
|
if (message.includes('rate limit') || message.includes('quota')) {
|
||||||
throw new WebContentAnalyzerError(
|
throw new WebContentAnalyzerError(
|
||||||
ErrorType.RATE_LIMIT,
|
ErrorType.RATE_LIMIT,
|
||||||
@ -283,6 +244,7 @@ async function analyzeContent(
|
|||||||
error
|
error
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (message.includes('timeout') || message.includes('aborted')) {
|
if (message.includes('timeout') || message.includes('aborted')) {
|
||||||
throw new WebContentAnalyzerError(
|
throw new WebContentAnalyzerError(
|
||||||
ErrorType.TIMEOUT,
|
ErrorType.TIMEOUT,
|
||||||
@ -294,6 +256,7 @@ async function analyzeContent(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Classify and throw the error
|
// Classify and throw the error
|
||||||
throw classifyError(error);
|
throw classifyError(error);
|
||||||
}
|
}
|
||||||
@ -332,15 +295,14 @@ export async function POST(req: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { url, modelProvider } = validationResult.data;
|
const { url } = validationResult.data;
|
||||||
console.log('modelProvider', modelProvider, 'url', url);
|
|
||||||
|
|
||||||
// Additional URL validation
|
// Additional URL validation
|
||||||
const urlValidation = validateUrl(url);
|
const urlValidation = validateUrl(url);
|
||||||
if (!urlValidation.success) {
|
if (!urlValidation.success) {
|
||||||
const urlError = new WebContentAnalyzerError(
|
const urlError = new WebContentAnalyzerError(
|
||||||
ErrorType.VALIDATION,
|
ErrorType.VALIDATION,
|
||||||
urlValidation.error.issues[0]?.message || 'Invalid URL',
|
urlValidation.error.errors[0]?.message || 'Invalid URL',
|
||||||
'Please enter a valid URL starting with http:// or https://',
|
'Please enter a valid URL starting with http:// or https://',
|
||||||
ErrorSeverity.MEDIUM,
|
ErrorSeverity.MEDIUM,
|
||||||
false
|
false
|
||||||
@ -357,6 +319,28 @@ export async function POST(req: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Check authentication
|
||||||
|
const session = await getSession();
|
||||||
|
if (!session) {
|
||||||
|
const authError = new WebContentAnalyzerError(
|
||||||
|
ErrorType.AUTHENTICATION,
|
||||||
|
'Authentication required',
|
||||||
|
'Please sign in to analyze web content.',
|
||||||
|
ErrorSeverity.HIGH,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
logError(authError, { requestId });
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
success: false,
|
||||||
|
error: authError.userMessage,
|
||||||
|
} satisfies AnalyzeContentResponse,
|
||||||
|
{ status: 401 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// Check if Firecrawl is configured
|
// Check if Firecrawl is configured
|
||||||
if (!validateFirecrawlConfig()) {
|
if (!validateFirecrawlConfig()) {
|
||||||
const configError = new WebContentAnalyzerError(
|
const configError = new WebContentAnalyzerError(
|
||||||
@ -378,7 +362,39 @@ export async function POST(req: NextRequest) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Starting analysis [requestId=${requestId}, url=${url}]`);
|
// Check if user has sufficient credits before starting analysis
|
||||||
|
const hasCredits = await hasEnoughCredits({
|
||||||
|
userId: session.user.id,
|
||||||
|
requiredCredits: CREDITS_COST,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!hasCredits) {
|
||||||
|
const creditError = new WebContentAnalyzerError(
|
||||||
|
ErrorType.CREDITS,
|
||||||
|
'Insufficient credits to perform analysis',
|
||||||
|
"You don't have enough credits to analyze this webpage. Please purchase more credits.",
|
||||||
|
ErrorSeverity.HIGH,
|
||||||
|
false
|
||||||
|
);
|
||||||
|
|
||||||
|
logError(creditError, {
|
||||||
|
requestId,
|
||||||
|
userId: session.user.id,
|
||||||
|
requiredCredits: CREDITS_COST,
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
success: false,
|
||||||
|
error: creditError.userMessage,
|
||||||
|
} satisfies AnalyzeContentResponse,
|
||||||
|
{ status: 402 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Starting analysis [requestId=${requestId}, url=${url}, userId=${session.user.id}]`
|
||||||
|
);
|
||||||
|
|
||||||
// Perform analysis with timeout and enhanced error handling
|
// Perform analysis with timeout and enhanced error handling
|
||||||
const analysisPromise = (async () => {
|
const analysisPromise = (async () => {
|
||||||
@ -386,8 +402,15 @@ export async function POST(req: NextRequest) {
|
|||||||
// Step 1: Scrape webpage
|
// Step 1: Scrape webpage
|
||||||
const { content, screenshot } = await scrapeWebpage(url);
|
const { content, screenshot } = await scrapeWebpage(url);
|
||||||
|
|
||||||
// Step 2: Analyze content with AI (pass provider)
|
// Step 2: Analyze content with AI
|
||||||
const analysis = await analyzeContent(content, url, modelProvider);
|
const analysis = await analyzeContent(content, url);
|
||||||
|
|
||||||
|
// Step 3: Consume credits (only on successful analysis)
|
||||||
|
await consumeCredits({
|
||||||
|
userId: session.user.id,
|
||||||
|
amount: CREDITS_COST,
|
||||||
|
description: `Web content analysis: ${url}`,
|
||||||
|
});
|
||||||
|
|
||||||
return { analysis, screenshot };
|
return { analysis, screenshot };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -412,6 +435,7 @@ export async function POST(req: NextRequest) {
|
|||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
success: true,
|
success: true,
|
||||||
data: result,
|
data: result,
|
||||||
|
creditsConsumed: CREDITS_COST,
|
||||||
} satisfies AnalyzeContentResponse);
|
} satisfies AnalyzeContentResponse);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const elapsed = ((performance.now() - startTime) / 1000).toFixed(1);
|
const elapsed = ((performance.now() - startTime) / 1000).toFixed(1);
|
||||||
@ -433,6 +457,12 @@ export async function POST(req: NextRequest) {
|
|||||||
case ErrorType.VALIDATION:
|
case ErrorType.VALIDATION:
|
||||||
statusCode = 400;
|
statusCode = 400;
|
||||||
break;
|
break;
|
||||||
|
case ErrorType.AUTHENTICATION:
|
||||||
|
statusCode = 401;
|
||||||
|
break;
|
||||||
|
case ErrorType.CREDITS:
|
||||||
|
statusCode = 402;
|
||||||
|
break;
|
||||||
case ErrorType.TIMEOUT:
|
case ErrorType.TIMEOUT:
|
||||||
statusCode = 408;
|
statusCode = 408;
|
||||||
break;
|
break;
|
||||||
|
@ -1,26 +0,0 @@
|
|||||||
import { type UIMessage, convertToModelMessages, streamText } from 'ai';
|
|
||||||
|
|
||||||
// Allow streaming responses up to 30 seconds
|
|
||||||
export const maxDuration = 30;
|
|
||||||
|
|
||||||
export async function POST(req: Request) {
|
|
||||||
const {
|
|
||||||
messages,
|
|
||||||
model,
|
|
||||||
webSearch,
|
|
||||||
}: { messages: UIMessage[]; model: string; webSearch: boolean } =
|
|
||||||
await req.json();
|
|
||||||
|
|
||||||
const result = streamText({
|
|
||||||
model: webSearch ? 'perplexity/sonar' : model,
|
|
||||||
messages: convertToModelMessages(messages),
|
|
||||||
system:
|
|
||||||
'You are a helpful assistant that can answer questions and help with tasks',
|
|
||||||
});
|
|
||||||
|
|
||||||
// send sources and reasoning back to the client
|
|
||||||
return result.toUIMessageStreamResponse({
|
|
||||||
sendSources: true,
|
|
||||||
sendReasoning: true,
|
|
||||||
});
|
|
||||||
}
|
|
@ -1,60 +0,0 @@
|
|||||||
import { distributeCreditsToAllUsers } from '@/credits/distribute';
|
|
||||||
import { NextResponse } from 'next/server';
|
|
||||||
|
|
||||||
// Basic authentication middleware
|
|
||||||
function validateBasicAuth(request: Request): boolean {
|
|
||||||
const authHeader = request.headers.get('authorization');
|
|
||||||
|
|
||||||
if (!authHeader || !authHeader.startsWith('Basic ')) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extract credentials from Authorization header
|
|
||||||
const base64Credentials = authHeader.split(' ')[1];
|
|
||||||
const credentials = Buffer.from(base64Credentials, 'base64').toString(
|
|
||||||
'utf-8'
|
|
||||||
);
|
|
||||||
const [username, password] = credentials.split(':');
|
|
||||||
|
|
||||||
// Validate against environment variables
|
|
||||||
const expectedUsername = process.env.CRON_JOBS_USERNAME;
|
|
||||||
const expectedPassword = process.env.CRON_JOBS_PASSWORD;
|
|
||||||
|
|
||||||
if (!expectedUsername || !expectedPassword) {
|
|
||||||
console.error(
|
|
||||||
'Basic auth credentials not configured in environment variables'
|
|
||||||
);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return username === expectedUsername && password === expectedPassword;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* distribute credits to all users daily
|
|
||||||
*/
|
|
||||||
export async function GET(request: Request) {
|
|
||||||
// Validate basic authentication
|
|
||||||
if (!validateBasicAuth(request)) {
|
|
||||||
console.error('distribute credits unauthorized');
|
|
||||||
return new NextResponse('Unauthorized', {
|
|
||||||
status: 401,
|
|
||||||
headers: {
|
|
||||||
'WWW-Authenticate': 'Basic realm="Secure Area"',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('route: distribute credits start');
|
|
||||||
const { usersCount, processedCount, errorCount } =
|
|
||||||
await distributeCreditsToAllUsers();
|
|
||||||
console.log(
|
|
||||||
`route: distribute credits end, users: ${usersCount}, processed: ${processedCount}, errors: ${errorCount}`
|
|
||||||
);
|
|
||||||
return NextResponse.json({
|
|
||||||
message: `distribute credits success, users: ${usersCount}, processed: ${processedCount}, errors: ${errorCount}`,
|
|
||||||
usersCount,
|
|
||||||
processedCount,
|
|
||||||
errorCount,
|
|
||||||
});
|
|
||||||
}
|
|
20
src/app/api/hello/route.ts
Normal file
20
src/app/api/hello/route.ts
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
import { inngest } from '@/inngest/client';
|
||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
|
||||||
|
// Opt out of caching; every request should send a new event
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
// Create a simple async Next.js API route handler
|
||||||
|
export async function GET() {
|
||||||
|
console.log('Send event to Inngest start');
|
||||||
|
// Send your event payload to Inngest
|
||||||
|
await inngest.send({
|
||||||
|
name: 'test/hello.world',
|
||||||
|
data: {
|
||||||
|
email: 'testUser@example.com',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('Send event to Inngest end');
|
||||||
|
return NextResponse.json({ message: 'Event sent!' });
|
||||||
|
}
|
19
src/app/api/inngest/route.ts
Normal file
19
src/app/api/inngest/route.ts
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import { serve } from 'inngest/next';
|
||||||
|
import { inngest } from '../../../inngest/client';
|
||||||
|
import { distributeCreditsDaily, helloWorld } from '../../../inngest/functions';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inngest route
|
||||||
|
*
|
||||||
|
* https://www.inngest.com/docs/getting-started/nextjs-quick-start
|
||||||
|
*
|
||||||
|
* Next.js Edge Functions hosted on Vercel can also stream responses back to Inngest,
|
||||||
|
* giving you a much higher request timeout of 15 minutes (up from 10 seconds on the Vercel Hobby plan!).
|
||||||
|
* To enable this, set your runtime to "edge" (see Quickstart for Using Edge Functions | Vercel Docs)
|
||||||
|
* and add the streaming: "allow" option to your serve handler:
|
||||||
|
* https://www.inngest.com/docs/learn/serving-inngest-functions#framework-next-js
|
||||||
|
*/
|
||||||
|
export const { GET, POST, PUT } = serve({
|
||||||
|
client: inngest,
|
||||||
|
functions: [helloWorld, distributeCreditsDaily],
|
||||||
|
});
|
@ -14,6 +14,8 @@ type Href = Parameters<typeof getLocalePathname>[0]['href'];
|
|||||||
const staticRoutes = [
|
const staticRoutes = [
|
||||||
'/',
|
'/',
|
||||||
'/pricing',
|
'/pricing',
|
||||||
|
'/blog',
|
||||||
|
'/docs',
|
||||||
'/about',
|
'/about',
|
||||||
'/contact',
|
'/contact',
|
||||||
'/waitlist',
|
'/waitlist',
|
||||||
@ -23,8 +25,6 @@ const staticRoutes = [
|
|||||||
'/cookie',
|
'/cookie',
|
||||||
'/auth/login',
|
'/auth/login',
|
||||||
'/auth/register',
|
'/auth/register',
|
||||||
...(websiteConfig.blog.enable ? ['/blog'] : []),
|
|
||||||
...(websiteConfig.docs.enable ? ['/docs'] : []),
|
|
||||||
];
|
];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -48,106 +48,101 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
// add blog related routes if enabled
|
// add categories
|
||||||
if (websiteConfig.blog.enable) {
|
sitemapList.push(
|
||||||
// add categories
|
...categorySource.getPages().flatMap((category) =>
|
||||||
sitemapList.push(
|
routing.locales.map((locale) => ({
|
||||||
...categorySource.getPages().flatMap((category) =>
|
url: getUrl(`/blog/category/${category.slugs[0]}`, locale),
|
||||||
routing.locales.map((locale) => ({
|
lastModified: new Date(),
|
||||||
url: getUrl(`/blog/category/${category.slugs[0]}`, locale),
|
priority: 0.8,
|
||||||
lastModified: new Date(),
|
changeFrequency: 'weekly' as const,
|
||||||
priority: 0.8,
|
}))
|
||||||
changeFrequency: 'weekly' as const,
|
)
|
||||||
}))
|
);
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
// add paginated blog list pages
|
// add paginated blog list pages
|
||||||
routing.locales.forEach((locale) => {
|
routing.locales.forEach((locale) => {
|
||||||
const posts = blogSource
|
const posts = blogSource
|
||||||
|
.getPages(locale)
|
||||||
|
.filter((post) => post.data.published);
|
||||||
|
const totalPages = Math.max(
|
||||||
|
1,
|
||||||
|
Math.ceil(posts.length / websiteConfig.blog.paginationSize)
|
||||||
|
);
|
||||||
|
// /blog/page/[page] (from 2)
|
||||||
|
for (let page = 2; page <= totalPages; page++) {
|
||||||
|
sitemapList.push({
|
||||||
|
url: getUrl(`/blog/page/${page}`, locale),
|
||||||
|
lastModified: new Date(),
|
||||||
|
priority: 0.8,
|
||||||
|
changeFrequency: 'weekly' as const,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// add paginated category pages
|
||||||
|
routing.locales.forEach((locale) => {
|
||||||
|
const localeCategories = categorySource.getPages(locale);
|
||||||
|
localeCategories.forEach((category) => {
|
||||||
|
// posts in this category and locale
|
||||||
|
const postsInCategory = blogSource
|
||||||
.getPages(locale)
|
.getPages(locale)
|
||||||
.filter((post) => post.data.published);
|
.filter((post) => post.data.published)
|
||||||
|
.filter((post) =>
|
||||||
|
post.data.categories.some((cat) => cat === category.slugs[0])
|
||||||
|
);
|
||||||
const totalPages = Math.max(
|
const totalPages = Math.max(
|
||||||
1,
|
1,
|
||||||
Math.ceil(posts.length / websiteConfig.blog.paginationSize)
|
Math.ceil(postsInCategory.length / websiteConfig.blog.paginationSize)
|
||||||
);
|
);
|
||||||
// /blog/page/[page] (from 2)
|
// /blog/category/[slug] (first page)
|
||||||
|
sitemapList.push({
|
||||||
|
url: getUrl(`/blog/category/${category.slugs[0]}`, locale),
|
||||||
|
lastModified: new Date(),
|
||||||
|
priority: 0.8,
|
||||||
|
changeFrequency: 'weekly' as const,
|
||||||
|
});
|
||||||
|
// /blog/category/[slug]/page/[page] (from 2)
|
||||||
for (let page = 2; page <= totalPages; page++) {
|
for (let page = 2; page <= totalPages; page++) {
|
||||||
sitemapList.push({
|
sitemapList.push({
|
||||||
url: getUrl(`/blog/page/${page}`, locale),
|
url: getUrl(
|
||||||
|
`/blog/category/${category.slugs[0]}/page/${page}`,
|
||||||
|
locale
|
||||||
|
),
|
||||||
lastModified: new Date(),
|
lastModified: new Date(),
|
||||||
priority: 0.8,
|
priority: 0.8,
|
||||||
changeFrequency: 'weekly' as const,
|
changeFrequency: 'weekly' as const,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
// add paginated category pages
|
// add posts (single post pages)
|
||||||
routing.locales.forEach((locale) => {
|
sitemapList.push(
|
||||||
const localeCategories = categorySource.getPages(locale);
|
...blogSource.getPages().flatMap((post) =>
|
||||||
localeCategories.forEach((category) => {
|
routing.locales
|
||||||
// posts in this category and locale
|
.filter((locale) => post.locale === locale)
|
||||||
const postsInCategory = blogSource
|
.map((locale) => ({
|
||||||
.getPages(locale)
|
url: getUrl(`/blog/${post.slugs.join('/')}`, locale),
|
||||||
.filter((post) => post.data.published)
|
|
||||||
.filter((post) =>
|
|
||||||
post.data.categories.some((cat) => cat === category.slugs[0])
|
|
||||||
);
|
|
||||||
const totalPages = Math.max(
|
|
||||||
1,
|
|
||||||
Math.ceil(postsInCategory.length / websiteConfig.blog.paginationSize)
|
|
||||||
);
|
|
||||||
// /blog/category/[slug] (first page)
|
|
||||||
sitemapList.push({
|
|
||||||
url: getUrl(`/blog/category/${category.slugs[0]}`, locale),
|
|
||||||
lastModified: new Date(),
|
|
||||||
priority: 0.8,
|
|
||||||
changeFrequency: 'weekly' as const,
|
|
||||||
});
|
|
||||||
// /blog/category/[slug]/page/[page] (from 2)
|
|
||||||
for (let page = 2; page <= totalPages; page++) {
|
|
||||||
sitemapList.push({
|
|
||||||
url: getUrl(
|
|
||||||
`/blog/category/${category.slugs[0]}/page/${page}`,
|
|
||||||
locale
|
|
||||||
),
|
|
||||||
lastModified: new Date(),
|
|
||||||
priority: 0.8,
|
|
||||||
changeFrequency: 'weekly' as const,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// add posts (single post pages)
|
|
||||||
sitemapList.push(
|
|
||||||
...blogSource.getPages().flatMap((post) =>
|
|
||||||
routing.locales
|
|
||||||
.filter((locale) => post.locale === locale)
|
|
||||||
.map((locale) => ({
|
|
||||||
url: getUrl(`/blog/${post.slugs.join('/')}`, locale),
|
|
||||||
lastModified: new Date(),
|
|
||||||
priority: 0.8,
|
|
||||||
changeFrequency: 'weekly' as const,
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// add docs related routes if enabled
|
|
||||||
if (websiteConfig.docs.enable) {
|
|
||||||
const docsParams = source.generateParams();
|
|
||||||
sitemapList.push(
|
|
||||||
...docsParams.flatMap((param) =>
|
|
||||||
routing.locales.map((locale) => ({
|
|
||||||
url: getUrl(`/docs/${param.slug.join('/')}`, locale),
|
|
||||||
lastModified: new Date(),
|
lastModified: new Date(),
|
||||||
priority: 0.8,
|
priority: 0.8,
|
||||||
changeFrequency: 'weekly' as const,
|
changeFrequency: 'weekly' as const,
|
||||||
}))
|
}))
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
|
||||||
|
// add docs
|
||||||
|
const docsParams = source.generateParams();
|
||||||
|
sitemapList.push(
|
||||||
|
...docsParams.flatMap((param) =>
|
||||||
|
routing.locales.map((locale) => ({
|
||||||
|
url: getUrl(`/docs/${param.slug.join('/')}`, locale),
|
||||||
|
lastModified: new Date(),
|
||||||
|
priority: 0.8,
|
||||||
|
changeFrequency: 'weekly' as const,
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
return sitemapList;
|
return sitemapList;
|
||||||
}
|
}
|
||||||
|
@ -6,6 +6,7 @@ import {
|
|||||||
Drawer,
|
Drawer,
|
||||||
DrawerClose,
|
DrawerClose,
|
||||||
DrawerContent,
|
DrawerContent,
|
||||||
|
DrawerDescription,
|
||||||
DrawerFooter,
|
DrawerFooter,
|
||||||
DrawerHeader,
|
DrawerHeader,
|
||||||
DrawerTitle,
|
DrawerTitle,
|
||||||
@ -20,12 +21,12 @@ import {
|
|||||||
import { Separator } from '@/components/ui/separator';
|
import { Separator } from '@/components/ui/separator';
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
import { useIsMobile } from '@/hooks/use-mobile';
|
import { useIsMobile } from '@/hooks/use-mobile';
|
||||||
import { useBanUser, useUnbanUser } from '@/hooks/use-users';
|
import { authClient } from '@/lib/auth-client';
|
||||||
import type { User } from '@/lib/auth-types';
|
import type { User } from '@/lib/auth-types';
|
||||||
import { isDemoWebsite } from '@/lib/demo';
|
|
||||||
import { formatDate } from '@/lib/formatter';
|
import { formatDate } from '@/lib/formatter';
|
||||||
import { getStripeDashboardCustomerUrl } from '@/lib/urls/urls';
|
import { getStripeDashboardCustomerUrl } from '@/lib/urls/urls';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { useUsersStore } from '@/stores/users-store';
|
||||||
import {
|
import {
|
||||||
CalendarIcon,
|
CalendarIcon,
|
||||||
Loader2Icon,
|
Loader2Icon,
|
||||||
@ -45,16 +46,14 @@ interface UserDetailViewerProps {
|
|||||||
export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
||||||
const t = useTranslations('Dashboard.admin.users');
|
const t = useTranslations('Dashboard.admin.users');
|
||||||
const isMobile = useIsMobile();
|
const isMobile = useIsMobile();
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [error, setError] = useState<string | undefined>();
|
const [error, setError] = useState<string | undefined>();
|
||||||
const [banReason, setBanReason] = useState(t('ban.defaultReason'));
|
const [banReason, setBanReason] = useState(t('ban.defaultReason'));
|
||||||
const [banExpiresAt, setBanExpiresAt] = useState<Date | undefined>();
|
const [banExpiresAt, setBanExpiresAt] = useState<Date | undefined>();
|
||||||
|
const triggerRefresh = useUsersStore((state) => state.triggerRefresh);
|
||||||
// TanStack Query mutations
|
|
||||||
const banUserMutation = useBanUser();
|
|
||||||
const unbanUserMutation = useUnbanUser();
|
|
||||||
|
|
||||||
// show fake data in demo website
|
// show fake data in demo website
|
||||||
const isDemo = isDemoWebsite();
|
const isDemo = process.env.NEXT_PUBLIC_DEMO_WEBSITE === 'true';
|
||||||
|
|
||||||
const handleBan = async () => {
|
const handleBan = async () => {
|
||||||
if (!banReason) {
|
if (!banReason) {
|
||||||
@ -67,10 +66,11 @@ export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
setError('');
|
setError('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await banUserMutation.mutateAsync({
|
await authClient.admin.banUser({
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
banReason,
|
banReason,
|
||||||
banExpiresIn: banExpiresAt
|
banExpiresIn: banExpiresAt
|
||||||
@ -82,11 +82,15 @@ export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
|||||||
// Reset form
|
// Reset form
|
||||||
setBanReason('');
|
setBanReason('');
|
||||||
setBanExpiresAt(undefined);
|
setBanExpiresAt(undefined);
|
||||||
|
// Trigger refresh
|
||||||
|
triggerRefresh();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const error = err as Error;
|
const error = err as Error;
|
||||||
console.error('Failed to ban user:', error);
|
console.error('Failed to ban user:', error);
|
||||||
setError(error.message || t('ban.error'));
|
setError(error.message || t('ban.error'));
|
||||||
toast.error(error.message || t('ban.error'));
|
toast.error(error.message || t('ban.error'));
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -96,19 +100,24 @@ export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
setError('');
|
setError('');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await unbanUserMutation.mutateAsync({
|
await authClient.admin.unbanUser({
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
});
|
});
|
||||||
|
|
||||||
toast.success(t('unban.success'));
|
toast.success(t('unban.success'));
|
||||||
|
// Trigger refresh
|
||||||
|
triggerRefresh();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const error = err as Error;
|
const error = err as Error;
|
||||||
console.error('Failed to unban user:', error);
|
console.error('Failed to unban user:', error);
|
||||||
setError(error.message || t('unban.error'));
|
setError(error.message || t('unban.error'));
|
||||||
toast.error(error.message || t('unban.error'));
|
toast.error(error.message || t('unban.error'));
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -156,7 +165,7 @@ export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
|||||||
{user.role === 'admin' ? t('admin') : t('user')}
|
{user.role === 'admin' ? t('admin') : t('user')}
|
||||||
</Badge>
|
</Badge>
|
||||||
{/* email verified */}
|
{/* email verified */}
|
||||||
{/* <Badge variant="outline" className="px-1.5 hover:bg-accent">
|
<Badge variant="outline" className="px-1.5 hover:bg-accent">
|
||||||
{user.emailVerified ? (
|
{user.emailVerified ? (
|
||||||
<MailCheckIcon className="stroke-green-500 dark:stroke-green-400" />
|
<MailCheckIcon className="stroke-green-500 dark:stroke-green-400" />
|
||||||
) : (
|
) : (
|
||||||
@ -165,7 +174,7 @@ export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
|||||||
{user.emailVerified
|
{user.emailVerified
|
||||||
? t('email.verified')
|
? t('email.verified')
|
||||||
: t('email.unverified')}
|
: t('email.unverified')}
|
||||||
</Badge> */}
|
</Badge>
|
||||||
|
|
||||||
{/* user banned */}
|
{/* user banned */}
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
@ -186,23 +195,15 @@ export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
|||||||
<span className="text-muted-foreground text-xs">
|
<span className="text-muted-foreground text-xs">
|
||||||
{t('columns.email')}:
|
{t('columns.email')}:
|
||||||
</span>
|
</span>
|
||||||
<div className="flex items-center gap-2">
|
<span
|
||||||
<Badge
|
className="break-words cursor-pointer hover:bg-accent px-2 py-1 rounded border"
|
||||||
variant="outline"
|
onClick={() => {
|
||||||
className="text-sm px-1.5 cursor-pointer hover:bg-accent"
|
navigator.clipboard.writeText(user.email!);
|
||||||
onClick={() => {
|
toast.success(t('emailCopied'));
|
||||||
navigator.clipboard.writeText(user.email);
|
}}
|
||||||
toast.success(t('emailCopied'));
|
>
|
||||||
}}
|
{user.email}
|
||||||
>
|
</span>
|
||||||
{user.emailVerified ? (
|
|
||||||
<MailCheckIcon className="stroke-green-500 dark:stroke-green-400" />
|
|
||||||
) : (
|
|
||||||
<MailQuestionIcon className="stroke-red-500 dark:stroke-red-400" />
|
|
||||||
)}
|
|
||||||
{user.email}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@ -254,10 +255,10 @@ export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
|||||||
<Button
|
<Button
|
||||||
variant="destructive"
|
variant="destructive"
|
||||||
onClick={handleUnban}
|
onClick={handleUnban}
|
||||||
disabled={unbanUserMutation.isPending || isDemo}
|
disabled={isLoading || isDemo}
|
||||||
className="mt-4 cursor-pointer"
|
className="mt-4 cursor-pointer"
|
||||||
>
|
>
|
||||||
{unbanUserMutation.isPending && (
|
{isLoading && (
|
||||||
<Loader2Icon className="mr-2 size-4 animate-spin" />
|
<Loader2Icon className="mr-2 size-4 animate-spin" />
|
||||||
)}
|
)}
|
||||||
{t('unban.button')}
|
{t('unban.button')}
|
||||||
@ -313,10 +314,10 @@ export function UserDetailViewer({ user }: UserDetailViewerProps) {
|
|||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
variant="destructive"
|
variant="destructive"
|
||||||
disabled={banUserMutation.isPending || !banReason || isDemo}
|
disabled={isLoading || !banReason || isDemo}
|
||||||
className="mt-4 cursor-pointer"
|
className="mt-4 cursor-pointer"
|
||||||
>
|
>
|
||||||
{banUserMutation.isPending && (
|
{isLoading && (
|
||||||
<Loader2Icon className="mr-2 size-4 animate-spin" />
|
<Loader2Icon className="mr-2 size-4 animate-spin" />
|
||||||
)}
|
)}
|
||||||
{t('ban.button')}
|
{t('ban.button')}
|
||||||
|
@ -1,59 +1,74 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
|
import { getUsersAction } from '@/actions/get-users';
|
||||||
import { UsersTable } from '@/components/admin/users-table';
|
import { UsersTable } from '@/components/admin/users-table';
|
||||||
import { useUsers } from '@/hooks/use-users';
|
import type { User } from '@/lib/auth-types';
|
||||||
|
import { useUsersStore } from '@/stores/users-store';
|
||||||
import type { SortingState } from '@tanstack/react-table';
|
import type { SortingState } from '@tanstack/react-table';
|
||||||
import { useTranslations } from 'next-intl';
|
import { useTranslations } from 'next-intl';
|
||||||
import {
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
parseAsIndex,
|
import { toast } from 'sonner';
|
||||||
parseAsInteger,
|
|
||||||
parseAsString,
|
|
||||||
useQueryStates,
|
|
||||||
} from 'nuqs';
|
|
||||||
import { useMemo } from 'react';
|
|
||||||
|
|
||||||
export function UsersPageClient() {
|
export function UsersPageClient() {
|
||||||
const t = useTranslations('Dashboard.admin.users');
|
const t = useTranslations('Dashboard.admin.users');
|
||||||
|
const [pageIndex, setPageIndex] = useState(0);
|
||||||
|
const [pageSize, setPageSize] = useState(10);
|
||||||
|
const [search, setSearch] = useState('');
|
||||||
|
const [data, setData] = useState<User[]>([]);
|
||||||
|
const [total, setTotal] = useState(0);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [sorting, setSorting] = useState<SortingState>([
|
||||||
|
{ id: 'createdAt', desc: true },
|
||||||
|
]);
|
||||||
|
const refreshTrigger = useUsersStore((state) => state.refreshTrigger);
|
||||||
|
|
||||||
const [{ page, pageSize, search, sortId, sortDesc }, setQueryStates] =
|
const fetchUsers = useCallback(async () => {
|
||||||
useQueryStates({
|
try {
|
||||||
page: parseAsIndex.withDefault(0), // parseAsIndex adds +1 to URL, so 0-based internally, 1-based in URL
|
setLoading(true);
|
||||||
pageSize: parseAsInteger.withDefault(10),
|
const result = await getUsersAction({
|
||||||
search: parseAsString.withDefault(''),
|
pageIndex,
|
||||||
sortId: parseAsString.withDefault('createdAt'),
|
pageSize,
|
||||||
sortDesc: parseAsInteger.withDefault(1),
|
search,
|
||||||
});
|
sorting,
|
||||||
|
});
|
||||||
|
|
||||||
const sorting: SortingState = useMemo(
|
if (result?.data?.success) {
|
||||||
() => [{ id: sortId, desc: Boolean(sortDesc) }],
|
setData(result.data.data?.items || []);
|
||||||
[sortId, sortDesc]
|
setTotal(result.data.data?.total || 0);
|
||||||
);
|
} else {
|
||||||
|
const errorMessage = result?.data?.error || t('error');
|
||||||
|
toast.error(errorMessage);
|
||||||
|
setData([]);
|
||||||
|
setTotal(0);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch users:', error);
|
||||||
|
toast.error(t('error'));
|
||||||
|
setData([]);
|
||||||
|
setTotal(0);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [pageIndex, pageSize, search, sorting, refreshTrigger]);
|
||||||
|
|
||||||
// page is already 0-based internally thanks to parseAsIndex
|
useEffect(() => {
|
||||||
const { data, isLoading } = useUsers(page, pageSize, search, sorting);
|
fetchUsers();
|
||||||
|
}, [fetchUsers]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<UsersTable
|
<>
|
||||||
data={data?.items || []}
|
<UsersTable
|
||||||
total={data?.total || 0}
|
data={data}
|
||||||
pageIndex={page}
|
total={total}
|
||||||
pageSize={pageSize}
|
pageIndex={pageIndex}
|
||||||
search={search}
|
pageSize={pageSize}
|
||||||
sorting={sorting}
|
search={search}
|
||||||
loading={isLoading}
|
loading={loading}
|
||||||
onSearch={(newSearch) => setQueryStates({ search: newSearch, page: 0 })}
|
onSearch={setSearch}
|
||||||
onPageChange={(newPageIndex) => setQueryStates({ page: newPageIndex })}
|
onPageChange={setPageIndex}
|
||||||
onPageSizeChange={(newPageSize) =>
|
onPageSizeChange={setPageSize}
|
||||||
setQueryStates({ pageSize: newPageSize, page: 0 })
|
onSortingChange={setSorting}
|
||||||
}
|
/>
|
||||||
onSortingChange={(newSorting) => {
|
</>
|
||||||
if (newSorting.length > 0) {
|
|
||||||
setQueryStates({
|
|
||||||
sortId: newSorting[0].id,
|
|
||||||
sortDesc: newSorting[0].desc ? 1 : 0,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -27,7 +27,6 @@ import {
|
|||||||
TableRow,
|
TableRow,
|
||||||
} from '@/components/ui/table';
|
} from '@/components/ui/table';
|
||||||
import type { User } from '@/lib/auth-types';
|
import type { User } from '@/lib/auth-types';
|
||||||
import { isDemoWebsite } from '@/lib/demo';
|
|
||||||
import { formatDate } from '@/lib/formatter';
|
import { formatDate } from '@/lib/formatter';
|
||||||
import { getStripeDashboardCustomerUrl } from '@/lib/urls/urls';
|
import { getStripeDashboardCustomerUrl } from '@/lib/urls/urls';
|
||||||
import { IconCaretDownFilled, IconCaretUpFilled } from '@tabler/icons-react';
|
import { IconCaretDownFilled, IconCaretUpFilled } from '@tabler/icons-react';
|
||||||
@ -59,7 +58,6 @@ import { useState } from 'react';
|
|||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { Badge } from '../ui/badge';
|
import { Badge } from '../ui/badge';
|
||||||
import { Label } from '../ui/label';
|
import { Label } from '../ui/label';
|
||||||
import { Skeleton } from '../ui/skeleton';
|
|
||||||
|
|
||||||
interface DataTableColumnHeaderProps<TData, TValue>
|
interface DataTableColumnHeaderProps<TData, TValue>
|
||||||
extends React.HTMLAttributes<HTMLDivElement> {
|
extends React.HTMLAttributes<HTMLDivElement> {
|
||||||
@ -117,27 +115,12 @@ function DataTableColumnHeader<TData, TValue>({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function TableRowSkeleton({ columns }: { columns: number }) {
|
|
||||||
return (
|
|
||||||
<TableRow>
|
|
||||||
{Array.from({ length: columns }).map((_, index) => (
|
|
||||||
<TableCell key={index} className="py-4">
|
|
||||||
<div className="flex items-center gap-2 pl-3">
|
|
||||||
<Skeleton className="h-6 w-full max-w-32" />
|
|
||||||
</div>
|
|
||||||
</TableCell>
|
|
||||||
))}
|
|
||||||
</TableRow>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface UsersTableProps {
|
interface UsersTableProps {
|
||||||
data: User[];
|
data: User[];
|
||||||
total: number;
|
total: number;
|
||||||
pageIndex: number;
|
pageIndex: number;
|
||||||
pageSize: number;
|
pageSize: number;
|
||||||
search: string;
|
search: string;
|
||||||
sorting?: SortingState;
|
|
||||||
loading?: boolean;
|
loading?: boolean;
|
||||||
onSearch: (search: string) => void;
|
onSearch: (search: string) => void;
|
||||||
onPageChange: (page: number) => void;
|
onPageChange: (page: number) => void;
|
||||||
@ -154,7 +137,6 @@ export function UsersTable({
|
|||||||
pageIndex,
|
pageIndex,
|
||||||
pageSize,
|
pageSize,
|
||||||
search,
|
search,
|
||||||
sorting = [{ id: 'createdAt', desc: true }],
|
|
||||||
loading,
|
loading,
|
||||||
onSearch,
|
onSearch,
|
||||||
onPageChange,
|
onPageChange,
|
||||||
@ -163,11 +145,14 @@ export function UsersTable({
|
|||||||
}: UsersTableProps) {
|
}: UsersTableProps) {
|
||||||
const t = useTranslations('Dashboard.admin.users');
|
const t = useTranslations('Dashboard.admin.users');
|
||||||
const tTable = useTranslations('Common.table');
|
const tTable = useTranslations('Common.table');
|
||||||
|
const [sorting, setSorting] = useState<SortingState>([
|
||||||
|
{ id: 'createdAt', desc: true },
|
||||||
|
]);
|
||||||
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
|
const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
|
||||||
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({});
|
||||||
|
|
||||||
// show fake data in demo website
|
// show fake data in demo website
|
||||||
const isDemo = isDemoWebsite();
|
const isDemo = process.env.NEXT_PUBLIC_DEMO_WEBSITE === 'true';
|
||||||
|
|
||||||
// Map column IDs to translation keys
|
// Map column IDs to translation keys
|
||||||
const columnIdToTranslationKey = {
|
const columnIdToTranslationKey = {
|
||||||
@ -365,6 +350,7 @@ export function UsersTable({
|
|||||||
},
|
},
|
||||||
onSortingChange: (updater) => {
|
onSortingChange: (updater) => {
|
||||||
const next = typeof updater === 'function' ? updater(sorting) : updater;
|
const next = typeof updater === 'function' ? updater(sorting) : updater;
|
||||||
|
setSorting(next);
|
||||||
onSortingChange?.(next);
|
onSortingChange?.(next);
|
||||||
},
|
},
|
||||||
onColumnFiltersChange: setColumnFilters,
|
onColumnFiltersChange: setColumnFilters,
|
||||||
@ -457,12 +443,7 @@ export function UsersTable({
|
|||||||
))}
|
))}
|
||||||
</TableHeader>
|
</TableHeader>
|
||||||
<TableBody>
|
<TableBody>
|
||||||
{loading ? (
|
{table.getRowModel().rows?.length ? (
|
||||||
// Show skeleton rows while loading
|
|
||||||
Array.from({ length: pageSize }).map((_, index) => (
|
|
||||||
<TableRowSkeleton key={index} columns={columns.length} />
|
|
||||||
))
|
|
||||||
) : table.getRowModel().rows?.length ? (
|
|
||||||
table.getRowModel().rows.map((row) => (
|
table.getRowModel().rows.map((row) => (
|
||||||
<TableRow
|
<TableRow
|
||||||
key={row.id}
|
key={row.id}
|
||||||
@ -484,7 +465,7 @@ export function UsersTable({
|
|||||||
colSpan={columns.length}
|
colSpan={columns.length}
|
||||||
className="h-24 text-center"
|
className="h-24 text-center"
|
||||||
>
|
>
|
||||||
{tTable('noResults')}
|
{loading ? tTable('loading') : tTable('noResults')}
|
||||||
</TableCell>
|
</TableCell>
|
||||||
</TableRow>
|
</TableRow>
|
||||||
)}
|
)}
|
||||||
|
@ -1,65 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import {
|
|
||||||
Tooltip,
|
|
||||||
TooltipContent,
|
|
||||||
TooltipProvider,
|
|
||||||
TooltipTrigger,
|
|
||||||
} from '@/components/ui/tooltip';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { ComponentProps } from 'react';
|
|
||||||
|
|
||||||
export type ActionsProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const Actions = ({ className, children, ...props }: ActionsProps) => (
|
|
||||||
<div className={cn('flex items-center gap-1', className)} {...props}>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type ActionProps = ComponentProps<typeof Button> & {
|
|
||||||
tooltip?: string;
|
|
||||||
label?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const Action = ({
|
|
||||||
tooltip,
|
|
||||||
children,
|
|
||||||
label,
|
|
||||||
className,
|
|
||||||
variant = 'ghost',
|
|
||||||
size = 'sm',
|
|
||||||
...props
|
|
||||||
}: ActionProps) => {
|
|
||||||
const button = (
|
|
||||||
<Button
|
|
||||||
className={cn(
|
|
||||||
'size-9 p-1.5 text-muted-foreground hover:text-foreground relative',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
size={size}
|
|
||||||
type="button"
|
|
||||||
variant={variant}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
<span className="sr-only">{label || tooltip}</span>
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
|
|
||||||
if (tooltip) {
|
|
||||||
return (
|
|
||||||
<TooltipProvider>
|
|
||||||
<Tooltip>
|
|
||||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
|
||||||
<TooltipContent>
|
|
||||||
<p>{tooltip}</p>
|
|
||||||
</TooltipContent>
|
|
||||||
</Tooltip>
|
|
||||||
</TooltipProvider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return button;
|
|
||||||
};
|
|
@ -1,212 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { UIMessage } from 'ai';
|
|
||||||
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
|
|
||||||
import type { ComponentProps, HTMLAttributes, ReactElement } from 'react';
|
|
||||||
import { createContext, useContext, useEffect, useState } from 'react';
|
|
||||||
|
|
||||||
type BranchContextType = {
|
|
||||||
currentBranch: number;
|
|
||||||
totalBranches: number;
|
|
||||||
goToPrevious: () => void;
|
|
||||||
goToNext: () => void;
|
|
||||||
branches: ReactElement[];
|
|
||||||
setBranches: (branches: ReactElement[]) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
const BranchContext = createContext<BranchContextType | null>(null);
|
|
||||||
|
|
||||||
const useBranch = () => {
|
|
||||||
const context = useContext(BranchContext);
|
|
||||||
|
|
||||||
if (!context) {
|
|
||||||
throw new Error('Branch components must be used within Branch');
|
|
||||||
}
|
|
||||||
|
|
||||||
return context;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type BranchProps = HTMLAttributes<HTMLDivElement> & {
|
|
||||||
defaultBranch?: number;
|
|
||||||
onBranchChange?: (branchIndex: number) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const Branch = ({
|
|
||||||
defaultBranch = 0,
|
|
||||||
onBranchChange,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: BranchProps) => {
|
|
||||||
const [currentBranch, setCurrentBranch] = useState(defaultBranch);
|
|
||||||
const [branches, setBranches] = useState<ReactElement[]>([]);
|
|
||||||
|
|
||||||
const handleBranchChange = (newBranch: number) => {
|
|
||||||
setCurrentBranch(newBranch);
|
|
||||||
onBranchChange?.(newBranch);
|
|
||||||
};
|
|
||||||
|
|
||||||
const goToPrevious = () => {
|
|
||||||
const newBranch =
|
|
||||||
currentBranch > 0 ? currentBranch - 1 : branches.length - 1;
|
|
||||||
handleBranchChange(newBranch);
|
|
||||||
};
|
|
||||||
|
|
||||||
const goToNext = () => {
|
|
||||||
const newBranch =
|
|
||||||
currentBranch < branches.length - 1 ? currentBranch + 1 : 0;
|
|
||||||
handleBranchChange(newBranch);
|
|
||||||
};
|
|
||||||
|
|
||||||
const contextValue: BranchContextType = {
|
|
||||||
currentBranch,
|
|
||||||
totalBranches: branches.length,
|
|
||||||
goToPrevious,
|
|
||||||
goToNext,
|
|
||||||
branches,
|
|
||||||
setBranches,
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<BranchContext.Provider value={contextValue}>
|
|
||||||
<div
|
|
||||||
className={cn('grid w-full gap-2 [&>div]:pb-0', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
</BranchContext.Provider>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type BranchMessagesProps = HTMLAttributes<HTMLDivElement>;
|
|
||||||
|
|
||||||
export const BranchMessages = ({ children, ...props }: BranchMessagesProps) => {
|
|
||||||
const { currentBranch, setBranches, branches } = useBranch();
|
|
||||||
const childrenArray = Array.isArray(children) ? children : [children];
|
|
||||||
|
|
||||||
// Use useEffect to update branches when they change
|
|
||||||
useEffect(() => {
|
|
||||||
if (branches.length !== childrenArray.length) {
|
|
||||||
setBranches(childrenArray);
|
|
||||||
}
|
|
||||||
}, [childrenArray, branches, setBranches]);
|
|
||||||
|
|
||||||
return childrenArray.map((branch, index) => (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'grid gap-2 overflow-hidden [&>div]:pb-0',
|
|
||||||
index === currentBranch ? 'block' : 'hidden'
|
|
||||||
)}
|
|
||||||
key={branch.key}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{branch}
|
|
||||||
</div>
|
|
||||||
));
|
|
||||||
};
|
|
||||||
|
|
||||||
export type BranchSelectorProps = HTMLAttributes<HTMLDivElement> & {
|
|
||||||
from: UIMessage['role'];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const BranchSelector = ({
|
|
||||||
className,
|
|
||||||
from,
|
|
||||||
...props
|
|
||||||
}: BranchSelectorProps) => {
|
|
||||||
const { totalBranches } = useBranch();
|
|
||||||
|
|
||||||
// Don't render if there's only one branch
|
|
||||||
if (totalBranches <= 1) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'flex items-center gap-2 self-end px-10',
|
|
||||||
from === 'assistant' ? 'justify-start' : 'justify-end',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type BranchPreviousProps = ComponentProps<typeof Button>;
|
|
||||||
|
|
||||||
export const BranchPrevious = ({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: BranchPreviousProps) => {
|
|
||||||
const { goToPrevious, totalBranches } = useBranch();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
aria-label="Previous branch"
|
|
||||||
className={cn(
|
|
||||||
'size-7 shrink-0 rounded-full text-muted-foreground transition-colors',
|
|
||||||
'hover:bg-accent hover:text-foreground',
|
|
||||||
'disabled:pointer-events-none disabled:opacity-50',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
disabled={totalBranches <= 1}
|
|
||||||
onClick={goToPrevious}
|
|
||||||
size="icon"
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children ?? <ChevronLeftIcon size={14} />}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type BranchNextProps = ComponentProps<typeof Button>;
|
|
||||||
|
|
||||||
export const BranchNext = ({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: BranchNextProps) => {
|
|
||||||
const { goToNext, totalBranches } = useBranch();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
aria-label="Next branch"
|
|
||||||
className={cn(
|
|
||||||
'size-7 shrink-0 rounded-full text-muted-foreground transition-colors',
|
|
||||||
'hover:bg-accent hover:text-foreground',
|
|
||||||
'disabled:pointer-events-none disabled:opacity-50',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
disabled={totalBranches <= 1}
|
|
||||||
onClick={goToNext}
|
|
||||||
size="icon"
|
|
||||||
type="button"
|
|
||||||
variant="ghost"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children ?? <ChevronRightIcon size={14} />}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type BranchPageProps = HTMLAttributes<HTMLSpanElement>;
|
|
||||||
|
|
||||||
export const BranchPage = ({ className, ...props }: BranchPageProps) => {
|
|
||||||
const { currentBranch, totalBranches } = useBranch();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
'font-medium text-muted-foreground text-xs tabular-nums',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{currentBranch + 1} of {totalBranches}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,148 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { CheckIcon, CopyIcon } from 'lucide-react';
|
|
||||||
import type { ComponentProps, HTMLAttributes, ReactNode } from 'react';
|
|
||||||
import { createContext, useContext, useState } from 'react';
|
|
||||||
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
|
|
||||||
import {
|
|
||||||
oneDark,
|
|
||||||
oneLight,
|
|
||||||
} from 'react-syntax-highlighter/dist/esm/styles/prism';
|
|
||||||
|
|
||||||
type CodeBlockContextType = {
|
|
||||||
code: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const CodeBlockContext = createContext<CodeBlockContextType>({
|
|
||||||
code: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
export type CodeBlockProps = HTMLAttributes<HTMLDivElement> & {
|
|
||||||
code: string;
|
|
||||||
language: string;
|
|
||||||
showLineNumbers?: boolean;
|
|
||||||
children?: ReactNode;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const CodeBlock = ({
|
|
||||||
code,
|
|
||||||
language,
|
|
||||||
showLineNumbers = false,
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: CodeBlockProps) => (
|
|
||||||
<CodeBlockContext.Provider value={{ code }}>
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'relative w-full overflow-hidden rounded-md border bg-background text-foreground',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<div className="relative">
|
|
||||||
<SyntaxHighlighter
|
|
||||||
className="overflow-hidden dark:hidden"
|
|
||||||
codeTagProps={{
|
|
||||||
className: 'font-mono text-sm',
|
|
||||||
}}
|
|
||||||
customStyle={{
|
|
||||||
margin: 0,
|
|
||||||
padding: '1rem',
|
|
||||||
fontSize: '0.875rem',
|
|
||||||
background: 'hsl(var(--background))',
|
|
||||||
color: 'hsl(var(--foreground))',
|
|
||||||
}}
|
|
||||||
language={language}
|
|
||||||
lineNumberStyle={{
|
|
||||||
color: 'hsl(var(--muted-foreground))',
|
|
||||||
paddingRight: '1rem',
|
|
||||||
minWidth: '2.5rem',
|
|
||||||
}}
|
|
||||||
showLineNumbers={showLineNumbers}
|
|
||||||
style={oneLight}
|
|
||||||
>
|
|
||||||
{code}
|
|
||||||
</SyntaxHighlighter>
|
|
||||||
<SyntaxHighlighter
|
|
||||||
className="hidden overflow-hidden dark:block"
|
|
||||||
codeTagProps={{
|
|
||||||
className: 'font-mono text-sm',
|
|
||||||
}}
|
|
||||||
customStyle={{
|
|
||||||
margin: 0,
|
|
||||||
padding: '1rem',
|
|
||||||
fontSize: '0.875rem',
|
|
||||||
background: 'hsl(var(--background))',
|
|
||||||
color: 'hsl(var(--foreground))',
|
|
||||||
}}
|
|
||||||
language={language}
|
|
||||||
lineNumberStyle={{
|
|
||||||
color: 'hsl(var(--muted-foreground))',
|
|
||||||
paddingRight: '1rem',
|
|
||||||
minWidth: '2.5rem',
|
|
||||||
}}
|
|
||||||
showLineNumbers={showLineNumbers}
|
|
||||||
style={oneDark}
|
|
||||||
>
|
|
||||||
{code}
|
|
||||||
</SyntaxHighlighter>
|
|
||||||
{children && (
|
|
||||||
<div className="absolute top-2 right-2 flex items-center gap-2">
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CodeBlockContext.Provider>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type CodeBlockCopyButtonProps = ComponentProps<typeof Button> & {
|
|
||||||
onCopy?: () => void;
|
|
||||||
onError?: (error: Error) => void;
|
|
||||||
timeout?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const CodeBlockCopyButton = ({
|
|
||||||
onCopy,
|
|
||||||
onError,
|
|
||||||
timeout = 2000,
|
|
||||||
children,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: CodeBlockCopyButtonProps) => {
|
|
||||||
const [isCopied, setIsCopied] = useState(false);
|
|
||||||
const { code } = useContext(CodeBlockContext);
|
|
||||||
|
|
||||||
const copyToClipboard = async () => {
|
|
||||||
if (typeof window === 'undefined' || !navigator.clipboard.writeText) {
|
|
||||||
onError?.(new Error('Clipboard API not available'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await navigator.clipboard.writeText(code);
|
|
||||||
setIsCopied(true);
|
|
||||||
onCopy?.();
|
|
||||||
setTimeout(() => setIsCopied(false), timeout);
|
|
||||||
} catch (error) {
|
|
||||||
onError?.(error as Error);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const Icon = isCopied ? CheckIcon : CopyIcon;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
className={cn('shrink-0', className)}
|
|
||||||
onClick={copyToClipboard}
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children ?? <Icon size={14} />}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,62 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { ArrowDownIcon } from 'lucide-react';
|
|
||||||
import type { ComponentProps } from 'react';
|
|
||||||
import { useCallback } from 'react';
|
|
||||||
import { StickToBottom, useStickToBottomContext } from 'use-stick-to-bottom';
|
|
||||||
|
|
||||||
export type ConversationProps = ComponentProps<typeof StickToBottom>;
|
|
||||||
|
|
||||||
export const Conversation = ({ className, ...props }: ConversationProps) => (
|
|
||||||
<StickToBottom
|
|
||||||
className={cn('relative flex-1 overflow-y-auto', className)}
|
|
||||||
initial="smooth"
|
|
||||||
resize="smooth"
|
|
||||||
role="log"
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type ConversationContentProps = ComponentProps<
|
|
||||||
typeof StickToBottom.Content
|
|
||||||
>;
|
|
||||||
|
|
||||||
export const ConversationContent = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: ConversationContentProps) => (
|
|
||||||
<StickToBottom.Content className={cn('p-4', className)} {...props} />
|
|
||||||
);
|
|
||||||
|
|
||||||
export type ConversationScrollButtonProps = ComponentProps<typeof Button>;
|
|
||||||
|
|
||||||
export const ConversationScrollButton = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: ConversationScrollButtonProps) => {
|
|
||||||
const { isAtBottom, scrollToBottom } = useStickToBottomContext();
|
|
||||||
|
|
||||||
const handleScrollToBottom = useCallback(() => {
|
|
||||||
scrollToBottom();
|
|
||||||
}, [scrollToBottom]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
!isAtBottom && (
|
|
||||||
<Button
|
|
||||||
className={cn(
|
|
||||||
'absolute bottom-4 left-[50%] translate-x-[-50%] rounded-full',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
onClick={handleScrollToBottom}
|
|
||||||
size="icon"
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ArrowDownIcon className="size-4" />
|
|
||||||
</Button>
|
|
||||||
)
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,24 +0,0 @@
|
|||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { Experimental_GeneratedImage } from 'ai';
|
|
||||||
|
|
||||||
export type ImageProps = Experimental_GeneratedImage & {
|
|
||||||
className?: string;
|
|
||||||
alt?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const Image = ({
|
|
||||||
base64,
|
|
||||||
uint8Array,
|
|
||||||
mediaType,
|
|
||||||
...props
|
|
||||||
}: ImageProps) => (
|
|
||||||
<img
|
|
||||||
{...props}
|
|
||||||
alt={props.alt}
|
|
||||||
className={cn(
|
|
||||||
'h-auto max-w-full overflow-hidden rounded-md',
|
|
||||||
props.className
|
|
||||||
)}
|
|
||||||
src={`data:${mediaType};base64,${base64}`}
|
|
||||||
/>
|
|
||||||
);
|
|
@ -1,287 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import {
|
|
||||||
Carousel,
|
|
||||||
CarouselContent,
|
|
||||||
CarouselItem,
|
|
||||||
type CarouselApi,
|
|
||||||
} from '@/components/ui/carousel';
|
|
||||||
import {
|
|
||||||
HoverCard,
|
|
||||||
HoverCardContent,
|
|
||||||
HoverCardTrigger,
|
|
||||||
} from '@/components/ui/hover-card';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { ArrowLeftIcon, ArrowRightIcon } from 'lucide-react';
|
|
||||||
import {
|
|
||||||
type ComponentProps,
|
|
||||||
createContext,
|
|
||||||
useCallback,
|
|
||||||
useContext,
|
|
||||||
useEffect,
|
|
||||||
useState,
|
|
||||||
} from 'react';
|
|
||||||
|
|
||||||
export type InlineCitationProps = ComponentProps<'span'>;
|
|
||||||
|
|
||||||
export const InlineCitation = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationProps) => (
|
|
||||||
<span
|
|
||||||
className={cn('group inline items-center gap-1', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type InlineCitationTextProps = ComponentProps<'span'>;
|
|
||||||
|
|
||||||
export const InlineCitationText = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationTextProps) => (
|
|
||||||
<span
|
|
||||||
className={cn('transition-colors group-hover:bg-accent', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type InlineCitationCardProps = ComponentProps<typeof HoverCard>;
|
|
||||||
|
|
||||||
export const InlineCitationCard = (props: InlineCitationCardProps) => (
|
|
||||||
<HoverCard closeDelay={0} openDelay={0} {...props} />
|
|
||||||
);
|
|
||||||
|
|
||||||
export type InlineCitationCardTriggerProps = ComponentProps<typeof Badge> & {
|
|
||||||
sources: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const InlineCitationCardTrigger = ({
|
|
||||||
sources,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationCardTriggerProps) => (
|
|
||||||
<HoverCardTrigger asChild>
|
|
||||||
<Badge
|
|
||||||
className={cn('ml-1 rounded-full', className)}
|
|
||||||
variant="secondary"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{sources.length ? (
|
|
||||||
<>
|
|
||||||
{new URL(sources[0]).hostname}{' '}
|
|
||||||
{sources.length > 1 && `+${sources.length - 1}`}
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
'unknown'
|
|
||||||
)}
|
|
||||||
</Badge>
|
|
||||||
</HoverCardTrigger>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type InlineCitationCardBodyProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const InlineCitationCardBody = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationCardBodyProps) => (
|
|
||||||
<HoverCardContent className={cn('relative w-80 p-0', className)} {...props} />
|
|
||||||
);
|
|
||||||
|
|
||||||
const CarouselApiContext = createContext<CarouselApi | undefined>(undefined);
|
|
||||||
|
|
||||||
const useCarouselApi = () => {
|
|
||||||
const context = useContext(CarouselApiContext);
|
|
||||||
return context;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type InlineCitationCarouselProps = ComponentProps<typeof Carousel>;
|
|
||||||
|
|
||||||
export const InlineCitationCarousel = ({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: InlineCitationCarouselProps) => {
|
|
||||||
const [api, setApi] = useState<CarouselApi>();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<CarouselApiContext.Provider value={api}>
|
|
||||||
<Carousel className={cn('w-full', className)} setApi={setApi} {...props}>
|
|
||||||
{children}
|
|
||||||
</Carousel>
|
|
||||||
</CarouselApiContext.Provider>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type InlineCitationCarouselContentProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const InlineCitationCarouselContent = (
|
|
||||||
props: InlineCitationCarouselContentProps
|
|
||||||
) => <CarouselContent {...props} />;
|
|
||||||
|
|
||||||
export type InlineCitationCarouselItemProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const InlineCitationCarouselItem = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationCarouselItemProps) => (
|
|
||||||
<CarouselItem
|
|
||||||
className={cn('w-full space-y-2 p-4 pl-8', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type InlineCitationCarouselHeaderProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const InlineCitationCarouselHeader = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationCarouselHeaderProps) => (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'flex items-center justify-between gap-2 rounded-t-md bg-secondary p-2',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type InlineCitationCarouselIndexProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const InlineCitationCarouselIndex = ({
|
|
||||||
children,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationCarouselIndexProps) => {
|
|
||||||
const api = useCarouselApi();
|
|
||||||
const [current, setCurrent] = useState(0);
|
|
||||||
const [count, setCount] = useState(0);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!api) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setCount(api.scrollSnapList().length);
|
|
||||||
setCurrent(api.selectedScrollSnap() + 1);
|
|
||||||
|
|
||||||
api.on('select', () => {
|
|
||||||
setCurrent(api.selectedScrollSnap() + 1);
|
|
||||||
});
|
|
||||||
}, [api]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'flex flex-1 items-center justify-end px-3 py-1 text-muted-foreground text-xs',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children ?? `${current}/${count}`}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type InlineCitationCarouselPrevProps = ComponentProps<'button'>;
|
|
||||||
|
|
||||||
export const InlineCitationCarouselPrev = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationCarouselPrevProps) => {
|
|
||||||
const api = useCarouselApi();
|
|
||||||
|
|
||||||
const handleClick = useCallback(() => {
|
|
||||||
if (api) {
|
|
||||||
api.scrollPrev();
|
|
||||||
}
|
|
||||||
}, [api]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
aria-label="Previous"
|
|
||||||
className={cn('shrink-0', className)}
|
|
||||||
onClick={handleClick}
|
|
||||||
type="button"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ArrowLeftIcon className="size-4 text-muted-foreground" />
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type InlineCitationCarouselNextProps = ComponentProps<'button'>;
|
|
||||||
|
|
||||||
export const InlineCitationCarouselNext = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationCarouselNextProps) => {
|
|
||||||
const api = useCarouselApi();
|
|
||||||
|
|
||||||
const handleClick = useCallback(() => {
|
|
||||||
if (api) {
|
|
||||||
api.scrollNext();
|
|
||||||
}
|
|
||||||
}, [api]);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
aria-label="Next"
|
|
||||||
className={cn('shrink-0', className)}
|
|
||||||
onClick={handleClick}
|
|
||||||
type="button"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<ArrowRightIcon className="size-4 text-muted-foreground" />
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type InlineCitationSourceProps = ComponentProps<'div'> & {
|
|
||||||
title?: string;
|
|
||||||
url?: string;
|
|
||||||
description?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const InlineCitationSource = ({
|
|
||||||
title,
|
|
||||||
url,
|
|
||||||
description,
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: InlineCitationSourceProps) => (
|
|
||||||
<div className={cn('space-y-1', className)} {...props}>
|
|
||||||
{title && (
|
|
||||||
<h4 className="truncate font-medium text-sm leading-tight">{title}</h4>
|
|
||||||
)}
|
|
||||||
{url && (
|
|
||||||
<p className="truncate break-all text-muted-foreground text-xs">{url}</p>
|
|
||||||
)}
|
|
||||||
{description && (
|
|
||||||
<p className="line-clamp-3 text-muted-foreground text-sm leading-relaxed">
|
|
||||||
{description}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type InlineCitationQuoteProps = ComponentProps<'blockquote'>;
|
|
||||||
|
|
||||||
export const InlineCitationQuote = ({
|
|
||||||
children,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: InlineCitationQuoteProps) => (
|
|
||||||
<blockquote
|
|
||||||
className={cn(
|
|
||||||
'border-muted border-l-2 pl-3 text-muted-foreground text-sm italic',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</blockquote>
|
|
||||||
);
|
|
@ -1,96 +0,0 @@
|
|||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { HTMLAttributes } from 'react';
|
|
||||||
|
|
||||||
type LoaderIconProps = {
|
|
||||||
size?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
const LoaderIcon = ({ size = 16 }: LoaderIconProps) => (
|
|
||||||
<svg
|
|
||||||
height={size}
|
|
||||||
strokeLinejoin="round"
|
|
||||||
style={{ color: 'currentcolor' }}
|
|
||||||
viewBox="0 0 16 16"
|
|
||||||
width={size}
|
|
||||||
>
|
|
||||||
<title>Loader</title>
|
|
||||||
<g clipPath="url(#clip0_2393_1490)">
|
|
||||||
<path d="M8 0V4" stroke="currentColor" strokeWidth="1.5" />
|
|
||||||
<path
|
|
||||||
d="M8 16V12"
|
|
||||||
opacity="0.5"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M3.29773 1.52783L5.64887 4.7639"
|
|
||||||
opacity="0.9"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M12.7023 1.52783L10.3511 4.7639"
|
|
||||||
opacity="0.1"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M12.7023 14.472L10.3511 11.236"
|
|
||||||
opacity="0.4"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M3.29773 14.472L5.64887 11.236"
|
|
||||||
opacity="0.6"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M15.6085 5.52783L11.8043 6.7639"
|
|
||||||
opacity="0.2"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M0.391602 10.472L4.19583 9.23598"
|
|
||||||
opacity="0.7"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M15.6085 10.4722L11.8043 9.2361"
|
|
||||||
opacity="0.3"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
/>
|
|
||||||
<path
|
|
||||||
d="M0.391602 5.52783L4.19583 6.7639"
|
|
||||||
opacity="0.8"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.5"
|
|
||||||
/>
|
|
||||||
</g>
|
|
||||||
<defs>
|
|
||||||
<clipPath id="clip0_2393_1490">
|
|
||||||
<rect fill="white" height="16" width="16" />
|
|
||||||
</clipPath>
|
|
||||||
</defs>
|
|
||||||
</svg>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type LoaderProps = HTMLAttributes<HTMLDivElement> & {
|
|
||||||
size?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const Loader = ({ className, size = 16, ...props }: LoaderProps) => (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'inline-flex animate-spin items-center justify-center',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<LoaderIcon size={size} />
|
|
||||||
</div>
|
|
||||||
);
|
|
@ -1,62 +0,0 @@
|
|||||||
import {
|
|
||||||
Avatar,
|
|
||||||
AvatarFallback,
|
|
||||||
AvatarImage,
|
|
||||||
} from '@/components/ui/avatar';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { UIMessage } from 'ai';
|
|
||||||
import type { ComponentProps, HTMLAttributes } from 'react';
|
|
||||||
|
|
||||||
export type MessageProps = HTMLAttributes<HTMLDivElement> & {
|
|
||||||
from: UIMessage['role'];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const Message = ({ className, from, ...props }: MessageProps) => (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'group flex w-full items-end justify-end gap-2 py-4',
|
|
||||||
from === 'user' ? 'is-user' : 'is-assistant flex-row-reverse justify-end',
|
|
||||||
'[&>div]:max-w-[80%]',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type MessageContentProps = HTMLAttributes<HTMLDivElement>;
|
|
||||||
|
|
||||||
export const MessageContent = ({
|
|
||||||
children,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: MessageContentProps) => (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'flex flex-col gap-2 overflow-hidden rounded-lg px-4 py-3 text-foreground text-sm',
|
|
||||||
'group-[.is-user]:bg-primary group-[.is-user]:text-primary-foreground',
|
|
||||||
'group-[.is-assistant]:bg-card group-[.is-assistant]:text-card-foreground',
|
|
||||||
'is-user:dark',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type MessageAvatarProps = ComponentProps<typeof Avatar> & {
|
|
||||||
src: string;
|
|
||||||
name?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const MessageAvatar = ({
|
|
||||||
src,
|
|
||||||
name,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: MessageAvatarProps) => (
|
|
||||||
<Avatar className={cn('size-8 ring-1 ring-border', className)} {...props}>
|
|
||||||
<AvatarImage alt="" className="mt-0 mb-0" src={src} />
|
|
||||||
<AvatarFallback>{name?.slice(0, 2) || 'ME'}</AvatarFallback>
|
|
||||||
</Avatar>
|
|
||||||
);
|
|
@ -1,230 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from '@/components/ui/select';
|
|
||||||
import { Textarea } from '@/components/ui/textarea';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { ChatStatus } from 'ai';
|
|
||||||
import { Loader2Icon, SendIcon, SquareIcon, XIcon } from 'lucide-react';
|
|
||||||
import type {
|
|
||||||
ComponentProps,
|
|
||||||
HTMLAttributes,
|
|
||||||
KeyboardEventHandler,
|
|
||||||
} from 'react';
|
|
||||||
import { Children } from 'react';
|
|
||||||
|
|
||||||
export type PromptInputProps = HTMLAttributes<HTMLFormElement>;
|
|
||||||
|
|
||||||
export const PromptInput = ({ className, ...props }: PromptInputProps) => (
|
|
||||||
<form
|
|
||||||
className={cn(
|
|
||||||
'w-full divide-y overflow-hidden rounded-xl border bg-background shadow-sm',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type PromptInputTextareaProps = ComponentProps<typeof Textarea> & {
|
|
||||||
minHeight?: number;
|
|
||||||
maxHeight?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const PromptInputTextarea = ({
|
|
||||||
onChange,
|
|
||||||
className,
|
|
||||||
placeholder = 'What would you like to know?',
|
|
||||||
minHeight = 48,
|
|
||||||
maxHeight = 164,
|
|
||||||
...props
|
|
||||||
}: PromptInputTextareaProps) => {
|
|
||||||
const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = (e) => {
|
|
||||||
if (e.key === 'Enter') {
|
|
||||||
// Don't submit if IME composition is in progress
|
|
||||||
if (e.nativeEvent.isComposing) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (e.shiftKey) {
|
|
||||||
// Allow newline
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Submit on Enter (without Shift)
|
|
||||||
e.preventDefault();
|
|
||||||
const form = e.currentTarget.form;
|
|
||||||
if (form) {
|
|
||||||
form.requestSubmit();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Textarea
|
|
||||||
className={cn(
|
|
||||||
'w-full resize-none rounded-none border-none p-3 shadow-none outline-none ring-0',
|
|
||||||
'field-sizing-content max-h-[6lh] bg-transparent dark:bg-transparent',
|
|
||||||
'focus-visible:ring-0',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
name="message"
|
|
||||||
onChange={(e) => {
|
|
||||||
onChange?.(e);
|
|
||||||
}}
|
|
||||||
onKeyDown={handleKeyDown}
|
|
||||||
placeholder={placeholder}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PromptInputToolbarProps = HTMLAttributes<HTMLDivElement>;
|
|
||||||
|
|
||||||
export const PromptInputToolbar = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: PromptInputToolbarProps) => (
|
|
||||||
<div
|
|
||||||
className={cn('flex items-center justify-between p-1', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type PromptInputToolsProps = HTMLAttributes<HTMLDivElement>;
|
|
||||||
|
|
||||||
export const PromptInputTools = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: PromptInputToolsProps) => (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'flex items-center gap-1',
|
|
||||||
'[&_button:first-child]:rounded-bl-xl',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type PromptInputButtonProps = ComponentProps<typeof Button>;
|
|
||||||
|
|
||||||
export const PromptInputButton = ({
|
|
||||||
variant = 'ghost',
|
|
||||||
className,
|
|
||||||
size,
|
|
||||||
...props
|
|
||||||
}: PromptInputButtonProps) => {
|
|
||||||
const newSize =
|
|
||||||
(size ?? Children.count(props.children) > 1) ? 'default' : 'icon';
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
className={cn(
|
|
||||||
'shrink-0 gap-1.5 rounded-lg',
|
|
||||||
variant === 'ghost' && 'text-muted-foreground',
|
|
||||||
newSize === 'default' && 'px-3',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
size={newSize}
|
|
||||||
type="button"
|
|
||||||
variant={variant}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PromptInputSubmitProps = ComponentProps<typeof Button> & {
|
|
||||||
status?: ChatStatus;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const PromptInputSubmit = ({
|
|
||||||
className,
|
|
||||||
variant = 'default',
|
|
||||||
size = 'icon',
|
|
||||||
status,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: PromptInputSubmitProps) => {
|
|
||||||
let Icon = <SendIcon className="size-4" />;
|
|
||||||
|
|
||||||
if (status === 'submitted') {
|
|
||||||
Icon = <Loader2Icon className="size-4 animate-spin" />;
|
|
||||||
} else if (status === 'streaming') {
|
|
||||||
Icon = <SquareIcon className="size-4" />;
|
|
||||||
} else if (status === 'error') {
|
|
||||||
Icon = <XIcon className="size-4" />;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
className={cn('gap-1.5 rounded-lg', className)}
|
|
||||||
size={size}
|
|
||||||
type="submit"
|
|
||||||
variant={variant}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children ?? Icon}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PromptInputModelSelectProps = ComponentProps<typeof Select>;
|
|
||||||
|
|
||||||
export const PromptInputModelSelect = (props: PromptInputModelSelectProps) => (
|
|
||||||
<Select {...props} />
|
|
||||||
);
|
|
||||||
|
|
||||||
export type PromptInputModelSelectTriggerProps = ComponentProps<
|
|
||||||
typeof SelectTrigger
|
|
||||||
>;
|
|
||||||
|
|
||||||
export const PromptInputModelSelectTrigger = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: PromptInputModelSelectTriggerProps) => (
|
|
||||||
<SelectTrigger
|
|
||||||
className={cn(
|
|
||||||
'border-none bg-transparent font-medium text-muted-foreground shadow-none transition-colors',
|
|
||||||
'hover:bg-accent hover:text-foreground [&[aria-expanded="true"]]:bg-accent [&[aria-expanded="true"]]:text-foreground',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type PromptInputModelSelectContentProps = ComponentProps<
|
|
||||||
typeof SelectContent
|
|
||||||
>;
|
|
||||||
|
|
||||||
export const PromptInputModelSelectContent = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: PromptInputModelSelectContentProps) => (
|
|
||||||
<SelectContent className={cn(className)} {...props} />
|
|
||||||
);
|
|
||||||
|
|
||||||
export type PromptInputModelSelectItemProps = ComponentProps<typeof SelectItem>;
|
|
||||||
|
|
||||||
export const PromptInputModelSelectItem = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: PromptInputModelSelectItemProps) => (
|
|
||||||
<SelectItem className={cn(className)} {...props} />
|
|
||||||
);
|
|
||||||
|
|
||||||
export type PromptInputModelSelectValueProps = ComponentProps<
|
|
||||||
typeof SelectValue
|
|
||||||
>;
|
|
||||||
|
|
||||||
export const PromptInputModelSelectValue = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: PromptInputModelSelectValueProps) => (
|
|
||||||
<SelectValue className={cn(className)} {...props} />
|
|
||||||
);
|
|
@ -1,171 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { useControllableState } from '@radix-ui/react-use-controllable-state';
|
|
||||||
import {
|
|
||||||
Collapsible,
|
|
||||||
CollapsibleContent,
|
|
||||||
CollapsibleTrigger,
|
|
||||||
} from '@/components/ui/collapsible';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { BrainIcon, ChevronDownIcon } from 'lucide-react';
|
|
||||||
import type { ComponentProps } from 'react';
|
|
||||||
import { createContext, memo, useContext, useEffect, useState } from 'react';
|
|
||||||
import { Response } from './response';
|
|
||||||
|
|
||||||
type ReasoningContextValue = {
|
|
||||||
isStreaming: boolean;
|
|
||||||
isOpen: boolean;
|
|
||||||
setIsOpen: (open: boolean) => void;
|
|
||||||
duration: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
const ReasoningContext = createContext<ReasoningContextValue | null>(null);
|
|
||||||
|
|
||||||
const useReasoning = () => {
|
|
||||||
const context = useContext(ReasoningContext);
|
|
||||||
if (!context) {
|
|
||||||
throw new Error('Reasoning components must be used within Reasoning');
|
|
||||||
}
|
|
||||||
return context;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ReasoningProps = ComponentProps<typeof Collapsible> & {
|
|
||||||
isStreaming?: boolean;
|
|
||||||
open?: boolean;
|
|
||||||
defaultOpen?: boolean;
|
|
||||||
onOpenChange?: (open: boolean) => void;
|
|
||||||
duration?: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
const AUTO_CLOSE_DELAY = 1000;
|
|
||||||
const MS_IN_S = 1000;
|
|
||||||
|
|
||||||
export const Reasoning = memo(
|
|
||||||
({
|
|
||||||
className,
|
|
||||||
isStreaming = false,
|
|
||||||
open,
|
|
||||||
defaultOpen = true,
|
|
||||||
onOpenChange,
|
|
||||||
duration: durationProp,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: ReasoningProps) => {
|
|
||||||
const [isOpen, setIsOpen] = useControllableState({
|
|
||||||
prop: open,
|
|
||||||
defaultProp: defaultOpen,
|
|
||||||
onChange: onOpenChange,
|
|
||||||
});
|
|
||||||
const [duration, setDuration] = useControllableState({
|
|
||||||
prop: durationProp,
|
|
||||||
defaultProp: 0,
|
|
||||||
});
|
|
||||||
|
|
||||||
const [hasAutoClosedRef, setHasAutoClosedRef] = useState(false);
|
|
||||||
const [startTime, setStartTime] = useState<number | null>(null);
|
|
||||||
|
|
||||||
// Track duration when streaming starts and ends
|
|
||||||
useEffect(() => {
|
|
||||||
if (isStreaming) {
|
|
||||||
if (startTime === null) {
|
|
||||||
setStartTime(Date.now());
|
|
||||||
}
|
|
||||||
} else if (startTime !== null) {
|
|
||||||
setDuration(Math.round((Date.now() - startTime) / MS_IN_S));
|
|
||||||
setStartTime(null);
|
|
||||||
}
|
|
||||||
}, [isStreaming, startTime, setDuration]);
|
|
||||||
|
|
||||||
// Auto-open when streaming starts, auto-close when streaming ends (once only)
|
|
||||||
useEffect(() => {
|
|
||||||
if (defaultOpen && !isStreaming && isOpen && !hasAutoClosedRef) {
|
|
||||||
// Add a small delay before closing to allow user to see the content
|
|
||||||
const timer = setTimeout(() => {
|
|
||||||
setIsOpen(false);
|
|
||||||
setHasAutoClosedRef(true);
|
|
||||||
}, AUTO_CLOSE_DELAY);
|
|
||||||
|
|
||||||
return () => clearTimeout(timer);
|
|
||||||
}
|
|
||||||
}, [isStreaming, isOpen, defaultOpen, setIsOpen, hasAutoClosedRef]);
|
|
||||||
|
|
||||||
const handleOpenChange = (newOpen: boolean) => {
|
|
||||||
setIsOpen(newOpen);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ReasoningContext.Provider
|
|
||||||
value={{ isStreaming, isOpen, setIsOpen, duration }}
|
|
||||||
>
|
|
||||||
<Collapsible
|
|
||||||
className={cn('not-prose mb-4', className)}
|
|
||||||
onOpenChange={handleOpenChange}
|
|
||||||
open={isOpen}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</Collapsible>
|
|
||||||
</ReasoningContext.Provider>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
export type ReasoningTriggerProps = ComponentProps<typeof CollapsibleTrigger>;
|
|
||||||
|
|
||||||
export const ReasoningTrigger = memo(
|
|
||||||
({ className, children, ...props }: ReasoningTriggerProps) => {
|
|
||||||
const { isStreaming, isOpen, duration } = useReasoning();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<CollapsibleTrigger
|
|
||||||
className={cn(
|
|
||||||
'flex items-center gap-2 text-muted-foreground text-sm',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children ?? (
|
|
||||||
<>
|
|
||||||
<BrainIcon className="size-4" />
|
|
||||||
{isStreaming || duration === 0 ? (
|
|
||||||
<p>Thinking...</p>
|
|
||||||
) : (
|
|
||||||
<p>Thought for {duration} seconds</p>
|
|
||||||
)}
|
|
||||||
<ChevronDownIcon
|
|
||||||
className={cn(
|
|
||||||
'size-4 text-muted-foreground transition-transform',
|
|
||||||
isOpen ? 'rotate-180' : 'rotate-0'
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
export type ReasoningContentProps = ComponentProps<
|
|
||||||
typeof CollapsibleContent
|
|
||||||
> & {
|
|
||||||
children: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ReasoningContent = memo(
|
|
||||||
({ className, children, ...props }: ReasoningContentProps) => (
|
|
||||||
<CollapsibleContent
|
|
||||||
className={cn(
|
|
||||||
'mt-4 text-sm',
|
|
||||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<Response className="grid gap-2">{children}</Response>
|
|
||||||
</CollapsibleContent>
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
Reasoning.displayName = 'Reasoning';
|
|
||||||
ReasoningTrigger.displayName = 'ReasoningTrigger';
|
|
||||||
ReasoningContent.displayName = 'ReasoningContent';
|
|
@ -1,22 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { type ComponentProps, memo } from 'react';
|
|
||||||
import { Streamdown } from 'streamdown';
|
|
||||||
|
|
||||||
type ResponseProps = ComponentProps<typeof Streamdown>;
|
|
||||||
|
|
||||||
export const Response = memo(
|
|
||||||
({ className, ...props }: ResponseProps) => (
|
|
||||||
<Streamdown
|
|
||||||
className={cn(
|
|
||||||
'size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
),
|
|
||||||
(prevProps, nextProps) => prevProps.children === nextProps.children
|
|
||||||
);
|
|
||||||
|
|
||||||
Response.displayName = 'Response';
|
|
@ -1,74 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import {
|
|
||||||
Collapsible,
|
|
||||||
CollapsibleContent,
|
|
||||||
CollapsibleTrigger,
|
|
||||||
} from '@/components/ui/collapsible';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { BookIcon, ChevronDownIcon } from 'lucide-react';
|
|
||||||
import type { ComponentProps } from 'react';
|
|
||||||
|
|
||||||
export type SourcesProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const Sources = ({ className, ...props }: SourcesProps) => (
|
|
||||||
<Collapsible
|
|
||||||
className={cn('not-prose mb-4 text-primary text-xs', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type SourcesTriggerProps = ComponentProps<typeof CollapsibleTrigger> & {
|
|
||||||
count: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const SourcesTrigger = ({
|
|
||||||
className,
|
|
||||||
count,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: SourcesTriggerProps) => (
|
|
||||||
<CollapsibleTrigger className="flex items-center gap-2" {...props}>
|
|
||||||
{children ?? (
|
|
||||||
<>
|
|
||||||
<p className="font-medium">Used {count} sources</p>
|
|
||||||
<ChevronDownIcon className="h-4 w-4" />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type SourcesContentProps = ComponentProps<typeof CollapsibleContent>;
|
|
||||||
|
|
||||||
export const SourcesContent = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: SourcesContentProps) => (
|
|
||||||
<CollapsibleContent
|
|
||||||
className={cn(
|
|
||||||
'mt-3 flex w-fit flex-col gap-2',
|
|
||||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type SourceProps = ComponentProps<'a'>;
|
|
||||||
|
|
||||||
export const Source = ({ href, title, children, ...props }: SourceProps) => (
|
|
||||||
<a
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
href={href}
|
|
||||||
rel="noreferrer"
|
|
||||||
target="_blank"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children ?? (
|
|
||||||
<>
|
|
||||||
<BookIcon className="h-4 w-4" />
|
|
||||||
<span className="block font-medium">{title}</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</a>
|
|
||||||
);
|
|
@ -1,74 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import {
|
|
||||||
Collapsible,
|
|
||||||
CollapsibleContent,
|
|
||||||
CollapsibleTrigger,
|
|
||||||
} from '@/components/ui/collapsible';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { BookIcon, ChevronDownIcon } from 'lucide-react';
|
|
||||||
import type { ComponentProps } from 'react';
|
|
||||||
|
|
||||||
export type SourcesProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const Sources = ({ className, ...props }: SourcesProps) => (
|
|
||||||
<Collapsible
|
|
||||||
className={cn('not-prose mb-4 text-primary text-xs', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type SourcesTriggerProps = ComponentProps<typeof CollapsibleTrigger> & {
|
|
||||||
count: number;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const SourcesTrigger = ({
|
|
||||||
className,
|
|
||||||
count,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: SourcesTriggerProps) => (
|
|
||||||
<CollapsibleTrigger className={cn("flex items-center gap-2", className)} {...props}>
|
|
||||||
{children ?? (
|
|
||||||
<>
|
|
||||||
<p className="font-medium">Used {count} sources</p>
|
|
||||||
<ChevronDownIcon className="h-4 w-4" />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type SourcesContentProps = ComponentProps<typeof CollapsibleContent>;
|
|
||||||
|
|
||||||
export const SourcesContent = ({
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: SourcesContentProps) => (
|
|
||||||
<CollapsibleContent
|
|
||||||
className={cn(
|
|
||||||
'mt-3 flex w-fit flex-col gap-2',
|
|
||||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type SourceProps = ComponentProps<'a'>;
|
|
||||||
|
|
||||||
export const Source = ({ href, title, children, ...props }: SourceProps) => (
|
|
||||||
<a
|
|
||||||
className="flex items-center gap-2"
|
|
||||||
href={href}
|
|
||||||
rel="noreferrer"
|
|
||||||
target="_blank"
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children ?? (
|
|
||||||
<>
|
|
||||||
<BookIcon className="h-4 w-4" />
|
|
||||||
<span className="block font-medium">{title}</span>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</a>
|
|
||||||
);
|
|
@ -1,56 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import {
|
|
||||||
ScrollArea,
|
|
||||||
ScrollBar,
|
|
||||||
} from '@/components/ui/scroll-area';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { ComponentProps } from 'react';
|
|
||||||
|
|
||||||
export type SuggestionsProps = ComponentProps<typeof ScrollArea>;
|
|
||||||
|
|
||||||
export const Suggestions = ({
|
|
||||||
className,
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: SuggestionsProps) => (
|
|
||||||
<ScrollArea className="w-full overflow-x-auto whitespace-nowrap" {...props}>
|
|
||||||
<div className={cn('flex w-max flex-nowrap items-center gap-2', className)}>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
<ScrollBar className="hidden" orientation="horizontal" />
|
|
||||||
</ScrollArea>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type SuggestionProps = Omit<ComponentProps<typeof Button>, 'onClick'> & {
|
|
||||||
suggestion: string;
|
|
||||||
onClick?: (suggestion: string) => void;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const Suggestion = ({
|
|
||||||
suggestion,
|
|
||||||
onClick,
|
|
||||||
className,
|
|
||||||
variant = 'outline',
|
|
||||||
size = 'sm',
|
|
||||||
children,
|
|
||||||
...props
|
|
||||||
}: SuggestionProps) => {
|
|
||||||
const handleClick = () => {
|
|
||||||
onClick?.(suggestion);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Button
|
|
||||||
className={cn('cursor-pointer rounded-full px-4', className)}
|
|
||||||
onClick={handleClick}
|
|
||||||
size={size}
|
|
||||||
type="button"
|
|
||||||
variant={variant}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children || suggestion}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
};
|
|
@ -1,94 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import {
|
|
||||||
Collapsible,
|
|
||||||
CollapsibleContent,
|
|
||||||
CollapsibleTrigger,
|
|
||||||
} from '@/components/ui/collapsible';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import { ChevronDownIcon, SearchIcon } from 'lucide-react';
|
|
||||||
import type { ComponentProps } from 'react';
|
|
||||||
|
|
||||||
export type TaskItemFileProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const TaskItemFile = ({
|
|
||||||
children,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: TaskItemFileProps) => (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'inline-flex items-center gap-1 rounded-md border bg-secondary px-1.5 py-0.5 text-foreground text-xs',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type TaskItemProps = ComponentProps<'div'>;
|
|
||||||
|
|
||||||
export const TaskItem = ({ children, className, ...props }: TaskItemProps) => (
|
|
||||||
<div className={cn('text-muted-foreground text-sm', className)} {...props}>
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type TaskProps = ComponentProps<typeof Collapsible>;
|
|
||||||
|
|
||||||
export const Task = ({
|
|
||||||
defaultOpen = true,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: TaskProps) => (
|
|
||||||
<Collapsible
|
|
||||||
className={cn(
|
|
||||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 data-[state=closed]:animate-out data-[state=open]:animate-in',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
defaultOpen={defaultOpen}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type TaskTriggerProps = ComponentProps<typeof CollapsibleTrigger> & {
|
|
||||||
title: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const TaskTrigger = ({
|
|
||||||
children,
|
|
||||||
className,
|
|
||||||
title,
|
|
||||||
...props
|
|
||||||
}: TaskTriggerProps) => (
|
|
||||||
<CollapsibleTrigger asChild className={cn('group', className)} {...props}>
|
|
||||||
{children ?? (
|
|
||||||
<div className="flex cursor-pointer items-center gap-2 text-muted-foreground hover:text-foreground">
|
|
||||||
<SearchIcon className="size-4" />
|
|
||||||
<p className="text-sm">{title}</p>
|
|
||||||
<ChevronDownIcon className="size-4 transition-transform group-data-[state=open]:rotate-180" />
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type TaskContentProps = ComponentProps<typeof CollapsibleContent>;
|
|
||||||
|
|
||||||
export const TaskContent = ({
|
|
||||||
children,
|
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: TaskContentProps) => (
|
|
||||||
<CollapsibleContent
|
|
||||||
className={cn(
|
|
||||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<div className="mt-4 space-y-2 border-muted border-l-2 pl-4">
|
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</CollapsibleContent>
|
|
||||||
);
|
|
@ -1,142 +0,0 @@
|
|||||||
'use client';
|
|
||||||
|
|
||||||
import { Badge } from '@/components/ui/badge';
|
|
||||||
import {
|
|
||||||
Collapsible,
|
|
||||||
CollapsibleContent,
|
|
||||||
CollapsibleTrigger,
|
|
||||||
} from '@/components/ui/collapsible';
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import type { ToolUIPart } from 'ai';
|
|
||||||
import {
|
|
||||||
CheckCircleIcon,
|
|
||||||
ChevronDownIcon,
|
|
||||||
CircleIcon,
|
|
||||||
ClockIcon,
|
|
||||||
WrenchIcon,
|
|
||||||
XCircleIcon,
|
|
||||||
} from 'lucide-react';
|
|
||||||
import type { ComponentProps, ReactNode } from 'react';
|
|
||||||
import { CodeBlock } from './code-block';
|
|
||||||
|
|
||||||
export type ToolProps = ComponentProps<typeof Collapsible>;
|
|
||||||
|
|
||||||
export const Tool = ({ className, ...props }: ToolProps) => (
|
|
||||||
<Collapsible
|
|
||||||
className={cn('not-prose mb-4 w-full rounded-md border', className)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type ToolHeaderProps = {
|
|
||||||
type: ToolUIPart['type'];
|
|
||||||
state: ToolUIPart['state'];
|
|
||||||
className?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
const getStatusBadge = (status: ToolUIPart['state']) => {
|
|
||||||
const labels = {
|
|
||||||
'input-streaming': 'Pending',
|
|
||||||
'input-available': 'Running',
|
|
||||||
'output-available': 'Completed',
|
|
||||||
'output-error': 'Error',
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const icons = {
|
|
||||||
'input-streaming': <CircleIcon className="size-4" />,
|
|
||||||
'input-available': <ClockIcon className="size-4 animate-pulse" />,
|
|
||||||
'output-available': <CheckCircleIcon className="size-4 text-green-600" />,
|
|
||||||
'output-error': <XCircleIcon className="size-4 text-red-600" />,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Badge className="gap-1.5 rounded-full text-xs" variant="secondary">
|
|
||||||
{icons[status]}
|
|
||||||
{labels[status]}
|
|
||||||
</Badge>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ToolHeader = ({
|
|
||||||
className,
|
|
||||||
type,
|
|
||||||
state,
|
|
||||||
...props
|
|
||||||
}: ToolHeaderProps) => (
|
|
||||||
<CollapsibleTrigger
|
|
||||||
className={cn(
|
|
||||||
'flex w-full items-center justify-between gap-4 p-3',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<WrenchIcon className="size-4 text-muted-foreground" />
|
|
||||||
<span className="font-medium text-sm">{type}</span>
|
|
||||||
{getStatusBadge(state)}
|
|
||||||
</div>
|
|
||||||
<ChevronDownIcon className="size-4 text-muted-foreground transition-transform group-data-[state=open]:rotate-180" />
|
|
||||||
</CollapsibleTrigger>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type ToolContentProps = ComponentProps<typeof CollapsibleContent>;
|
|
||||||
|
|
||||||
export const ToolContent = ({ className, ...props }: ToolContentProps) => (
|
|
||||||
<CollapsibleContent
|
|
||||||
className={cn(
|
|
||||||
'data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-popover-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in',
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type ToolInputProps = ComponentProps<'div'> & {
|
|
||||||
input: ToolUIPart['input'];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ToolInput = ({ className, input, ...props }: ToolInputProps) => (
|
|
||||||
<div className={cn('space-y-2 overflow-hidden p-4', className)} {...props}>
|
|
||||||
<h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
|
|
||||||
Parameters
|
|
||||||
</h4>
|
|
||||||
<div className="rounded-md bg-muted/50">
|
|
||||||
<CodeBlock code={JSON.stringify(input, null, 2)} language="json" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
export type ToolOutputProps = ComponentProps<'div'> & {
|
|
||||||
output: ReactNode;
|
|
||||||
errorText: ToolUIPart['errorText'];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const ToolOutput = ({
|
|
||||||
className,
|
|
||||||
output,
|
|
||||||
errorText,
|
|
||||||
...props
|
|
||||||
}: ToolOutputProps) => {
|
|
||||||
if (!(output || errorText)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={cn('space-y-2 p-4', className)} {...props}>
|
|
||||||
<h4 className="font-medium text-muted-foreground text-xs uppercase tracking-wide">
|
|
||||||
{errorText ? 'Error' : 'Result'}
|
|
||||||
</h4>
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
'overflow-x-auto rounded-md text-xs [&_table]:w-full',
|
|
||||||
errorText
|
|
||||||
? 'bg-destructive/10 text-destructive'
|
|
||||||
: 'bg-muted/50 text-foreground'
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{errorText && <div>{errorText}</div>}
|
|
||||||
{output && <div>{output}</div>}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user