mirror of
https://github.com/supabase/supabase.git
synced 2026-10-13 21:29:08 +03:00
fix: merge conflict in ChartHeader
This commit is contained in:
commit
ec7fb258f8
142 files changed
+2828
-3549
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Copy this file in the same folder, rename it to .env.local and fill out the env vars
|
||||
NEXT_PUBLIC_BASE_PATH=/design-system
|
||||
@@ -389,11 +389,6 @@ export const docsConfig: DocsConfig = {
|
||||
href: '/docs/components/textarea',
|
||||
items: [],
|
||||
},
|
||||
{
|
||||
title: 'Toast',
|
||||
href: '/docs/components/toast',
|
||||
items: [],
|
||||
},
|
||||
{
|
||||
title: 'Toggle',
|
||||
href: '/docs/components/toggle',
|
||||
|
||||
@@ -6,9 +6,8 @@
|
||||
"scripts": {
|
||||
"preinstall": "npx only-allow pnpm",
|
||||
"dev": "next dev --turbopack --port 3003",
|
||||
"build": "pnpm run content:build && pnpm run build:registry && pnpm run build:llms && next build",
|
||||
"build": "pnpm run content:build && pnpm run build:registry && next build",
|
||||
"build:registry": "tsx --tsconfig ./tsconfig.scripts.json ./scripts/build-registry.mts && prettier --log-level silent --write \"registry/**/*.{ts,tsx,mdx}\" --cache",
|
||||
"build:llms": "tsx --tsconfig ./tsconfig.scripts.json ./scripts/build-llms-txt.ts",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"content:build": "contentlayer2 build",
|
||||
@@ -18,6 +17,7 @@
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.1.1",
|
||||
"contentlayer2": "0.4.6",
|
||||
"date-fns": "^2.30.0",
|
||||
"eslint-config-supabase": "workspace:*",
|
||||
"icons": "workspace:*",
|
||||
"jotai": "^2.8.0",
|
||||
|
||||
@@ -1,158 +0,0 @@
|
||||
# Supabase Design System
|
||||
Last updated: 2025-04-24T06:00:07.374Z
|
||||
|
||||
## Overview
|
||||
The Design System used in Supabase Studio.
|
||||
|
||||
## Docs
|
||||
- [Changelog](https://supabase-design-system.vercel.app/design-system/docs/changelog)
|
||||
- Latest updates and announcements.
|
||||
- [Color usage](https://supabase-design-system.vercel.app/design-system/docs/color-usage)
|
||||
- Colors system breakdown with best practise
|
||||
- [Accordion](https://supabase-design-system.vercel.app/design-system/docs/components/accordion)
|
||||
- A vertically stacked set of interactive headings that each reveal a section of content.
|
||||
- [Alert](https://supabase-design-system.vercel.app/design-system/docs/components/alert copy)
|
||||
- Displays a callout for user attention.
|
||||
- [Alert Dialog](https://supabase-design-system.vercel.app/design-system/docs/components/alert-dialog)
|
||||
- A modal dialog that interrupts the user with important content and expects a response.
|
||||
- [Alert](https://supabase-design-system.vercel.app/design-system/docs/components/alert)
|
||||
- Displays a callout for user attention.
|
||||
- [Aspect Ratio](https://supabase-design-system.vercel.app/design-system/docs/components/aspect-ratio)
|
||||
- Displays content within a desired ratio.
|
||||
- [Atom components](https://supabase-design-system.vercel.app/design-system/docs/components/atom-components)
|
||||
- [Avatar](https://supabase-design-system.vercel.app/design-system/docs/components/avatar)
|
||||
- An image element with a fallback for representing the user.
|
||||
- [Badge](https://supabase-design-system.vercel.app/design-system/docs/components/badge)
|
||||
- Displays a badge or a component that looks like a badge.
|
||||
- [Breadcrumb](https://supabase-design-system.vercel.app/design-system/docs/components/breadcrumb)
|
||||
- Displays the path to the current resource using a hierarchy of links.
|
||||
- [Button](https://supabase-design-system.vercel.app/design-system/docs/components/button)
|
||||
- Displays a button or a component that looks like a button.
|
||||
- [Calendar](https://supabase-design-system.vercel.app/design-system/docs/components/calendar)
|
||||
- A date field component that allows users to enter and edit date.
|
||||
- [Card](https://supabase-design-system.vercel.app/design-system/docs/components/card)
|
||||
- Displays a card with header, content, and footer.
|
||||
- [Carousel](https://supabase-design-system.vercel.app/design-system/docs/components/carousel)
|
||||
- A carousel with motion and swipe built using Embla.
|
||||
- [Chart](https://supabase-design-system.vercel.app/design-system/docs/components/chart)
|
||||
- Beautiful charts. Built using Recharts. Copy and paste into your apps.
|
||||
- [Checkbox](https://supabase-design-system.vercel.app/design-system/docs/components/checkbox)
|
||||
- A control that allows the user to toggle between checked and not checked.
|
||||
- [Collapsible](https://supabase-design-system.vercel.app/design-system/docs/components/collapsible)
|
||||
- An interactive component which expands/collapses a panel.
|
||||
- [Combobox](https://supabase-design-system.vercel.app/design-system/docs/components/combobox)
|
||||
- Autocomplete input and command palette with a list of suggestions.
|
||||
- [Command](https://supabase-design-system.vercel.app/design-system/docs/components/command)
|
||||
- Fast, composable, unstyled command menu for React.
|
||||
- [Command Menu (cmdk)](https://supabase-design-system.vercel.app/design-system/docs/components/commandmenu)
|
||||
- A central command menu that acts as a control center with searchable actions.
|
||||
- [Context Menu](https://supabase-design-system.vercel.app/design-system/docs/components/context-menu)
|
||||
- Displays a menu to the user — such as a set of actions or functions — triggered by a button.
|
||||
- [Data Table](https://supabase-design-system.vercel.app/design-system/docs/components/data-table)
|
||||
- Powerful table and datagrids built using TanStack Table.
|
||||
- [Date Picker](https://supabase-design-system.vercel.app/design-system/docs/components/date-picker)
|
||||
- A date picker component with range and presets.
|
||||
- [Dialog](https://supabase-design-system.vercel.app/design-system/docs/components/dialog)
|
||||
- A window overlaid on either the primary window or another dialog window, rendering the content underneath inert.
|
||||
- [Drawer](https://supabase-design-system.vercel.app/design-system/docs/components/drawer)
|
||||
- A drawer component for React.
|
||||
- [Dropdown Menu](https://supabase-design-system.vercel.app/design-system/docs/components/dropdown-menu)
|
||||
- Displays a menu to the user — such as a set of actions or functions — triggered by a button.
|
||||
- [Expanding Textarea](https://supabase-design-system.vercel.app/design-system/docs/components/expanding-textarea)
|
||||
- Displays a textarea which autoexpands (or shrinks) based on its content.
|
||||
- [React Hook Form](https://supabase-design-system.vercel.app/design-system/docs/components/form)
|
||||
- Building forms with React Hook Form and Zod.
|
||||
- [Fragment components](https://supabase-design-system.vercel.app/design-system/docs/components/fragment-components)
|
||||
- ''
|
||||
- [Hover Card](https://supabase-design-system.vercel.app/design-system/docs/components/hover-card)
|
||||
- For sighted users to preview content available behind a link.
|
||||
- [Input OTP](https://supabase-design-system.vercel.app/design-system/docs/components/input-otp)
|
||||
- Accessible one-time password component with copy paste functionality.
|
||||
- [Input](https://supabase-design-system.vercel.app/design-system/docs/components/input)
|
||||
- Displays a form input field or a component that looks like an input field.
|
||||
- [Label](https://supabase-design-system.vercel.app/design-system/docs/components/label)
|
||||
- Renders an accessible label associated with controls.
|
||||
- [Menubar](https://supabase-design-system.vercel.app/design-system/docs/components/menubar)
|
||||
- A visually persistent menu common in desktop applications that provides quick access to a consistent set of commands.
|
||||
- [Navigation Menu](https://supabase-design-system.vercel.app/design-system/docs/components/navigation-menu)
|
||||
- A collection of links for navigating websites.
|
||||
- [Pagination](https://supabase-design-system.vercel.app/design-system/docs/components/pagination)
|
||||
- Pagination with page navigation, next and previous links.
|
||||
- [Popover](https://supabase-design-system.vercel.app/design-system/docs/components/popover)
|
||||
- Displays rich content in a portal, triggered by a button.
|
||||
- [Progress](https://supabase-design-system.vercel.app/design-system/docs/components/progress)
|
||||
- Displays an indicator showing the completion progress of a task, typically displayed as a progress bar.
|
||||
- [Radio Group Card](https://supabase-design-system.vercel.app/design-system/docs/components/radio-group-card)
|
||||
- A set of checkable buttons—known as radio buttons—where no more than one of the buttons can be checked at a time.
|
||||
- [Radio Group Stacked](https://supabase-design-system.vercel.app/design-system/docs/components/radio-group-stacked)
|
||||
- A set of checkable buttons—known as radio buttons—where no more than one of the buttons can be checked at a time.
|
||||
- [Radio Group](https://supabase-design-system.vercel.app/design-system/docs/components/radio-group)
|
||||
- A set of checkable buttons—known as radio buttons—where no more than one of the buttons can be checked at a time.
|
||||
- [Resizable](https://supabase-design-system.vercel.app/design-system/docs/components/resizable)
|
||||
- Accessible resizable panel groups and layouts with keyboard support.
|
||||
- [Scroll-area](https://supabase-design-system.vercel.app/design-system/docs/components/scroll-area)
|
||||
- Augments native scroll functionality for custom, cross-browser styling.
|
||||
- [Select](https://supabase-design-system.vercel.app/design-system/docs/components/select)
|
||||
- Displays a list of options for the user to pick from—triggered by a button.
|
||||
- [Separator](https://supabase-design-system.vercel.app/design-system/docs/components/separator)
|
||||
- Visually or semantically separates content.
|
||||
- [Sheet](https://supabase-design-system.vercel.app/design-system/docs/components/sheet)
|
||||
- Extends the Dialog component to display content that complements the main content of the screen.
|
||||
- [Sidebar](https://supabase-design-system.vercel.app/design-system/docs/components/sidebar)
|
||||
- A composable, themeable and customizable sidebar component.
|
||||
- [Skeleton](https://supabase-design-system.vercel.app/design-system/docs/components/skeleton)
|
||||
- Use to show a placeholder while content is loading.
|
||||
- [Slider](https://supabase-design-system.vercel.app/design-system/docs/components/slider)
|
||||
- An input where the user selects a value from within a given range.
|
||||
- [Sonner](https://supabase-design-system.vercel.app/design-system/docs/components/sonner)
|
||||
- An opinionated toast component for React.
|
||||
- [Switch](https://supabase-design-system.vercel.app/design-system/docs/components/switch)
|
||||
- A control that allows the user to toggle between checked and not checked.
|
||||
- [Table](https://supabase-design-system.vercel.app/design-system/docs/components/table)
|
||||
- A responsive table component.
|
||||
- [Tabs](https://supabase-design-system.vercel.app/design-system/docs/components/tabs)
|
||||
- A set of layered sections of content—known as tab panels—that are displayed one at a time.
|
||||
- [Textarea](https://supabase-design-system.vercel.app/design-system/docs/components/textarea)
|
||||
- Displays a form textarea or a component that looks like a textarea.
|
||||
- [Toggle Group](https://supabase-design-system.vercel.app/design-system/docs/components/toggle-group)
|
||||
- A set of two-state buttons that can be toggled on or off.
|
||||
- [Toggle](https://supabase-design-system.vercel.app/design-system/docs/components/toggle)
|
||||
- A two-state button that can be either on or off.
|
||||
- [Tooltip](https://supabase-design-system.vercel.app/design-system/docs/components/tooltip)
|
||||
- A popup that displays information related to an element when the element receives keyboard focus or the mouse hovers over it.
|
||||
- [Tree View](https://supabase-design-system.vercel.app/design-system/docs/components/tree-view)
|
||||
- A tree view that assembles all the functionalities of the Accordion component to create a tree view.
|
||||
- [Typography](https://supabase-design-system.vercel.app/design-system/docs/components/typography)
|
||||
- Styles for headings, paragraphs, lists...etc
|
||||
- [Figma](https://supabase-design-system.vercel.app/design-system/docs/figma)
|
||||
- Every component recreated in Figma. With customizable props, typography and icons.
|
||||
- [Admonition](https://supabase-design-system.vercel.app/design-system/docs/fragments/admonition)
|
||||
- Displays a callout for user attention.
|
||||
- [Assistant Chat](https://supabase-design-system.vercel.app/design-system/docs/fragments/assistant-chat)
|
||||
- Bespoke Assistant chat text area, with support for a commands Popover.
|
||||
- [Filter Bar](https://supabase-design-system.vercel.app/design-system/docs/fragments/filter-bar)
|
||||
- An advanced filtering component with support for multiple conditions and operators.
|
||||
- [Form Item Layout](https://supabase-design-system.vercel.app/design-system/docs/fragments/form-item-layout)
|
||||
- A helper component that provides a layout for form items.
|
||||
- [Info Tooltip](https://supabase-design-system.vercel.app/design-system/docs/fragments/info-tooltip)
|
||||
- InfoTooltip provides a tooltip with an information icon.
|
||||
- [Inner Side Menu](https://supabase-design-system.vercel.app/design-system/docs/fragments/inner-side-menu)
|
||||
- InnerSideMenu is a component that provides a collapsible side menu with multiple sections.
|
||||
- [Logs Bar Chart](https://supabase-design-system.vercel.app/design-system/docs/fragments/logs-bar-chart)
|
||||
- A stacked bar chart that displays logs errors and successes.
|
||||
- [Modal](https://supabase-design-system.vercel.app/design-system/docs/fragments/modal)
|
||||
- A window overlaid on either the primary window or another dialog window, rendering the content underneath inert.
|
||||
- [Multi Select](https://supabase-design-system.vercel.app/design-system/docs/fragments/multi-select)
|
||||
- Multiple selection component.
|
||||
- [Text Confirm Dialog](https://supabase-design-system.vercel.app/design-system/docs/fragments/text-confirm-dialog)
|
||||
- A modal dialog that interrupts the user with important content and expects a response.
|
||||
- [Table of Contents (TOC)](https://supabase-design-system.vercel.app/design-system/docs/fragments/toc)
|
||||
- List of page anchors for the current page.
|
||||
- [Icons](https://supabase-design-system.vercel.app/design-system/docs/icons)
|
||||
- Icons system breakdown. Copy values of Icons.
|
||||
- [Introduction](https://supabase-design-system.vercel.app/design-system/docs/index)
|
||||
- Components and patterns that you can copy and paste into Supabase apps. Accessible. Customizable. Open Source.
|
||||
- [Tailwind Classes](https://supabase-design-system.vercel.app/design-system/docs/tailwind-classes)
|
||||
- Icons system breakdown. Copy values of Icons.
|
||||
- [Themes](https://supabase-design-system.vercel.app/design-system/docs/theming)
|
||||
- Themes used in Supabase
|
||||
@@ -17,7 +17,7 @@ export default function Component() {
|
||||
fill="none"
|
||||
className="absolute left-[5px] top-[50px] z-10"
|
||||
>
|
||||
<g clip-path="url(#a)">
|
||||
<g clipPath="url(#a)">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M173.928 21.13C115.811 44.938 58.751 45.773 0 26.141c4.227-4.386 7.82-2.715 10.567-1.88 21.133 5.64 42.9 6.266 64.457 7.101 31.066 1.253 60.441-5.848 89.183-17.335 1.268-.418 2.325-1.253 4.861-2.924-14.582-2.924-29.165 2.089-41.845-3.76.212-.835.212-1.879.423-2.714 9.51-.627 19.231-1.253 28.742-2.089 9.51-.835 18.808-1.88 28.318-2.506 6.974-.418 9.933 2.924 7.397 9.19-3.17 8.145-7.608 15.664-11.623 23.391-.423.836-1.057 1.88-1.902 2.298-2.325.835-4.65 1.044-7.186 1.67-.422-2.088-1.479-4.386-1.268-6.265.423-2.506 1.902-4.595 3.804-9.19Z"
|
||||
@@ -48,7 +48,7 @@ export default function Component() {
|
||||
viewBox="0 0 122 148"
|
||||
className="absolute left-[85px] top-[10px] z-10 -scale-x-100"
|
||||
>
|
||||
<g clip-path="url(#ab)">
|
||||
<g clipPath="url(#ab)">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M0 2.65c6.15-4.024 12.299-2.753 17.812-.847a115.56 115.56 0 0 1 21.84 10.59C70.4 32.727 88.849 61.744 96.483 97.54c1.908 9.108 2.544 18.639 3.817 29.017 8.481-4.871 12.934-14.402 21.416-19.909 1.061 4.236-1.06 6.989-2.756 9.319-6.998 9.531-14.207 19.062-21.63 28.382-3.604 4.448-6.36 4.871-10.177 1.059-8.058-7.837-12.935-17.368-14.42-28.382 0-.424.636-1.059 1.485-2.118 9.118 2.33 6.997 13.979 14.843 18.215 3.393-14.614.848-28.593-2.969-42.149-4.029-14.19-9.33-27.746-17.812-39.82-8.27-11.86-18.66-21.392-30.11-30.287C26.93 11.758 14.207 6.039 0 2.65Z"
|
||||
@@ -96,7 +96,7 @@ export default function Component() {
|
||||
viewBox="0 0 75 175"
|
||||
className="absolute left-[30px] top-[38px] z-10 rotate-[-40deg]"
|
||||
>
|
||||
<g clip-path="url(#abc)">
|
||||
<g clipPath="url(#abc)">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M20.187 175c-4.439-2.109-7.186-2.531-8.032-4.008-3.17-5.484-6.763-10.968-8.454-17.084-5.073-16.242-4.439-32.694-1.057-49.146 5.707-28.053 18.388-52.942 34.24-76.565 1.692-2.531 3.171-5.063 4.862-7.805 0-.21-.211-.632-.634-1.265-4.65 1.265-9.511 2.53-14.161 3.585-2.537.422-5.496.422-8.032-.421-1.48-.422-3.593-2.742-3.593-4.219 0-1.898 1.48-4.218 2.747-5.906 1.057-1.054 2.96-1.265 4.65-1.687C35.406 7.315 48.088 3.729 60.98.776c10.99-2.53 14.584 1.055 13.95 11.812-.634 11.18-.846 22.358-1.268 33.326-.212 3.375-.846 6.96-1.268 10.757-8.878-4.007-8.878-4.007-12.048-38.177C47.03 33.259 38.153 49.289 29.91 65.741 21.667 82.193 16.17 99.49 13.212 117.84c-2.959 18.984.634 36.912 6.975 57.161Z"
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
import { Minus, Plus } from 'lucide-react'
|
||||
import { Bar, BarChart, ResponsiveContainer } from 'recharts'
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
@@ -104,11 +104,12 @@ export default function NavigationMenuDemo() {
|
||||
</NavigationMenuContent>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<Link href="/docs" legacyBehavior passHref>
|
||||
<NavigationMenuLink className={buttonVariants({ type: 'text', size: 'small' })}>
|
||||
Documentation
|
||||
</NavigationMenuLink>
|
||||
</Link>
|
||||
<NavigationMenuLink
|
||||
href="/docs"
|
||||
className={buttonVariants({ type: 'text', size: 'small' })}
|
||||
>
|
||||
Documentation
|
||||
</NavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
</NavigationMenuList>
|
||||
</NavigationMenu>
|
||||
|
||||
@@ -144,11 +144,12 @@ export default function NavigationMenuDemo() {
|
||||
</NavigationMenuContent>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<Link href="/docs" legacyBehavior passHref>
|
||||
<NavigationMenuLink className={buttonVariants({ type: 'text', size: 'small' })}>
|
||||
Documentation
|
||||
</NavigationMenuLink>
|
||||
</Link>
|
||||
<NavigationMenuLink
|
||||
href="/docs"
|
||||
className={buttonVariants({ type: 'text', size: 'small' })}
|
||||
>
|
||||
Documentation
|
||||
</NavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
</NavigationMenuList>
|
||||
<ScrollBar orientation="horizontal" />
|
||||
|
||||
@@ -8,15 +8,12 @@ const tags = Array.from({ length: 50 }).map((_, i, a) => `v1.2.0-beta.${a.length
|
||||
export default function ScrollAreaDemo() {
|
||||
return (
|
||||
<ScrollArea className="h-72 w-48 rounded-md border">
|
||||
<div className="p-4">
|
||||
<div className="p-4 divide-y divide-border">
|
||||
<h4 className="mb-4 text-sm font-medium leading-none">Tags</h4>
|
||||
{tags.map((tag) => (
|
||||
<>
|
||||
<div key={tag} className="text-sm">
|
||||
{tag}
|
||||
</div>
|
||||
<Separator className="my-2" />
|
||||
</>
|
||||
<div key={tag} className="text-sm py-2">
|
||||
{tag}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
@@ -28,13 +28,13 @@ export default function SheetDemo() {
|
||||
<Label_Shadcn_ htmlFor="name" className="text-right">
|
||||
Name
|
||||
</Label_Shadcn_>
|
||||
<Input_Shadcn_ id="name" value="Pedro Duarte" className="col-span-3" />
|
||||
<Input_Shadcn_ id="name" value="Pedro Duarte" className="col-span-3" readOnly />
|
||||
</div>
|
||||
<div className="grid grid-cols-4 items-center gap-4">
|
||||
<Label_Shadcn_ htmlFor="username" className="text-right">
|
||||
Username
|
||||
</Label_Shadcn_>
|
||||
<Input_Shadcn_ id="username" value="@peduarte" className="col-span-3" />
|
||||
<Input_Shadcn_ id="username" value="@peduarte" className="col-span-3" readOnly />
|
||||
</div>
|
||||
</div>
|
||||
<SheetFooter>
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
import { registry } from '@/registry/registry'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
const BASE_URL = 'https://supabase-design-system.vercel.app/design-system/docs'
|
||||
|
||||
interface DocMeta {
|
||||
title: string
|
||||
description?: string
|
||||
path: string
|
||||
}
|
||||
|
||||
console.log('🤖 Building llms.txt')
|
||||
|
||||
// Function to extract frontmatter from MDX files
|
||||
function extractFrontmatter(content: string): { title?: string; description?: string } {
|
||||
const frontmatterRegex = /---\n([\s\S]*?)\n---/
|
||||
const match = content.match(frontmatterRegex)
|
||||
if (!match) return {}
|
||||
|
||||
const frontmatter = match[1]
|
||||
const titleMatch = frontmatter.match(/title:\s*(.*)/)
|
||||
const descriptionMatch = frontmatter.match(/description:\s*(.*)/)
|
||||
|
||||
return {
|
||||
title: titleMatch?.[1],
|
||||
description: descriptionMatch?.[1],
|
||||
}
|
||||
}
|
||||
|
||||
// Function to recursively get all MDX files
|
||||
function getMdxFiles(dir: string): string[] {
|
||||
const files: string[] = []
|
||||
const entries = fs.readdirSync(dir, { withFileTypes: true })
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) {
|
||||
files.push(...getMdxFiles(fullPath))
|
||||
} else if (entry.name.endsWith('.mdx')) {
|
||||
files.push(fullPath)
|
||||
}
|
||||
}
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
// Function to get all MDX files and their metadata
|
||||
function getDocFiles(): DocMeta[] {
|
||||
const docsDir = path.join(process.cwd(), 'content/docs')
|
||||
const mdxFiles = getMdxFiles(docsDir)
|
||||
|
||||
const docs: DocMeta[] = []
|
||||
|
||||
for (const fullPath of mdxFiles) {
|
||||
const content = fs.readFileSync(fullPath, 'utf-8')
|
||||
const { title, description } = extractFrontmatter(content)
|
||||
|
||||
if (title) {
|
||||
// Get relative path and convert to URL path
|
||||
const relativePath = path.relative(docsDir, fullPath)
|
||||
const urlPath = relativePath
|
||||
.replace(/\.mdx$/, '')
|
||||
.replace(/\/index$/, '')
|
||||
.replace(/\\/g, '/')
|
||||
|
||||
docs.push({
|
||||
title,
|
||||
description,
|
||||
path: urlPath,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return docs
|
||||
}
|
||||
|
||||
// Generate the llms.txt content
|
||||
const docs = getDocFiles()
|
||||
let content = `# Supabase Design System
|
||||
Last updated: ${new Date().toISOString()}
|
||||
|
||||
## Overview
|
||||
The Design System used in Supabase Studio.
|
||||
|
||||
## Docs
|
||||
`
|
||||
|
||||
// Add documentation links
|
||||
for (const doc of docs) {
|
||||
const url = `${BASE_URL}/${doc.path}`
|
||||
content += `- [${doc.title}](${url})`
|
||||
if (doc.description) {
|
||||
content += `\n - ${doc.description}`
|
||||
}
|
||||
content += '\n'
|
||||
}
|
||||
|
||||
// Write the file
|
||||
const publicDir = path.join(process.cwd(), 'public')
|
||||
if (!fs.existsSync(publicDir)) {
|
||||
fs.mkdirSync(publicDir, { recursive: true })
|
||||
}
|
||||
|
||||
fs.writeFileSync(path.join(publicDir, 'llms.txt'), content)
|
||||
console.log('✅ Generated llms.txt in public directory')
|
||||
@@ -20,7 +20,8 @@
|
||||
"paths": {
|
||||
"@/*": ["./*"],
|
||||
"@ui/*": ["./../../packages/ui/src/*"], // handle ui package paths
|
||||
"contentlayer/generated": ["./.contentlayer/generated"]
|
||||
"contentlayer/generated": ["./.contentlayer/generated"],
|
||||
"icons/*": ["./../../packages/icons/*"]
|
||||
},
|
||||
"plugins": [
|
||||
{
|
||||
|
||||
@@ -107,7 +107,7 @@ const BreadcrumbsInternal = ({
|
||||
<DrawerTrigger aria-label="Toggle Menu">
|
||||
<BreadcrumbEllipsis className="h-4 w-4" />
|
||||
</DrawerTrigger>
|
||||
<DrawerContent showHandle={false}>
|
||||
<DrawerContent>
|
||||
<div className="grid gap-1 px-4">
|
||||
{breadcrumbs.slice(1, -2).map((crumb, index) =>
|
||||
crumb.url ? (
|
||||
|
||||
@@ -2193,7 +2193,7 @@ export const platform: NavMenuConstant = {
|
||||
url: '/guides/platform/project-transfer',
|
||||
},
|
||||
{
|
||||
name: 'Duplicate Project',
|
||||
name: 'Restore to a new project',
|
||||
url: '/guides/platform/clone-project',
|
||||
},
|
||||
{
|
||||
|
||||
@@ -165,7 +165,32 @@ supabase --experimental \
|
||||
postgres-config delete --config shared_buffers,work_mem
|
||||
```
|
||||
|
||||
By default, changing the configuration, whether by updating or deleting, causes the database and all associated read replicas to restart. You can use the `--no-restart` flag to prevent this behavior, and attempt to reload the updated configuration without a restart. Refer to the Postgres documentation to determine if a given parameter can be reloaded without a restart.
|
||||
By default, CLI v2 (≥ 2.0.0) checks the parameter’s context and requests the correct action (reload or restart):
|
||||
|
||||
- If the setting can be reloaded (`pg_settings.context = 'sighup'`), then the Management API will detect this and apply the change with a configuration reload.
|
||||
- If the setting requires a restart (`pg_settings.context = 'postmaster'`), then both the primary and any read replicas will restart to apply the change.
|
||||
|
||||
To check whether a parameter can be reloaded without a restart, see the [Postgres docs](https://www.postgresql.org/docs/current/runtime-config.html).
|
||||
|
||||
You can verify whether changes have been applied with the following checks:
|
||||
|
||||
```bash
|
||||
supabase --version;
|
||||
```
|
||||
|
||||
```sql
|
||||
-- Check whether the parameters were updated (and if a restart is pending):
|
||||
select name, setting, context, pending_restart
|
||||
from pg_settings
|
||||
where name in ('max_slot_wal_keep_size', 'shared_buffers', 'max_connections');
|
||||
```
|
||||
|
||||
```sql
|
||||
-- If the timestamp hasn’t changed, no restart occurred
|
||||
select pg_postmaster_start_time();
|
||||
```
|
||||
|
||||
You can also pass the `--no-restart` flag to attempt a reload-only apply. If the parameter cannot be reloaded, the change stays pending until the next restart.
|
||||
|
||||
<Admonition type="note" label="Read Replicas and Custom Config">
|
||||
|
||||
|
||||
@@ -1,9 +1,29 @@
|
||||
---
|
||||
title: Duplicate project
|
||||
title: Restore to a new project
|
||||
subtitle: How to clone your existing Supabase project
|
||||
---
|
||||
|
||||
You can clone your Supabase project by restoring your data from an existing project into a completely new one. Note that this only duplicates your database, not your project configuration.
|
||||
<Admonition type="note" label="Beta Version">
|
||||
|
||||
You can clone your Supabase project by restoring your data from an existing project into a completely new one. This process creates a database-only copy and requires manual reconfiguration to fully replicate your original project.
|
||||
|
||||
</Admonition>
|
||||
|
||||
**What will be transferred?**
|
||||
|
||||
- Database schema (tables, views, procedures)
|
||||
- All data and indexes
|
||||
- Database roles, permissions and users
|
||||
- Auth user data (user accounts, hashed passwords, and authentication records from the auth schema)
|
||||
|
||||
**What needs manual reconfiguration?**
|
||||
|
||||
- Storage objects & settings (Your S3/storage files and bucket configurations are **NOT** copied)
|
||||
- Edge Functions
|
||||
- Auth settings & API keys
|
||||
- Realtime settings
|
||||
- Database extensions and settings
|
||||
- Read replicas
|
||||
|
||||
Whether you're using physical backups or Point-in-Time recovery (PITR), this feature allows you to duplicate project data with ease, perform testing safely, or recover data for analysis. Access to this feature is exclusive to users on paid plans and requires that physical backups are enabled for the source project.
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@ To enforce private channels you need to disable the 'Allow public access' settin
|
||||
|
||||
Realtime uses the `messages` table in your database's `realtime` schema to generate access policies for your clients when they connect to a Channel topic.
|
||||
|
||||
By creating RLS polices on the `realtime.messages` table you can control the access users have to a Channel topic, and features within a Channel topic.
|
||||
By creating RLS policies on the `realtime.messages` table you can control the access users have to a Channel topic, and features within a Channel topic.
|
||||
|
||||
The validation is done when the user connects. When their WebSocket connection is established and a Channel topic is joined, their permissions are calculated based on:
|
||||
|
||||
@@ -373,9 +373,9 @@ When using Postgres Changes with RLS, database records are sent only to clients
|
||||
|
||||
## Updating RLS policies
|
||||
|
||||
Client access polices are cached for the duration of the connection. Your database is not queried for every Channel message.
|
||||
Client access policies are cached for the duration of the connection. Your database is not queried for every Channel message.
|
||||
|
||||
Realtime updates the access policy cache for a client based on your RLS polices when:
|
||||
Realtime updates the access policy cache for a client based on your RLS policies when:
|
||||
|
||||
- A client connects to Realtime and subscribes to a Channel
|
||||
- A new JWT is sent to Realtime from a client via the [`access_token` message](/docs/guides/realtime/protocol#access-token)
|
||||
|
||||
@@ -45,6 +45,7 @@ Eduardo Gurgel
|
||||
Egor Romanov
|
||||
Eleftheria Trivyzaki
|
||||
Emmett Folger
|
||||
Eric Kharitonashvili
|
||||
Etienne Stalmans
|
||||
Fabrizio Fenoglio
|
||||
Felipe Stival
|
||||
@@ -123,6 +124,7 @@ Taryn King
|
||||
Terry Sutton
|
||||
Thomas E
|
||||
Thor Schaeff
|
||||
Timothy Lim
|
||||
Tom Ashley
|
||||
Tom G
|
||||
Tyler Hillery
|
||||
|
||||
@@ -214,10 +214,14 @@ export function useLoadTableEditorStateFromLocalStorageIntoUrl({
|
||||
}
|
||||
|
||||
export const handleCopyCell = (
|
||||
{ column, row }: { column: CalculatedColumn<any, unknown>; row: any },
|
||||
{
|
||||
mode,
|
||||
column,
|
||||
row,
|
||||
}: { mode: 'SELECT' | 'EDIT'; column: CalculatedColumn<any, unknown>; row: any },
|
||||
event: CellKeyboardEvent
|
||||
) => {
|
||||
if (event.code === 'KeyC' && (event.metaKey || event.ctrlKey)) {
|
||||
if (mode === 'SELECT' && event.code === 'KeyC' && (event.metaKey || event.ctrlKey)) {
|
||||
const colKey = column.key
|
||||
const cellValue = row[colKey] ?? ''
|
||||
const value = formatClipboardValue(cellValue)
|
||||
|
||||
@@ -128,9 +128,7 @@ export const Grid = memo(
|
||||
}
|
||||
}
|
||||
|
||||
const removeAllFilters = () => {
|
||||
onApplyFilters([])
|
||||
}
|
||||
const removeAllFilters = () => onApplyFilters([])
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -13,6 +13,11 @@ import { EMPTY_ARR } from 'lib/void'
|
||||
import { basename } from 'path'
|
||||
import { Card, CardContent, CardHeader, CardTitle, cn, Skeleton } from 'ui'
|
||||
|
||||
const EMPTY_FUNCTION_BODY: EdgeFunctionBodyData = {
|
||||
version: 0,
|
||||
files: EMPTY_ARR,
|
||||
}
|
||||
|
||||
interface EdgeFunctionsDiffPanelProps {
|
||||
diffResults: EdgeFunctionsDiffResult
|
||||
currentBranchRef?: string
|
||||
@@ -81,11 +86,11 @@ const FunctionDiff = ({
|
||||
}
|
||||
}, [allFileKeys, activeFileKey])
|
||||
|
||||
const currentFile = currentBody.find(
|
||||
(f: EdgeFunctionBodyData[number]) => fileKey(f.name) === activeFileKey
|
||||
const currentFile = currentBody.files.find(
|
||||
(f: EdgeFunctionBodyData['files'][number]) => fileKey(f.name) === activeFileKey
|
||||
)
|
||||
const mainFile = mainBody.find(
|
||||
(f: EdgeFunctionBodyData[number]) => fileKey(f.name) === activeFileKey
|
||||
const mainFile = mainBody.files.find(
|
||||
(f: EdgeFunctionBodyData['files'][number]) => fileKey(f.name) === activeFileKey
|
||||
)
|
||||
|
||||
const language = useMemo(() => {
|
||||
@@ -189,7 +194,7 @@ const EdgeFunctionsDiffPanel = ({
|
||||
key={slug}
|
||||
functionSlug={slug}
|
||||
currentBody={diffResults.addedBodiesMap[slug]!}
|
||||
mainBody={EMPTY_ARR}
|
||||
mainBody={EMPTY_FUNCTION_BODY}
|
||||
currentBranchRef={currentBranchRef}
|
||||
fileInfos={diffResults.functionFileInfo[slug] || EMPTY_ARR}
|
||||
/>
|
||||
|
||||
+1
-1
@@ -162,7 +162,7 @@ export const CreateNewProjectDialog = ({
|
||||
<FormControl_Shadcn_>
|
||||
<Input
|
||||
id="db-password"
|
||||
label="Database Password"
|
||||
label="Database password"
|
||||
type="password"
|
||||
placeholder="Type in a strong password"
|
||||
value={field.value}
|
||||
|
||||
@@ -401,7 +401,7 @@ const CreateFunction = ({ func, visible, setVisible }: CreateFunctionProps) => {
|
||||
disabled={isCreating || isUpdating}
|
||||
loading={isCreating || isUpdating}
|
||||
>
|
||||
Confirm
|
||||
{isEditing ? 'Save' : 'Create'} function
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</div>
|
||||
|
||||
@@ -293,11 +293,6 @@ export const ReplicationPipelineStatus = () => {
|
||||
<div className="text-sm text-foreground">
|
||||
{statusConfig.description}
|
||||
</div>
|
||||
{'lag' in table.state && (
|
||||
<div className="text-xs text-foreground-light">
|
||||
Lag: {table.state.lag}ms
|
||||
</div>
|
||||
)}
|
||||
{table.state.name === 'error' && (
|
||||
<ErroredTableDetails
|
||||
state={table.state}
|
||||
|
||||
@@ -451,7 +451,7 @@ export const TriggerSheet = ({ selectedTrigger, open, setOpen }: TriggerSheetPro
|
||||
Cancel
|
||||
</Button>
|
||||
<Button form={formId} htmlType="submit" loading={isCreating || isUpdating}>
|
||||
Create trigger
|
||||
{isEditing ? 'Save' : 'Create'} trigger
|
||||
</Button>
|
||||
</SheetFooter>
|
||||
</SheetContent>
|
||||
|
||||
@@ -61,7 +61,7 @@ export const PostgresVersionSelector = ({
|
||||
form,
|
||||
type = 'create',
|
||||
layout = 'horizontal',
|
||||
label = 'Postgres Version',
|
||||
label = 'Postgres version',
|
||||
}: PostgresVersionSelectorProps) => {
|
||||
const { data: project } = useSelectedProjectQuery()
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ export function getAvailableRegions(cloudProvider: CloudProvider): Region {
|
||||
switch (cloudProvider) {
|
||||
case 'AWS':
|
||||
case 'AWS_K8S':
|
||||
case 'AWS_NIMBUS':
|
||||
return AWS_REGIONS
|
||||
case 'FLY':
|
||||
return FLY_REGIONS
|
||||
|
||||
@@ -87,9 +87,14 @@ export const RegionSelector = ({
|
||||
<>
|
||||
<p>Select the region closest to your users for the best performance.</p>
|
||||
{showNonProdFields && (
|
||||
<p className="text-warning">
|
||||
Note: Only US (NV), Frankfurt and SG are supported for local/staging projects
|
||||
</p>
|
||||
<div className="mt-2 text-warning-600">
|
||||
<p>Only these regions are supported for local/staging projects:</p>
|
||||
<ul className="list-disc list-inside mt-1">
|
||||
<li>East US (North Virginia)</li>
|
||||
<li>Central EU (Frankfurt)</li>
|
||||
<li>Southeast Asia (Singapore)</li>
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ export const SecurityOptions = ({
|
||||
control={form.control}
|
||||
render={({ field }) => (
|
||||
<>
|
||||
<FormItemLayout className="mt-6" layout={layout} label="Data API Configuration">
|
||||
<FormItemLayout className="mt-6" layout={layout} label="Data API configuration">
|
||||
<FormControl_Shadcn_>
|
||||
<RadioGroupStacked
|
||||
defaultValue={field.value.toString()}
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
} from 'data/query-insights/insights-metrics-query'
|
||||
import { useInsightsQueriesQuery } from 'data/query-insights/insights-queries-query'
|
||||
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
|
||||
import ComposedChart from 'components/ui/Charts/ComposedChart'
|
||||
import { ComposedChart } from 'components/ui/Charts/ComposedChart'
|
||||
import { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'
|
||||
import dayjs from 'dayjs'
|
||||
import { type InsightsQuery } from 'data/query-insights/insights-queries-query'
|
||||
|
||||
@@ -1,36 +1,13 @@
|
||||
/**
|
||||
* ReportChart
|
||||
*
|
||||
* A wrapper component that uses the useChartData hook to fetch data for a chart
|
||||
* and then passes the data and loading state to the ComposedChartHandler.
|
||||
*
|
||||
* This component acts as a bridge between the data-fetching logic and the
|
||||
* presentational chart component.
|
||||
*/
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useRef, useState } from 'react'
|
||||
|
||||
import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'
|
||||
import LogChartHandler from 'components/ui/Charts/LogChartHandler'
|
||||
import Panel from 'components/ui/Panel'
|
||||
import { useFillTimeseriesSorted } from 'hooks/analytics/useFillTimeseriesSorted'
|
||||
import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'
|
||||
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
|
||||
import { useChartData } from 'hooks/useChartData'
|
||||
import type { UpdateDateRange } from 'pages/project/[ref]/reports/database'
|
||||
import { Button, cn } from 'ui'
|
||||
import { ReportChartUpsell } from './v2/ReportChartUpsell'
|
||||
|
||||
const ReportChart = ({
|
||||
chart,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
updateDateRange,
|
||||
functionIds,
|
||||
isLoading,
|
||||
className,
|
||||
}: {
|
||||
interface ReportChartProps {
|
||||
chart: any
|
||||
startDate: string
|
||||
endDate: string
|
||||
@@ -38,13 +15,28 @@ const ReportChart = ({
|
||||
updateDateRange: UpdateDateRange
|
||||
functionIds?: string[]
|
||||
isLoading?: boolean
|
||||
className?: string
|
||||
}) => {
|
||||
}
|
||||
|
||||
/**
|
||||
* A wrapper component that uses the useChartData hook to fetch data for a chart
|
||||
* and then passes the data and loading state to the ComposedChartHandler.
|
||||
*
|
||||
* This component acts as a bridge between the data-fetching logic and the
|
||||
* presentational chart component.
|
||||
*/
|
||||
export const ReportChart = ({
|
||||
chart,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
updateDateRange,
|
||||
functionIds,
|
||||
isLoading,
|
||||
}: ReportChartProps) => {
|
||||
const { data: org } = useSelectedOrganizationQuery()
|
||||
const { plan: orgPlan } = useCurrentOrgPlan()
|
||||
const orgPlanId = orgPlan?.id
|
||||
|
||||
const [isHoveringUpgrade, setIsHoveringUpgrade] = useState(false)
|
||||
const isAvailable =
|
||||
chart.availableIn === undefined || (orgPlanId && chart.availableIn.includes(orgPlanId))
|
||||
|
||||
@@ -87,77 +79,8 @@ const ReportChart = ({
|
||||
? filledData
|
||||
: chartDataArray
|
||||
|
||||
const getExpDemoChartData = () =>
|
||||
new Array(20).fill(0).map((_, index) => ({
|
||||
period_start: new Date(startDate).getTime() + index * 1000,
|
||||
demo: Math.floor(Math.pow(1.25, index) * 10),
|
||||
max_demo: 1000,
|
||||
}))
|
||||
|
||||
const getDemoChartData = () =>
|
||||
new Array(20).fill(0).map((_, index) => ({
|
||||
period_start: new Date(startDate).getTime() + index * 1000,
|
||||
demo: Math.floor(Math.random() * 10) + 1,
|
||||
max_demo: 1000,
|
||||
}))
|
||||
|
||||
// [Jordi] useRef to prevent re-rendering making the chart change.
|
||||
const demoChartData = useRef(getDemoChartData())
|
||||
const exponentialChartData = useRef(getExpDemoChartData())
|
||||
|
||||
const chartData = isHoveringUpgrade ? exponentialChartData.current : demoChartData.current
|
||||
|
||||
if (!isAvailable && !isLoading) {
|
||||
return (
|
||||
<Panel
|
||||
title={<p className="text-sm">{chart.label}</p>}
|
||||
className={cn('h-[260px] relative', className)}
|
||||
>
|
||||
<div className="z-10 flex flex-col items-center justify-center space-y-2 h-full absolute top-0 left-0 w-full bg-surface-100/70 backdrop-blur-md">
|
||||
<h2>{chart.label}</h2>
|
||||
<p className="text-sm text-foreground-light">
|
||||
This chart is available from{' '}
|
||||
<span className="capitalize">
|
||||
{!!chart.availableIn?.length ? chart.availableIn[0] : 'Pro'}
|
||||
</span>{' '}
|
||||
plan and above
|
||||
</p>
|
||||
<Button
|
||||
asChild
|
||||
type="primary"
|
||||
onMouseEnter={() => setIsHoveringUpgrade(true)}
|
||||
onMouseLeave={() => setIsHoveringUpgrade(false)}
|
||||
>
|
||||
<Link href={`/org/${org?.slug}/billing?panel=subscriptionPlan&source=reports`}>
|
||||
Upgrade to{' '}
|
||||
<span className="capitalize">
|
||||
{!!chart.availableIn?.length ? chart.availableIn[0] : 'Pro'}
|
||||
</span>
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="absolute top-0 left-0 w-full h-full z-0">
|
||||
<LogChartHandler
|
||||
attributes={[
|
||||
{
|
||||
attribute: 'demo',
|
||||
enabled: true,
|
||||
label: 'Demo',
|
||||
provider: 'logs',
|
||||
},
|
||||
]}
|
||||
label={chart.label}
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
interval={interval}
|
||||
data={chartData as any}
|
||||
isLoading={false}
|
||||
highlightedValue={0}
|
||||
updateDateRange={updateDateRange}
|
||||
/>
|
||||
</div>
|
||||
</Panel>
|
||||
)
|
||||
return <ReportChartUpsell report={chart} orgSlug={org?.slug ?? ''} />
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -171,4 +94,3 @@ const ReportChart = ({
|
||||
/>
|
||||
)
|
||||
}
|
||||
export default ReportChart
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { formatTimestamp } from './Reports.utils'
|
||||
import dayjs from 'dayjs'
|
||||
import utc from 'dayjs/plugin/utc'
|
||||
|
||||
dayjs.extend(utc)
|
||||
|
||||
describe('formatTimestamp', () => {
|
||||
it('formats milliseconds timestamp correctly', () => {
|
||||
const timestamp = 1640995200000 // 2022-01-01 00:00:00 UTC in milliseconds
|
||||
const result = formatTimestamp(timestamp, { returnUtc: true })
|
||||
expect(result).toBe('Jan 1, 12:00am')
|
||||
})
|
||||
|
||||
it('formats microseconds timestamp correctly', () => {
|
||||
const timestamp = 1640995200000000 // 2022-01-01 00:00:00 UTC in microseconds
|
||||
const result = formatTimestamp(timestamp, { returnUtc: true })
|
||||
expect(result).toBe('Jan 1, 12:00am')
|
||||
})
|
||||
|
||||
it('formats seconds timestamp correctly', () => {
|
||||
const timestamp = 1640995200 // 2022-01-01 00:00:00 UTC in seconds
|
||||
const result = formatTimestamp(timestamp, { returnUtc: true })
|
||||
expect(result).toBe('Jan 1, 12:00am')
|
||||
})
|
||||
|
||||
it('handles string timestamp input', () => {
|
||||
const timestamp = '1640995200000'
|
||||
const result = formatTimestamp(timestamp, { returnUtc: true })
|
||||
expect(result).toBe('Jan 1, 12:00am')
|
||||
})
|
||||
|
||||
it('handles invalid string timestamp', () => {
|
||||
const timestamp = 'invalid-timestamp'
|
||||
const result = formatTimestamp(timestamp, { returnUtc: true })
|
||||
expect(result).toBe('Invalid Date')
|
||||
})
|
||||
|
||||
it('handles zero timestamp', () => {
|
||||
const timestamp = 0
|
||||
const result = formatTimestamp(timestamp, { returnUtc: true })
|
||||
expect(result).toBe('Jan 1, 12:00am')
|
||||
})
|
||||
})
|
||||
@@ -1,3 +1,5 @@
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
import useDbQuery, { DbQueryHook } from 'hooks/analytics/useDbQuery'
|
||||
import useLogsQuery, { LogsQueryHook } from 'hooks/analytics/useLogsQuery'
|
||||
import type { BaseQueries, PresetConfig, ReportQuery } from './Reports.types'
|
||||
@@ -9,10 +11,13 @@ export const queryParamsToObject = (params: string) => {
|
||||
return Object.fromEntries(new URLSearchParams(params))
|
||||
}
|
||||
|
||||
// generate hooks based on preset config
|
||||
export type PresetHookResult = LogsQueryHook | DbQueryHook
|
||||
type PresetHooks = Record<keyof PresetConfig['queries'], () => PresetHookResult>
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* Queries are hooks, avoid generating hooks dynamically
|
||||
* Generate fetch functions instead, and pass it to a hook inside the component
|
||||
*/
|
||||
export const queriesFactory = <T extends string>(
|
||||
queries: BaseQueries<T>,
|
||||
projectRef: string
|
||||
@@ -35,3 +40,36 @@ export const queriesFactory = <T extends string>(
|
||||
)
|
||||
return hooks
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a timestamp to a human readable format in UTC
|
||||
*
|
||||
* @param timestamp - The timestamp to format
|
||||
* @param returnUtc - Whether to return the timestamp in UTC
|
||||
* @param format - The format to use for the timestamp
|
||||
* @returns The formatted timestamp string
|
||||
*/
|
||||
export const formatTimestamp = (
|
||||
timestamp: number | string,
|
||||
{ returnUtc = false, format = 'MMM D, h:mma' }: { returnUtc?: boolean; format?: string } = {}
|
||||
) => {
|
||||
try {
|
||||
const isSeconds = String(timestamp).length === 10
|
||||
const isMicroseconds = String(timestamp).length === 16
|
||||
|
||||
const timestampInMs = isSeconds
|
||||
? Number(timestamp) * 1000
|
||||
: isMicroseconds
|
||||
? Number(timestamp) / 1000
|
||||
: Number(timestamp)
|
||||
|
||||
if (returnUtc) {
|
||||
return dayjs.utc(timestampInMs).format(format)
|
||||
} else {
|
||||
return dayjs(timestampInMs).format(format)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error)
|
||||
return 'Invalid Date'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import Link from 'next/link'
|
||||
import { useRef, useState } from 'react'
|
||||
|
||||
import { LogChartHandler } from 'components/ui/Charts/LogChartHandler'
|
||||
import { ReportConfig } from 'data/reports/v2/reports.types'
|
||||
import { Button, Card, cn } from 'ui'
|
||||
|
||||
export function ReportChartUpsell({ report, orgSlug }: { report: ReportConfig; orgSlug: string }) {
|
||||
const [isHoveringUpgrade, setIsHoveringUpgrade] = useState(false)
|
||||
|
||||
const startDate = '2025-01-01'
|
||||
const endDate = '2025-01-02'
|
||||
|
||||
const getExpDemoChartData = () =>
|
||||
new Array(20).fill(0).map((_, index) => ({
|
||||
period_start: new Date(startDate).getTime() + index * 1000,
|
||||
demo: Math.floor(Math.pow(1.25, index) * 10),
|
||||
max_demo: 1000,
|
||||
}))
|
||||
|
||||
const getDemoChartData = () =>
|
||||
new Array(20).fill(0).map((_, index) => ({
|
||||
period_start: new Date(startDate).getTime() + index * 1000,
|
||||
demo: Math.floor(Math.random() * 10) + 1,
|
||||
max_demo: 1000,
|
||||
}))
|
||||
|
||||
const demoChartData = useRef(getDemoChartData())
|
||||
const exponentialChartData = useRef(getExpDemoChartData())
|
||||
|
||||
const demoData = isHoveringUpgrade ? exponentialChartData.current : demoChartData.current
|
||||
|
||||
return (
|
||||
<Card className={cn('h-[260px] relative')}>
|
||||
<div className="z-10 flex flex-col items-center justify-center space-y-2 h-full absolute top-0 left-0 w-full bg-surface-100/70 backdrop-blur-md">
|
||||
<h2 className="text-sm">{report.label}</h2>
|
||||
<p className="text-sm text-foreground-light">
|
||||
This chart is available from{' '}
|
||||
<span className="capitalize">
|
||||
{!!report.availableIn?.length ? report.availableIn[0] : 'Pro'}
|
||||
</span>{' '}
|
||||
plan and above
|
||||
</p>
|
||||
<Button
|
||||
asChild
|
||||
type="primary"
|
||||
onMouseEnter={() => setIsHoveringUpgrade(true)}
|
||||
onMouseLeave={() => setIsHoveringUpgrade(false)}
|
||||
className="mt-4"
|
||||
>
|
||||
<Link href={`/org/${orgSlug}/billing?panel=subscriptionPlan&source=reports`}>
|
||||
Upgrade to{' '}
|
||||
<span className="capitalize">
|
||||
{!!report.availableIn?.length ? report.availableIn[0] : 'Pro'}
|
||||
</span>
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="absolute top-0 left-0 w-full h-full z-0">
|
||||
<LogChartHandler
|
||||
attributes={[
|
||||
{
|
||||
attribute: 'demo',
|
||||
enabled: true,
|
||||
label: 'Demo',
|
||||
provider: 'logs',
|
||||
},
|
||||
]}
|
||||
label={''}
|
||||
startDate={startDate}
|
||||
endDate={endDate}
|
||||
interval={'1d'}
|
||||
data={demoData as any}
|
||||
isLoading={false}
|
||||
highlightedValue={0}
|
||||
updateDateRange={() => {}}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
|
||||
import { ComposedChart } from 'components/ui/Charts/ComposedChart'
|
||||
import type { AnalyticsInterval } from 'data/analytics/constants'
|
||||
import type { ReportConfig } from 'data/reports/v2/reports.types'
|
||||
import { useFillTimeseriesSorted } from 'hooks/analytics/useFillTimeseriesSorted'
|
||||
import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'
|
||||
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
|
||||
import { Card, CardContent, cn } from 'ui'
|
||||
import { ReportChartUpsell } from './ReportChartUpsell'
|
||||
|
||||
export interface ReportChartV2Props {
|
||||
report: ReportConfig
|
||||
projectRef: string
|
||||
startDate: string
|
||||
endDate: string
|
||||
interval: AnalyticsInterval
|
||||
updateDateRange: (from: string, to: string) => void
|
||||
functionIds?: string[]
|
||||
edgeFnIdToName?: (id: string) => string | undefined
|
||||
className?: string
|
||||
syncId?: string
|
||||
}
|
||||
|
||||
export const ReportChartV2 = ({
|
||||
report,
|
||||
projectRef,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
updateDateRange,
|
||||
functionIds,
|
||||
edgeFnIdToName,
|
||||
className,
|
||||
syncId,
|
||||
}: ReportChartV2Props) => {
|
||||
const { data: org } = useSelectedOrganizationQuery()
|
||||
const { plan: orgPlan } = useCurrentOrgPlan()
|
||||
const orgPlanId = orgPlan?.id
|
||||
|
||||
const isAvailable =
|
||||
report.availableIn === undefined || (orgPlanId && report.availableIn.includes(orgPlanId))
|
||||
|
||||
const canFetch = orgPlanId !== undefined
|
||||
|
||||
const {
|
||||
data: queryResult,
|
||||
isLoading: isLoadingChart,
|
||||
error,
|
||||
} = useQuery(
|
||||
['projects', projectRef, 'report-v2', report.id, { startDate, endDate, interval, functionIds }],
|
||||
async () => {
|
||||
return await report.dataProvider(
|
||||
projectRef,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
functionIds,
|
||||
edgeFnIdToName
|
||||
)
|
||||
},
|
||||
{
|
||||
enabled: Boolean(projectRef && canFetch && isAvailable),
|
||||
refetchOnWindowFocus: false,
|
||||
}
|
||||
)
|
||||
|
||||
const chartData = queryResult?.data || []
|
||||
const dynamicAttributes = queryResult?.attributes || []
|
||||
|
||||
const { data: filledChartData, isError: isFillError } = useFillTimeseriesSorted(
|
||||
chartData,
|
||||
'timestamp',
|
||||
(dynamicAttributes as any[]).map((attr: any) => attr.attribute),
|
||||
0,
|
||||
startDate,
|
||||
endDate,
|
||||
undefined,
|
||||
interval
|
||||
)
|
||||
|
||||
const finalChartData =
|
||||
filledChartData && filledChartData.length > 0 && !isFillError ? filledChartData : chartData
|
||||
|
||||
const [chartStyle, setChartStyle] = useState<string>(report.defaultChartStyle)
|
||||
|
||||
if (!isAvailable && !isLoadingChart) {
|
||||
return <ReportChartUpsell report={report} orgSlug={org?.slug ?? ''} />
|
||||
}
|
||||
|
||||
const isErrorState = error && !isLoadingChart
|
||||
const showEmptyState = (!finalChartData || finalChartData.length === 0) && !isLoadingChart
|
||||
|
||||
return (
|
||||
<Card id={report.id} className={cn('relative w-full overflow-hidden scroll-mt-16', className)}>
|
||||
<CardContent className="flex flex-col gap-4 min-h-[280px] items-center justify-center">
|
||||
{isLoadingChart ? (
|
||||
<Loader2 className="size-5 animate-spin text-foreground-light" />
|
||||
) : showEmptyState ? (
|
||||
<p className="text-sm text-foreground-light text-center h-full flex items-center justify-center">
|
||||
No data available for the selected time range
|
||||
</p>
|
||||
) : isErrorState ? (
|
||||
<p className="text-sm text-foreground-light text-center h-full flex items-center justify-center">
|
||||
Error loading chart data
|
||||
</p>
|
||||
) : (
|
||||
<div className="w-full">
|
||||
<ComposedChart
|
||||
attributes={dynamicAttributes}
|
||||
data={finalChartData}
|
||||
format={report.format ?? undefined}
|
||||
xAxisKey={report.xAxisKey ?? 'timestamp'}
|
||||
yAxisKey={report.yAxisKey ?? dynamicAttributes[0]?.attribute}
|
||||
highlightedValue={0}
|
||||
title={report.label}
|
||||
customDateFormat={undefined}
|
||||
chartHighlight={undefined}
|
||||
chartStyle={chartStyle}
|
||||
showTooltip={report.showTooltip}
|
||||
showLegend={report.showLegend}
|
||||
showTotal={false}
|
||||
showMaxValue={report.showMaxValue}
|
||||
onChartStyleChange={setChartStyle}
|
||||
updateDateRange={updateDateRange}
|
||||
valuePrecision={report.valuePrecision}
|
||||
hideChartType={report.hideChartType}
|
||||
titleTooltip={report.titleTooltip}
|
||||
syncId={syncId}
|
||||
sql={queryResult?.query}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -676,7 +676,7 @@ export const SQLEditor = () => {
|
||||
direction="vertical"
|
||||
autoSaveId={LOCAL_STORAGE_KEYS.SQL_EDITOR_SPLIT_SIZE}
|
||||
>
|
||||
<ResizablePanel maxSize={70}>
|
||||
<ResizablePanel defaultSize={50} maxSize={70}>
|
||||
<div className="flex-grow overflow-y-auto border-b h-full">
|
||||
{isLoading ? (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
@@ -793,7 +793,7 @@ export const SQLEditor = () => {
|
||||
|
||||
<ResizableHandle withHandle />
|
||||
|
||||
<ResizablePanel maxSize={70}>
|
||||
<ResizablePanel defaultSize={50} maxSize={70}>
|
||||
{isLoading ? (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<Loader2 className="animate-spin text-brand" />
|
||||
@@ -811,7 +811,7 @@ export const SQLEditor = () => {
|
||||
)}
|
||||
</ResizablePanel>
|
||||
|
||||
<div className="max-h-9">
|
||||
<div className="h-9">
|
||||
{results?.rows !== undefined && !isExecuting && (
|
||||
<GridFooter className="flex items-center justify-between gap-2">
|
||||
<Tooltip>
|
||||
|
||||
@@ -78,7 +78,7 @@ const UtilityActions = ({
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
data-testId="sql-editor-utility-actions"
|
||||
data-testid="sql-editor-utility-actions"
|
||||
type="default"
|
||||
className={cn('px-1', isAiOpen ? 'block 2xl:hidden' : 'hidden')}
|
||||
icon={<MoreVertical className="text-foreground-light" />}
|
||||
|
||||
@@ -15,7 +15,7 @@ import type { Filters, LogData, LogsEndpointParams } from './Logs.types'
|
||||
* Convert a micro timestamp from number/string to iso timestamp
|
||||
*/
|
||||
export const unixMicroToIsoTimestamp = (unix: string | number): string => {
|
||||
return dayjs.unix(Number(unix) / 1000 / 1000).toISOString()
|
||||
return dayjs.utc(Number(unix) / 1000).toISOString()
|
||||
}
|
||||
|
||||
export const isUnixMicro = (unix: string | number): boolean => {
|
||||
@@ -483,19 +483,22 @@ export const fillTimeseries = (
|
||||
// If we have more points than minPointsToFill, just normalize timestamps and return
|
||||
if (timeseriesData.length > minPointsToFill) {
|
||||
return timeseriesData.map((datum) => {
|
||||
const iso = dayjs.utc(datum[timestampKey]).toISOString()
|
||||
const timestamp = datum[timestampKey]
|
||||
const iso = isUnixMicro(timestamp)
|
||||
? unixMicroToIsoTimestamp(timestamp)
|
||||
: dayjs.utc(timestamp).toISOString()
|
||||
datum[timestampKey] = iso
|
||||
return datum
|
||||
})
|
||||
}
|
||||
|
||||
if (timeseriesData.length <= 1 && !(min || max)) return timeseriesData
|
||||
if (timeseriesData.length <= 1 && !(min && max)) return timeseriesData
|
||||
const dates: unknown[] = timeseriesData.map((datum) => dayjs.utc(datum[timestampKey]))
|
||||
|
||||
const maxDate = max ? dayjs.utc(max) : dayjs.utc(Math.max.apply(null, dates as number[]))
|
||||
const minDate = min ? dayjs.utc(min) : dayjs.utc(Math.min.apply(null, dates as number[]))
|
||||
|
||||
// const truncationSample = timeseriesData.length > 0 ? timeseriesData[0][timestampKey] : min || max
|
||||
// When no data exists but min/max are provided, we need to determine truncation from the time range
|
||||
const truncationSamples = timeseriesData.length > 0 ? dates : [minDate, maxDate]
|
||||
let truncation: 'second' | 'minute' | 'hour' | 'day'
|
||||
let step = 1
|
||||
@@ -515,11 +518,21 @@ export const fillTimeseries = (
|
||||
truncation = getTimestampTruncation(truncationSamples as Dayjs[])
|
||||
}
|
||||
|
||||
// If no data exists and no interval specified, default to minute precision
|
||||
if (timeseriesData.length === 0 && !interval) {
|
||||
truncation = 'minute'
|
||||
}
|
||||
|
||||
const newData = timeseriesData.map((datum) => {
|
||||
const timestamp = datum[timestampKey]
|
||||
const iso = isUnixMicro(timestamp)
|
||||
? unixMicroToIsoTimestamp(timestamp)
|
||||
: dayjs.utc(timestamp).toISOString()
|
||||
|
||||
if (Array.isArray(valueKey) && valueKey.length === 0) {
|
||||
return { [timestampKey]: iso }
|
||||
}
|
||||
|
||||
datum[timestampKey] = iso
|
||||
return datum
|
||||
})
|
||||
@@ -533,7 +546,8 @@ export const fillTimeseries = (
|
||||
d_date.month() === currentDate.month() &&
|
||||
d_date.date() === currentDate.date() &&
|
||||
d_date.hour() === currentDate.hour() &&
|
||||
d_date.minute() === currentDate.minute()
|
||||
d_date.minute() === currentDate.minute() &&
|
||||
d_date.second() === currentDate.second()
|
||||
)
|
||||
})
|
||||
if (!found) {
|
||||
|
||||
@@ -56,22 +56,23 @@ const EdgeFunctionDetailsLayout = ({
|
||||
isError,
|
||||
} = useEdgeFunctionQuery({ projectRef: ref, slug: functionSlug })
|
||||
|
||||
const { data: functionFiles = [], error: filesError } = useEdgeFunctionBodyQuery(
|
||||
{
|
||||
projectRef: ref,
|
||||
slug: functionSlug,
|
||||
},
|
||||
{
|
||||
retry: false,
|
||||
retryOnMount: true,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: Infinity,
|
||||
refetchOnMount: false,
|
||||
refetchOnReconnect: false,
|
||||
refetchInterval: false,
|
||||
refetchIntervalInBackground: false,
|
||||
}
|
||||
)
|
||||
const { data: functionBody = { version: 0, files: [] }, error: filesError } =
|
||||
useEdgeFunctionBodyQuery(
|
||||
{
|
||||
projectRef: ref,
|
||||
slug: functionSlug,
|
||||
},
|
||||
{
|
||||
retry: false,
|
||||
retryOnMount: true,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: Infinity,
|
||||
refetchOnMount: false,
|
||||
refetchOnReconnect: false,
|
||||
refetchInterval: false,
|
||||
refetchIntervalInBackground: false,
|
||||
}
|
||||
)
|
||||
|
||||
const name = selectedFunction?.name || ''
|
||||
|
||||
@@ -112,7 +113,7 @@ const EdgeFunctionDetailsLayout = ({
|
||||
|
||||
const zipFileWriter = new BlobWriter('application/zip')
|
||||
const zipWriter = new ZipWriter(zipFileWriter, { bufferedWrite: true })
|
||||
functionFiles.forEach((file) => {
|
||||
functionBody.files.forEach((file) => {
|
||||
const nameSections = file.name.split('/')
|
||||
const slugIndex = nameSections.indexOf(functionSlug ?? '')
|
||||
const fileName = nameSections.slice(slugIndex + 1).join('/')
|
||||
|
||||
@@ -105,6 +105,9 @@ export function LogsSidebarMenuV2() {
|
||||
},
|
||||
{
|
||||
enabled: enablePgReplicate,
|
||||
retry: false,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ export const SQLEditorMenu = () => {
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
data-testId="sql-editor-new-query-button"
|
||||
data-testid="sql-editor-new-query-button"
|
||||
type="default"
|
||||
icon={<Plus className="text-foreground" />}
|
||||
className="w-[26px]"
|
||||
|
||||
@@ -53,7 +53,11 @@ export const SearchList = ({ search }: SearchListProps) => {
|
||||
)
|
||||
const totalNumber = (count as unknown as { count: number })?.count ?? 0
|
||||
|
||||
const snippets = useMemo(() => data?.pages.flatMap((page) => page.content), [data?.pages])
|
||||
const snippets = useMemo(
|
||||
// [Joshen] Set folder_id to null to ensure flat list
|
||||
() => data?.pages.flatMap((page) => page.content.map((x) => ({ ...x, folder_id: null }))),
|
||||
[data?.pages]
|
||||
)
|
||||
const treeState = formatFolderResponseForTreeView({ folders: [], contents: snippets as any })
|
||||
|
||||
const snippetsLastItemIds = useMemo(() => getLastItemIds(treeState), [treeState])
|
||||
@@ -117,6 +121,7 @@ export const SearchList = ({ search }: SearchListProps) => {
|
||||
</span>
|
||||
),
|
||||
}}
|
||||
isBranch={false}
|
||||
isOpened={isOpened && !isPreview}
|
||||
isSelected={isActive}
|
||||
isPreview={isPreview}
|
||||
|
||||
@@ -50,7 +50,7 @@ export function useTableEditorTabsCleanUp() {
|
||||
// e.g Using the SQL editor to rename the entity
|
||||
const openTabs = openTabsRef.current
|
||||
.map((id) => tabMapRef.current[id])
|
||||
.filter((tab) => editorEntityTypes['table']?.includes(tab.type))
|
||||
.filter((tab) => !!tab && editorEntityTypes['table']?.includes(tab.type))
|
||||
|
||||
openTabs.forEach((tab) => {
|
||||
const entity = entities?.find((x) => tab.metadata?.tableId === x.id)
|
||||
@@ -97,7 +97,7 @@ export function useSqlEditorTabsCleanup() {
|
||||
// e.g for a shared snippet, the owner could've updated the name of the snippet
|
||||
const openSqlTabs = openTabsRef.current
|
||||
.map((id) => tabMapRef.current[id])
|
||||
.filter((tab) => editorEntityTypes['sql']?.includes(tab.type))
|
||||
.filter((tab) => !!tab && editorEntityTypes['sql']?.includes(tab.type))
|
||||
|
||||
openSqlTabs.forEach((tab) => {
|
||||
const snippet = snippets?.find((x) => tab.metadata?.sqlId === x.id)
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Area, AreaChart as RechartAreaChart, Tooltip, XAxis } from 'recharts'
|
||||
import { useChartHoverState } from './useChartHoverState'
|
||||
|
||||
import { CHART_COLORS, DateTimeFormats } from 'components/ui/Charts/Charts.constants'
|
||||
import ChartHeader from './ChartHeader'
|
||||
import { ChartHeader } from './ChartHeader'
|
||||
import type { CommonChartProps, Datum } from './Charts.types'
|
||||
import { numberFormatter, useChartSize } from './Charts.utils'
|
||||
import NoDataPlaceholder from './NoDataPlaceholder'
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import dayjs from 'dayjs'
|
||||
import { ComponentProps, useState, useMemo } from 'react'
|
||||
import { useChartHoverState } from './useChartHoverState'
|
||||
import { ComponentProps, useMemo, useState } from 'react'
|
||||
import {
|
||||
Bar,
|
||||
CartesianGrid,
|
||||
@@ -14,10 +13,11 @@ import {
|
||||
|
||||
import { CHART_COLORS, DateTimeFormats } from 'components/ui/Charts/Charts.constants'
|
||||
import type { CategoricalChartState } from 'recharts/types/chart/types'
|
||||
import ChartHeader from './ChartHeader'
|
||||
import { ChartHeader } from './ChartHeader'
|
||||
import type { CommonChartProps, Datum } from './Charts.types'
|
||||
import { numberFormatter, useChartSize } from './Charts.utils'
|
||||
import NoDataPlaceholder from './NoDataPlaceholder'
|
||||
import { useChartHoverState } from './useChartHoverState'
|
||||
|
||||
export interface BarChartProps<D = Datum> extends CommonChartProps<D> {
|
||||
yAxisKey: string
|
||||
@@ -57,10 +57,9 @@ const BarChart = ({
|
||||
showGrid = false,
|
||||
syncId,
|
||||
}: BarChartProps) => {
|
||||
const { hoveredIndex, isHovered, isCurrentChart, setHover, clearHover } =
|
||||
useChartHoverState('default')
|
||||
const { Container } = useChartSize(size)
|
||||
const { hoveredIndex, syncTooltip, setHover, clearHover } = useChartHoverState(
|
||||
syncId || 'default'
|
||||
)
|
||||
const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
|
||||
|
||||
// Transform data to ensure yAxisKey values are numbers
|
||||
@@ -177,7 +176,7 @@ const BarChart = ({
|
||||
/>
|
||||
<Tooltip
|
||||
content={(props) =>
|
||||
syncId && syncTooltip && hoveredIndex !== null ? (
|
||||
syncId && isHovered && isCurrentChart && hoveredIndex !== null ? (
|
||||
<div className="bg-black/90 text-white p-2 rounded text-xs">
|
||||
<div className="font-medium">
|
||||
{dayjs(data[hoveredIndex]?.[xAxisKey]).format(customDateFormat)}
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import { Button, Tooltip, TooltipContent, TooltipTrigger, cn } from 'ui'
|
||||
import { Activity, BarChartIcon, GitCommitHorizontalIcon, InfoIcon } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useEffect, useState } from 'react'
|
||||
import dayjs from 'dayjs'
|
||||
import {
|
||||
Activity,
|
||||
BarChartIcon,
|
||||
GitCommitHorizontalIcon,
|
||||
InfoIcon,
|
||||
SquareTerminal,
|
||||
} from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { useRouter } from 'next/router'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { cn } from 'ui'
|
||||
import { useParams } from 'common'
|
||||
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
|
||||
import { formatBytes } from 'lib/helpers'
|
||||
import { useChartHoverState } from './useChartHoverState'
|
||||
import { numberFormatter } from './Charts.utils'
|
||||
import { useChartHoverState } from './useChartHoverState'
|
||||
|
||||
export interface ChartHeaderProps {
|
||||
title?: string
|
||||
@@ -33,9 +42,10 @@ export interface ChartHeaderProps {
|
||||
shouldFormatBytes?: boolean
|
||||
isNetworkChart?: boolean
|
||||
attributes?: any[]
|
||||
sql?: string
|
||||
}
|
||||
|
||||
const ChartHeader = ({
|
||||
export const ChartHeader = ({
|
||||
format,
|
||||
highlightedValue,
|
||||
highlightedLabel,
|
||||
@@ -61,16 +71,25 @@ const ChartHeader = ({
|
||||
shouldFormatBytes = false,
|
||||
isNetworkChart = false,
|
||||
attributes,
|
||||
sql,
|
||||
}: ChartHeaderProps) => {
|
||||
const { hoveredIndex, syncHover } = useChartHoverState(syncId || 'default')
|
||||
const { hoveredIndex, isHovered, isCurrentChart, setHover, clearHover } = useChartHoverState(
|
||||
syncId || 'default'
|
||||
)
|
||||
const [localHighlightedValue, setLocalHighlightedValue] = useState(highlightedValue)
|
||||
const [localHighlightedLabel, setLocalHighlightedLabel] = useState(highlightedLabel)
|
||||
const { ref } = useParams()
|
||||
const router = useRouter()
|
||||
|
||||
const formatHighlightedValue = (value: any) => {
|
||||
if (typeof value !== 'number') {
|
||||
return value
|
||||
}
|
||||
|
||||
if (typeof format === 'function') {
|
||||
return format(value)
|
||||
}
|
||||
|
||||
if (shouldFormatBytes) {
|
||||
const bytesValue = isNetworkChart ? Math.abs(value) : value
|
||||
return formatBytes(bytesValue, valuePrecision)
|
||||
@@ -80,7 +99,7 @@ const ChartHeader = ({
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (syncId && hoveredIndex !== null && syncHover && data && xAxisKey && yAxisKey) {
|
||||
if (syncId && hoveredIndex !== null && isHovered && data && xAxisKey && yAxisKey) {
|
||||
const activeDataPoint = data[hoveredIndex]
|
||||
if (activeDataPoint) {
|
||||
// For stacked charts, we need to calculate the total of all attributes
|
||||
@@ -132,7 +151,7 @@ const ChartHeader = ({
|
||||
}
|
||||
}, [
|
||||
hoveredIndex,
|
||||
syncHover,
|
||||
isHovered,
|
||||
syncId,
|
||||
data,
|
||||
xAxisKey,
|
||||
@@ -151,20 +170,21 @@ const ChartHeader = ({
|
||||
{title}
|
||||
</h3>
|
||||
{docsUrl && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Link
|
||||
href={docsUrl}
|
||||
target="_blank"
|
||||
className="text-foreground-lighter hover:text-foreground-light"
|
||||
>
|
||||
<InfoIcon className="w-3 h-3" />
|
||||
</Link>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center">
|
||||
Read docs
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<ButtonTooltip
|
||||
type="text"
|
||||
className="px-1"
|
||||
asChild
|
||||
tooltip={{
|
||||
content: {
|
||||
side: 'top',
|
||||
text: 'Read docs',
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Link href={docsUrl} target="_blank">
|
||||
<InfoIcon className="w-4 h-4 text-foreground-lighter" />
|
||||
</Link>
|
||||
</ButtonTooltip>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
@@ -174,10 +194,6 @@ const ChartHeader = ({
|
||||
className={`text-foreground text-xl font-normal ${minimalHeader ? 'text-base' : 'text-2xl'}`}
|
||||
>
|
||||
{localHighlightedValue !== undefined && formatHighlightedValue(localHighlightedValue)}
|
||||
{format === 'seconds' ? ' ' : ''}
|
||||
<span className="text-lg">
|
||||
{typeof format === 'function' ? format(localHighlightedValue) : format}
|
||||
</span>
|
||||
</h4>
|
||||
)
|
||||
const label = <h4 className="text-foreground-lighter text-xs">{localHighlightedLabel}</h4>
|
||||
@@ -214,43 +230,57 @@ const ChartHeader = ({
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{sql ? (
|
||||
<ButtonTooltip
|
||||
type="default"
|
||||
className="px-1.5"
|
||||
asChild
|
||||
tooltip={{
|
||||
content: {
|
||||
side: 'top',
|
||||
text: 'Open in Log Explorer',
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Link href={`/project/${ref}/logs/explorer?q=${encodeURIComponent(sql)}`}>
|
||||
<SquareTerminal className="w-4 h-4 text-foreground-lighter" />
|
||||
</Link>
|
||||
</ButtonTooltip>
|
||||
) : null}
|
||||
|
||||
{!hideChartType && onChartStyleChange && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="default"
|
||||
className="px-1.5"
|
||||
icon={chartStyle === 'bar' ? <Activity /> : <BarChartIcon />}
|
||||
onClick={() => onChartStyleChange(chartStyle === 'bar' ? 'line' : 'bar')}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center">
|
||||
View as {chartStyle === 'bar' ? 'line chart' : 'bar chart'}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<ButtonTooltip
|
||||
type="default"
|
||||
className="px-1.5"
|
||||
icon={chartStyle === 'bar' ? <Activity /> : <BarChartIcon />}
|
||||
onClick={() => onChartStyleChange(chartStyle === 'bar' ? 'line' : 'bar')}
|
||||
tooltip={{
|
||||
content: {
|
||||
side: 'top',
|
||||
text: `View as ${chartStyle === 'bar' ? 'line chart' : 'bar chart'}`,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{setShowMaxValue && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type={showMaxValue ? 'default' : 'dashed'}
|
||||
className="px-1.5"
|
||||
icon={
|
||||
<GitCommitHorizontalIcon
|
||||
className={showMaxValue ? 'text-foreground-light' : 'text-foreground-lighter'}
|
||||
/>
|
||||
}
|
||||
onClick={() => setShowMaxValue(!showMaxValue)}
|
||||
<ButtonTooltip
|
||||
type={showMaxValue ? 'default' : 'dashed'}
|
||||
className="px-1.5"
|
||||
icon={
|
||||
<GitCommitHorizontalIcon
|
||||
className={showMaxValue ? 'text-foreground-light' : 'text-foreground-lighter'}
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" align="center">
|
||||
{showMaxValue ? 'Hide' : 'Show'} limit
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
}
|
||||
onClick={() => setShowMaxValue(!showMaxValue)}
|
||||
tooltip={{
|
||||
content: {
|
||||
side: 'top',
|
||||
text: `${showMaxValue ? 'Hide' : 'Show'} limit`,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default ChartHeader
|
||||
@@ -1,13 +1,10 @@
|
||||
import dayjs from 'dayjs'
|
||||
import utc from 'dayjs/plugin/utc'
|
||||
import { FC, PropsWithChildren, useMemo } from 'react'
|
||||
import { ResponsiveContainer } from 'recharts'
|
||||
|
||||
import { DateTimeFormats } from './Charts.constants'
|
||||
import type { CommonChartProps, StackedChartProps } from './Charts.types'
|
||||
|
||||
dayjs.extend(utc)
|
||||
|
||||
/**
|
||||
* Auto formats a number to a default precision if it is a float
|
||||
*
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
'use client'
|
||||
|
||||
import dayjs from 'dayjs'
|
||||
import { formatBytes } from 'lib/helpers'
|
||||
import { useTheme } from 'next-themes'
|
||||
import { ComponentProps, useEffect, useState } from 'react'
|
||||
import { useChartHoverState } from './useChartHoverState'
|
||||
import {
|
||||
Area,
|
||||
Bar,
|
||||
@@ -18,9 +15,10 @@ import {
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from 'recharts'
|
||||
|
||||
import { CategoricalChartState } from 'recharts/types/chart/types'
|
||||
import { cn } from 'ui'
|
||||
import ChartHeader from './ChartHeader'
|
||||
import { ChartHeader } from './ChartHeader'
|
||||
import ChartHighlightActions from './ChartHighlightActions'
|
||||
import {
|
||||
CHART_COLORS,
|
||||
@@ -38,6 +36,7 @@ import {
|
||||
} from './ComposedChart.utils'
|
||||
import NoDataPlaceholder from './NoDataPlaceholder'
|
||||
import { ChartHighlight } from './useChartHighlight'
|
||||
import { useChartHoverState } from './useChartHoverState'
|
||||
|
||||
export interface ComposedChartProps<D = Datum> extends CommonChartProps<D> {
|
||||
attributes: MultiAttribute[]
|
||||
@@ -66,9 +65,10 @@ export interface ComposedChartProps<D = Datum> extends CommonChartProps<D> {
|
||||
hideHighlightArea?: boolean
|
||||
syncId?: string
|
||||
docsUrl?: string
|
||||
sql?: string
|
||||
}
|
||||
|
||||
export default function ComposedChart({
|
||||
export function ComposedChart({
|
||||
data,
|
||||
attributes,
|
||||
yAxisKey,
|
||||
@@ -104,6 +104,7 @@ export default function ComposedChart({
|
||||
hideHighlightArea = false,
|
||||
syncId,
|
||||
docsUrl,
|
||||
sql,
|
||||
}: ComposedChartProps) {
|
||||
const { resolvedTheme } = useTheme()
|
||||
const { hoveredIndex, syncTooltip, setHover, clearHover } = useChartHoverState(
|
||||
@@ -331,6 +332,7 @@ export default function ComposedChart({
|
||||
shouldFormatBytes={shouldFormatBytes}
|
||||
isNetworkChart={isNetworkChart}
|
||||
attributes={attributes}
|
||||
sql={sql}
|
||||
/>
|
||||
<Container className="relative z-10">
|
||||
<RechartComposedChart
|
||||
|
||||
@@ -37,7 +37,7 @@ export type Provider = 'infra-monitoring' | 'daily-stats' | 'mock' | 'reference-
|
||||
|
||||
export type MultiAttribute = {
|
||||
attribute: string
|
||||
provider: Provider
|
||||
provider?: Provider
|
||||
label?: string
|
||||
color?: {
|
||||
light: string
|
||||
|
||||
@@ -4,7 +4,7 @@ import React, { PropsWithChildren, useEffect, useMemo, useRef, useState } from '
|
||||
import { cn, WarningIcon } from 'ui'
|
||||
|
||||
import Panel from 'components/ui/Panel'
|
||||
import ComposedChart from './ComposedChart'
|
||||
import { ComposedChart } from './ComposedChart'
|
||||
|
||||
import { AnalyticsInterval, DataPoint } from 'data/analytics/constants'
|
||||
import { useInfraMonitoringQueries } from 'data/analytics/infra-monitoring-queries'
|
||||
@@ -353,7 +353,7 @@ const useAttributeQueries = (
|
||||
return [...infraQueries, ...dailyStatsQueries, ...referenceLineQueries]
|
||||
}
|
||||
|
||||
export default function LazyComposedChartHandler(props: ComposedChartHandlerProps) {
|
||||
export function LazyComposedChartHandler(props: ComposedChartHandlerProps) {
|
||||
if (props.hide) return null
|
||||
|
||||
return (
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Loader2 } from 'lucide-react'
|
||||
import { cn, WarningIcon } from 'ui'
|
||||
|
||||
import Panel from 'components/ui/Panel'
|
||||
import ComposedChart from './ComposedChart'
|
||||
import { ComposedChart } from './ComposedChart'
|
||||
|
||||
import { AnalyticsInterval, DataPoint } from 'data/analytics/constants'
|
||||
import { InfraMonitoringAttribute } from 'data/analytics/infra-monitoring-query'
|
||||
@@ -40,6 +40,7 @@ interface LogChartHandlerProps {
|
||||
isVisible?: boolean
|
||||
titleTooltip?: string
|
||||
docsUrl?: string
|
||||
syncId?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -87,7 +88,7 @@ const LazyChartWrapper = ({ children }: PropsWithChildren) => {
|
||||
*
|
||||
* Provided data must be in the expected chart format.
|
||||
*/
|
||||
const LogChartHandler = ({
|
||||
export const LogChartHandler = ({
|
||||
label,
|
||||
attributes,
|
||||
customDateFormat,
|
||||
@@ -107,6 +108,7 @@ const LogChartHandler = ({
|
||||
valuePrecision,
|
||||
titleTooltip,
|
||||
id,
|
||||
syncId,
|
||||
...otherProps
|
||||
}: PropsWithChildren<LogChartHandlerProps>) => {
|
||||
const [chartStyle, setChartStyle] = useState<string>(defaultChartStyle)
|
||||
@@ -143,7 +145,7 @@ const LogChartHandler = ({
|
||||
data={data as any}
|
||||
format={format}
|
||||
xAxisKey="period_start"
|
||||
yAxisKey={attributes[0].attribute}
|
||||
yAxisKey={attributes[0]?.attribute}
|
||||
highlightedValue={highlightedValue}
|
||||
title={label}
|
||||
customDateFormat={customDateFormat}
|
||||
@@ -158,6 +160,7 @@ const LogChartHandler = ({
|
||||
valuePrecision={valuePrecision}
|
||||
hideChartType={hideChartType}
|
||||
titleTooltip={titleTooltip}
|
||||
syncId={syncId}
|
||||
{...otherProps}
|
||||
/>
|
||||
</Panel.Content>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { BarChart2 } from 'lucide-react'
|
||||
|
||||
import { cn } from 'ui'
|
||||
import ChartHeader from './ChartHeader'
|
||||
import { ChartHeader } from './ChartHeader'
|
||||
import { useChartSize } from './Charts.utils'
|
||||
|
||||
interface NoDataPlaceholderProps {
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import dayjs from 'dayjs'
|
||||
import { useState } from 'react'
|
||||
import { Bar, BarChart, Cell, Legend, Tooltip, XAxis } from 'recharts'
|
||||
import dayjs from 'dayjs'
|
||||
import utc from 'dayjs/plugin/utc'
|
||||
import { useChartHoverState } from './useChartHoverState'
|
||||
import ChartHeader from './ChartHeader'
|
||||
|
||||
import { ChartHeader } from './ChartHeader'
|
||||
import {
|
||||
CHART_COLORS,
|
||||
DateTimeFormats,
|
||||
@@ -20,7 +19,7 @@ import {
|
||||
useStacked,
|
||||
} from './Charts.utils'
|
||||
import NoDataPlaceholder from './NoDataPlaceholder'
|
||||
dayjs.extend(utc)
|
||||
import { useChartHoverState } from './useChartHoverState'
|
||||
|
||||
interface Props extends CommonChartProps<any> {
|
||||
xAxisKey: string
|
||||
|
||||
@@ -15,6 +15,9 @@ interface PanelProps {
|
||||
titleClasses?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use Card component from ui package instead
|
||||
*/
|
||||
function Panel(props: PropsWithChildren<PanelProps>) {
|
||||
const content = (
|
||||
<div
|
||||
|
||||
@@ -44,6 +44,7 @@ const PasswordStrengthBar = ({
|
||||
>
|
||||
Generate a password
|
||||
</span>
|
||||
.
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -15,6 +15,7 @@ export type EdgeFunctionFile = {
|
||||
}
|
||||
|
||||
export type EdgeFunctionBodyResponse = {
|
||||
version: number
|
||||
files: EdgeFunctionFile[]
|
||||
}
|
||||
|
||||
@@ -51,11 +52,14 @@ export async function getEdgeFunctionBody(
|
||||
)
|
||||
}
|
||||
|
||||
const { files } = await parseResponse.json()
|
||||
return files as EdgeFunctionFile[]
|
||||
const response = (await parseResponse.json()) as EdgeFunctionBodyResponse
|
||||
return response
|
||||
} catch (error) {
|
||||
handleError(error)
|
||||
return []
|
||||
return {
|
||||
version: 0,
|
||||
files: [],
|
||||
} as EdgeFunctionBodyResponse
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { organizationKeys } from './keys'
|
||||
|
||||
export type OrganizationAvailableRegionsVariables = {
|
||||
slug?: string
|
||||
cloudProvider: 'AWS' | 'FLY' | 'AWS_K8S'
|
||||
cloudProvider: 'AWS' | 'FLY' | 'AWS_K8S' | 'AWS_NIMBUS'
|
||||
}
|
||||
|
||||
export async function getOrganizationAvailableRegions(
|
||||
|
||||
@@ -31,7 +31,12 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '2-core',
|
||||
priceHourly: 0.01344,
|
||||
priceMonthly: 10,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.FLY.id],
|
||||
cloud_providers: [
|
||||
PROVIDERS.AWS.id,
|
||||
PROVIDERS.AWS_K8S.id,
|
||||
PROVIDERS.AWS_NIMBUS.id,
|
||||
PROVIDERS.FLY.id,
|
||||
],
|
||||
},
|
||||
small: {
|
||||
label: 'Small',
|
||||
@@ -39,7 +44,12 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '2-core',
|
||||
priceHourly: 0.0206,
|
||||
priceMonthly: 15,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.FLY.id],
|
||||
cloud_providers: [
|
||||
PROVIDERS.AWS.id,
|
||||
PROVIDERS.AWS_K8S.id,
|
||||
PROVIDERS.AWS_NIMBUS.id,
|
||||
PROVIDERS.FLY.id,
|
||||
],
|
||||
},
|
||||
medium: {
|
||||
label: 'Medium',
|
||||
@@ -47,7 +57,12 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '2-core',
|
||||
priceHourly: 0.0822,
|
||||
priceMonthly: 60,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.FLY.id],
|
||||
cloud_providers: [
|
||||
PROVIDERS.AWS.id,
|
||||
PROVIDERS.AWS_K8S.id,
|
||||
PROVIDERS.AWS_NIMBUS.id,
|
||||
PROVIDERS.FLY.id,
|
||||
],
|
||||
},
|
||||
large: {
|
||||
label: 'Large',
|
||||
@@ -55,7 +70,12 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '2-core',
|
||||
priceHourly: 0.1517,
|
||||
priceMonthly: 110,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.FLY.id],
|
||||
cloud_providers: [
|
||||
PROVIDERS.AWS.id,
|
||||
PROVIDERS.AWS_K8S.id,
|
||||
PROVIDERS.AWS_NIMBUS.id,
|
||||
PROVIDERS.FLY.id,
|
||||
],
|
||||
},
|
||||
xlarge: {
|
||||
label: 'XL',
|
||||
@@ -63,7 +83,12 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '4-core',
|
||||
priceHourly: 0.2877,
|
||||
priceMonthly: 210,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.FLY.id],
|
||||
cloud_providers: [
|
||||
PROVIDERS.AWS.id,
|
||||
PROVIDERS.AWS_K8S.id,
|
||||
PROVIDERS.AWS_NIMBUS.id,
|
||||
PROVIDERS.FLY.id,
|
||||
],
|
||||
},
|
||||
'2xlarge': {
|
||||
label: '2XL',
|
||||
@@ -71,7 +96,12 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '8-core',
|
||||
priceHourly: 0.562,
|
||||
priceMonthly: 410,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.FLY.id],
|
||||
cloud_providers: [
|
||||
PROVIDERS.AWS.id,
|
||||
PROVIDERS.AWS_K8S.id,
|
||||
PROVIDERS.AWS_NIMBUS.id,
|
||||
PROVIDERS.FLY.id,
|
||||
],
|
||||
},
|
||||
'4xlarge': {
|
||||
label: '4XL',
|
||||
@@ -79,7 +109,12 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '16-core',
|
||||
priceHourly: 1.32,
|
||||
priceMonthly: 960,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.FLY.id],
|
||||
cloud_providers: [
|
||||
PROVIDERS.AWS.id,
|
||||
PROVIDERS.AWS_K8S.id,
|
||||
PROVIDERS.AWS_NIMBUS.id,
|
||||
PROVIDERS.FLY.id,
|
||||
],
|
||||
},
|
||||
'8xlarge': {
|
||||
label: '8XL',
|
||||
@@ -87,7 +122,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '32-core',
|
||||
priceHourly: 2.562,
|
||||
priceMonthly: 1870,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'12xlarge': {
|
||||
label: '12XL',
|
||||
@@ -95,7 +130,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '48-core',
|
||||
priceHourly: 3.836,
|
||||
priceMonthly: 2800,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'16xlarge': {
|
||||
label: '16XL',
|
||||
@@ -103,7 +138,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '64-core',
|
||||
priceHourly: 5.12,
|
||||
priceMonthly: 3730,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'24xlarge': {
|
||||
label: '24XL',
|
||||
@@ -111,7 +146,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '96-core',
|
||||
priceHourly: 9.73,
|
||||
priceMonthly: 7100,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'24xlarge_optimized_cpu': {
|
||||
label: '24XL - Optimized CPU',
|
||||
@@ -119,7 +154,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '96-core',
|
||||
priceHourly: 8.9,
|
||||
priceMonthly: 6500,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'24xlarge_optimized_memory': {
|
||||
label: '24XL - Optimized Memory',
|
||||
@@ -127,7 +162,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '96-core',
|
||||
priceHourly: 13.84,
|
||||
priceMonthly: 10100,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'24xlarge_high_memory': {
|
||||
label: '24XL - High Memory',
|
||||
@@ -135,7 +170,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '96-core',
|
||||
priceHourly: 21.91,
|
||||
priceMonthly: 16000,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'48xlarge': {
|
||||
label: '48XL',
|
||||
@@ -143,7 +178,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '192-core',
|
||||
priceHourly: 19.47,
|
||||
priceMonthly: 14200,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'48xlarge_optimized_cpu': {
|
||||
label: '48XL - Optimized CPU',
|
||||
@@ -151,7 +186,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '192-core',
|
||||
priceHourly: 17.8,
|
||||
priceMonthly: 13000,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'48xlarge_optimized_memory': {
|
||||
label: '48XL - Optimized Memory',
|
||||
@@ -159,7 +194,7 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '192-core',
|
||||
priceHourly: 27.68,
|
||||
priceMonthly: 20200,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
'48xlarge_high_memory': {
|
||||
label: '48XL - High Memory',
|
||||
@@ -167,6 +202,6 @@ export const instanceSizeSpecs: Record<
|
||||
cpu: '192-core',
|
||||
priceHourly: 43.84,
|
||||
priceMonthly: 32000,
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id],
|
||||
cloud_providers: [PROVIDERS.AWS.id, PROVIDERS.AWS_K8S.id, PROVIDERS.AWS_NIMBUS.id],
|
||||
},
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { ReportAttributes } from 'components/ui/Charts/ComposedChart.utils'
|
||||
|
||||
export const getEdgeFunctionReportAttributes = (): ReportAttributes[] => [
|
||||
{
|
||||
id: 'execution-status-codes',
|
||||
label: 'Edge Function Status Codes',
|
||||
valuePrecision: 0,
|
||||
hide: false,
|
||||
showTooltip: true,
|
||||
showLegend: true,
|
||||
showMaxValue: false,
|
||||
hideChartType: false,
|
||||
defaultChartStyle: 'bar',
|
||||
titleTooltip: 'The total number of edge function executions by status code.',
|
||||
availableIn: ['free', 'pro', 'team', 'enterprise'],
|
||||
attributes: [
|
||||
{
|
||||
attribute: 'ExecutionStatusCodes',
|
||||
provider: 'logs',
|
||||
label: 'Execution Status Codes',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'execution-time',
|
||||
label: 'Edge Function Execution Time',
|
||||
valuePrecision: 0,
|
||||
hide: false,
|
||||
showTooltip: true,
|
||||
showLegend: true,
|
||||
showMaxValue: false,
|
||||
hideChartType: false,
|
||||
defaultChartStyle: 'line',
|
||||
titleTooltip: 'Average execution time for edge functions.',
|
||||
availableIn: ['free', 'pro', 'team', 'enterprise'],
|
||||
format: 'ms',
|
||||
YAxisProps: {
|
||||
width: 50,
|
||||
tickFormatter: (value: number) => `${value}ms`,
|
||||
},
|
||||
attributes: [
|
||||
{
|
||||
attribute: 'ExecutionTime',
|
||||
label: 'Avg. Execution Time (ms)',
|
||||
provider: 'logs',
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'invocations-by-region',
|
||||
label: 'Edge Function Invocations by Region',
|
||||
valuePrecision: 0,
|
||||
hide: false,
|
||||
showTooltip: true,
|
||||
showLegend: true,
|
||||
showMaxValue: false,
|
||||
hideChartType: false,
|
||||
defaultChartStyle: 'bar',
|
||||
titleTooltip: 'The total number of edge function invocations by region.',
|
||||
availableIn: ['pro', 'team', 'enterprise'],
|
||||
attributes: [
|
||||
{
|
||||
attribute: 'InvocationsByRegion',
|
||||
provider: 'logs',
|
||||
label: 'Invocations by Region',
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
@@ -1,415 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { get } from 'data/fetchers'
|
||||
import { AnalyticsInterval } from 'data/analytics/constants'
|
||||
import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'
|
||||
import { getHttpStatusCodeInfo } from 'lib/http-status-codes'
|
||||
import { analyticsIntervalToGranularity, useEdgeFnIdToName } from './report.utils'
|
||||
import { REPORT_STATUS_CODE_COLORS } from './report.utils'
|
||||
|
||||
/**
|
||||
* METRICS
|
||||
* Each chart in the UI has a corresponding metric key.
|
||||
*/
|
||||
|
||||
const METRIC_KEYS = [
|
||||
'TotalInvocations',
|
||||
'ExecutionStatusCodes',
|
||||
'InvocationsByRegion',
|
||||
'ExecutionTime',
|
||||
]
|
||||
|
||||
type MetricKey = (typeof METRIC_KEYS)[number]
|
||||
|
||||
/**
|
||||
* SQL
|
||||
* Each metric has a corresponding SQL query.
|
||||
*/
|
||||
|
||||
const METRIC_SQL: Record<
|
||||
MetricKey,
|
||||
(interval: AnalyticsInterval, functionIds?: string[]) => string
|
||||
> = {
|
||||
TotalInvocations: (interval, functionIds) => {
|
||||
return `
|
||||
--edgefn-report-invocations
|
||||
select
|
||||
timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,
|
||||
function_id,
|
||||
count(*) as count
|
||||
from
|
||||
function_edge_logs
|
||||
CROSS JOIN UNNEST(metadata) AS m
|
||||
CROSS JOIN UNNEST(m.request) AS request
|
||||
CROSS JOIN UNNEST(m.response) AS response
|
||||
${
|
||||
functionIds && functionIds.length > 0
|
||||
? `WHERE function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
|
||||
: ''
|
||||
}
|
||||
group by
|
||||
timestamp,
|
||||
function_id
|
||||
order by
|
||||
timestamp desc;
|
||||
|
||||
`
|
||||
},
|
||||
ExecutionStatusCodes: (interval, functionIds) => {
|
||||
return `
|
||||
--edgefn-report-execution-status-codes
|
||||
select
|
||||
timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,
|
||||
response.status_code AS status_code,
|
||||
COUNT(*) AS count
|
||||
FROM
|
||||
function_edge_logs
|
||||
CROSS JOIN UNNEST(metadata) AS m
|
||||
CROSS JOIN UNNEST(m.response) AS response
|
||||
CROSS JOIN UNNEST(m.request) AS request
|
||||
${
|
||||
functionIds && functionIds.length > 0
|
||||
? `WHERE function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
|
||||
: ''
|
||||
}
|
||||
group by
|
||||
timestamp,
|
||||
status_code
|
||||
order by
|
||||
timestamp desc;
|
||||
`
|
||||
},
|
||||
InvocationsByRegion: (interval, functionIds) => {
|
||||
const granularity = analyticsIntervalToGranularity(interval)
|
||||
return `
|
||||
--edgefn-report-invocations-by-region
|
||||
select
|
||||
timestamp_trunc(timestamp, ${granularity}) as timestamp,
|
||||
h.x_sb_edge_region as region,
|
||||
count(*) as count
|
||||
from
|
||||
function_edge_logs
|
||||
cross join unnest(metadata) as m
|
||||
cross join unnest(m.response) as r
|
||||
cross join unnest(r.headers) as h
|
||||
where h.x_sb_edge_region is not null
|
||||
${
|
||||
functionIds && functionIds.length > 0
|
||||
? `and function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
|
||||
: ''
|
||||
}
|
||||
group by
|
||||
timestamp,
|
||||
region
|
||||
order by
|
||||
timestamp desc
|
||||
`
|
||||
},
|
||||
ExecutionTime: (interval, functionIds) => {
|
||||
const granularity = analyticsIntervalToGranularity(interval)
|
||||
const hasFunctions = functionIds && functionIds.length > 0
|
||||
return `
|
||||
--edgefn-report-execution-time
|
||||
select
|
||||
timestamp_trunc(timestamp, ${granularity}) as timestamp,
|
||||
${hasFunctions ? 'function_id,' : ''}
|
||||
avg(m.execution_time_ms) as avg_execution_time
|
||||
from
|
||||
function_edge_logs
|
||||
cross join unnest(metadata) as m
|
||||
cross join unnest(m.request) as request
|
||||
${hasFunctions ? `where function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})` : ''}
|
||||
group by
|
||||
timestamp
|
||||
${hasFunctions ? ', function_id' : ''}
|
||||
order by
|
||||
timestamp desc
|
||||
`
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* FORMATTERS.
|
||||
* Metrics need to be formatted before being passed on to the UI charts.
|
||||
*/
|
||||
|
||||
function defaultFormatter(rawData: any, attributes: MultiAttribute[]) {
|
||||
const chartAttributes = attributes
|
||||
if (!rawData) return { data: undefined, chartAttributes }
|
||||
const result = rawData.result || []
|
||||
const timestamps = new Set<string>(result.map((p: any) => p.timestamp))
|
||||
const data = Array.from(timestamps)
|
||||
.sort()
|
||||
.map((timestamp) => {
|
||||
const point: any = { period_start: timestamp }
|
||||
chartAttributes.forEach((attr) => {
|
||||
point[attr.attribute] = 0
|
||||
})
|
||||
const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)
|
||||
matchingPoints.forEach((p: any) => {
|
||||
point[attributes[0].attribute] = p.count
|
||||
})
|
||||
return point
|
||||
})
|
||||
return { data, chartAttributes }
|
||||
}
|
||||
|
||||
const METRIC_FORMATTER: Record<
|
||||
MetricKey,
|
||||
(
|
||||
rawData: any,
|
||||
attributes: MultiAttribute[],
|
||||
logsMetric: string,
|
||||
functionIds?: string[],
|
||||
edgeFnIdToName?: (id: string) => string | undefined
|
||||
) => { data: any; chartAttributes: any }
|
||||
> = {
|
||||
TotalInvocations: (rawData, attributes, logsMetric, functionIds, edgeFnIdToName) => {
|
||||
// Always use dynamic attributes, so the chart can show per-function stats.
|
||||
if (!rawData) return { data: undefined, chartAttributes: attributes }
|
||||
const result = rawData.result || []
|
||||
|
||||
const functionIdsInData = Array.from(new Set(result.map((p: any) => p.function_id))) as string[]
|
||||
|
||||
const chartFunctionIds = functionIds && functionIds.length > 0 ? functionIds : functionIdsInData
|
||||
|
||||
if (chartFunctionIds.length === 0) {
|
||||
return { data: [], chartAttributes: [] } // No data, empty chart
|
||||
}
|
||||
|
||||
const chartAttributes = chartFunctionIds.map((id: string) => ({
|
||||
attribute: id,
|
||||
label: edgeFnIdToName?.(id) ?? id,
|
||||
provider: 'logs',
|
||||
enabled: true,
|
||||
}))
|
||||
|
||||
const timestamps = new Set<string>(result.map((p: any) => p.timestamp))
|
||||
const data = Array.from(timestamps)
|
||||
.sort()
|
||||
.map((timestamp) => {
|
||||
const point: any = { period_start: timestamp }
|
||||
chartAttributes.forEach((attr) => {
|
||||
point[attr.attribute] = 0
|
||||
})
|
||||
const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)
|
||||
matchingPoints.forEach((p: any) => {
|
||||
point[p.function_id as string] = p.count
|
||||
})
|
||||
return point
|
||||
})
|
||||
|
||||
return { data, chartAttributes }
|
||||
},
|
||||
ExecutionStatusCodes: (rawData, attributes) => {
|
||||
if (!rawData) return { data: undefined, chartAttributes: attributes }
|
||||
const result = rawData.result || []
|
||||
|
||||
const statusCodes = Array.from(new Set(result.map((p: any) => p.status_code)))
|
||||
|
||||
const chartAttributes = statusCodes.map((statusCode) => {
|
||||
const statusCodeInfo = getHttpStatusCodeInfo(Number(statusCode))
|
||||
const color =
|
||||
REPORT_STATUS_CODE_COLORS[String(statusCode)] || REPORT_STATUS_CODE_COLORS.default
|
||||
|
||||
return {
|
||||
attribute: `status_${statusCode}`,
|
||||
label: `${statusCode} ${statusCodeInfo.label}`,
|
||||
provider: 'logs',
|
||||
enabled: true,
|
||||
color: color,
|
||||
statusCode: String(statusCode),
|
||||
}
|
||||
})
|
||||
|
||||
const timestamps = new Set<string>(result.map((p: any) => p.timestamp))
|
||||
const data = Array.from(timestamps)
|
||||
.sort()
|
||||
.map((timestamp) => {
|
||||
const point: any = { period_start: timestamp }
|
||||
chartAttributes.forEach((attr) => {
|
||||
point[attr.attribute] = 0
|
||||
})
|
||||
const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)
|
||||
matchingPoints.forEach((p: any) => {
|
||||
point[`status_${p.status_code}`] = p.count
|
||||
})
|
||||
return point
|
||||
})
|
||||
|
||||
return { data, chartAttributes }
|
||||
},
|
||||
InvocationsByRegion: (rawData, attributes) => {
|
||||
if (!rawData) return { data: undefined, chartAttributes: attributes }
|
||||
const result = rawData.result || []
|
||||
|
||||
const regions = Array.from(new Set(result.map((p: any) => p.region))).filter(Boolean)
|
||||
|
||||
if (regions.length === 0) {
|
||||
return { data: [], chartAttributes: [] } // No data, empty chart
|
||||
}
|
||||
|
||||
const chartAttributes = regions.map((region) => {
|
||||
return {
|
||||
attribute: region,
|
||||
label: region,
|
||||
provider: 'logs',
|
||||
enabled: true,
|
||||
}
|
||||
})
|
||||
|
||||
const timestamps = new Set<string>(result.map((p: any) => p.timestamp))
|
||||
const data = Array.from(timestamps)
|
||||
.sort()
|
||||
.map((timestamp) => {
|
||||
const point: any = { period_start: timestamp }
|
||||
chartAttributes.forEach((attr) => {
|
||||
point[attr.attribute as string] = 0
|
||||
})
|
||||
const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)
|
||||
matchingPoints.forEach((p: any) => {
|
||||
point[p.region] = p.count
|
||||
})
|
||||
return point
|
||||
})
|
||||
|
||||
return { data, chartAttributes }
|
||||
},
|
||||
ExecutionTime: (rawData, attributes, logsMetric, functionIds, edgeFnIdToName) => {
|
||||
if (!rawData) return { data: undefined, chartAttributes: attributes }
|
||||
const result = rawData.result || []
|
||||
const hasFunctions = functionIds && functionIds.length > 0
|
||||
|
||||
if (hasFunctions) {
|
||||
const chartAttributes = functionIds.map((id: string) => ({
|
||||
attribute: id,
|
||||
label: edgeFnIdToName?.(id) ?? id,
|
||||
provider: 'logs',
|
||||
enabled: true,
|
||||
}))
|
||||
|
||||
if (result.length === 0) {
|
||||
return { data: [], chartAttributes }
|
||||
}
|
||||
|
||||
const timestamps = new Set<string>(result.map((p: any) => p.timestamp))
|
||||
const data = Array.from(timestamps)
|
||||
.sort()
|
||||
.map((timestamp) => {
|
||||
const point: any = { period_start: timestamp }
|
||||
chartAttributes.forEach((attr) => {
|
||||
point[attr.attribute] = 0
|
||||
})
|
||||
const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)
|
||||
matchingPoints.forEach((p: any) => {
|
||||
point[p.function_id as string] = p.avg_execution_time
|
||||
})
|
||||
return point
|
||||
})
|
||||
|
||||
return { data, chartAttributes }
|
||||
} else {
|
||||
const chartAttributes = [
|
||||
{
|
||||
attribute: 'avg_execution_time',
|
||||
label: 'Avg. execution time (ms)',
|
||||
provider: 'logs',
|
||||
enabled: true,
|
||||
},
|
||||
]
|
||||
|
||||
const data = result
|
||||
.map((p: any) => ({
|
||||
period_start: p.timestamp,
|
||||
avg_execution_time: p.avg_execution_time,
|
||||
}))
|
||||
.sort(
|
||||
(a: { period_start: string }, b: { period_start: string }) =>
|
||||
new Date(a.period_start).getTime() - new Date(b.period_start).getTime()
|
||||
)
|
||||
|
||||
return { data, chartAttributes }
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* REPORT QUERY.
|
||||
* Fetching and state management for the report.
|
||||
*/
|
||||
|
||||
export function useEdgeFunctionReport({
|
||||
projectRef,
|
||||
attributes,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
enabled = true,
|
||||
functionIds,
|
||||
}: {
|
||||
projectRef: string
|
||||
attributes: MultiAttribute[]
|
||||
startDate: string
|
||||
endDate: string
|
||||
interval: AnalyticsInterval
|
||||
enabled?: boolean
|
||||
functionIds?: string[]
|
||||
}) {
|
||||
const logsMetric = attributes.length > 0 ? attributes[0].attribute : ''
|
||||
const { edgeFnIdToName } = useEdgeFnIdToName({ projectRef })
|
||||
const isEdgeFnMetric = METRIC_KEYS.includes(logsMetric)
|
||||
|
||||
const sql = isEdgeFnMetric ? METRIC_SQL[logsMetric as MetricKey](interval, functionIds) : ''
|
||||
|
||||
const {
|
||||
data: rawData,
|
||||
error,
|
||||
isLoading,
|
||||
} = useQuery(
|
||||
[
|
||||
'edge-function-report',
|
||||
projectRef,
|
||||
logsMetric,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
sql,
|
||||
functionIds,
|
||||
],
|
||||
async () => {
|
||||
const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {
|
||||
params: {
|
||||
path: { ref: projectRef },
|
||||
query: {
|
||||
sql,
|
||||
iso_timestamp_start: startDate,
|
||||
iso_timestamp_end: endDate,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (error) throw error
|
||||
return data
|
||||
},
|
||||
{
|
||||
enabled: Boolean(projectRef && sql && enabled && isEdgeFnMetric),
|
||||
refetchOnWindowFocus: false,
|
||||
}
|
||||
)
|
||||
|
||||
// Use formatter if available
|
||||
const formatter =
|
||||
(isEdgeFnMetric ? METRIC_FORMATTER[logsMetric as MetricKey] : undefined) || defaultFormatter
|
||||
const { data, chartAttributes } = formatter(
|
||||
rawData,
|
||||
attributes,
|
||||
logsMetric,
|
||||
functionIds,
|
||||
edgeFnIdToName
|
||||
)
|
||||
|
||||
return {
|
||||
data,
|
||||
attributes: chartAttributes,
|
||||
isLoading,
|
||||
error,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
import dayjs from 'dayjs'
|
||||
|
||||
import {
|
||||
isUnixMicro,
|
||||
unixMicroToIsoTimestamp,
|
||||
} from 'components/interfaces/Settings/Logs/Logs.utils'
|
||||
import type { AnalyticsInterval } from 'data/analytics/constants'
|
||||
import { get } from 'data/fetchers'
|
||||
import {
|
||||
analyticsIntervalToGranularity,
|
||||
REPORT_STATUS_CODE_COLORS,
|
||||
} from 'data/reports/report.utils'
|
||||
import { getHttpStatusCodeInfo } from 'lib/http-status-codes'
|
||||
import { ReportConfig } from './reports.types'
|
||||
|
||||
const METRIC_SQL: Record<string, (interval: AnalyticsInterval, functionIds?: string[]) => string> =
|
||||
{
|
||||
TotalInvocations: (interval, functionIds) => {
|
||||
return `
|
||||
--edgefn-report-invocations
|
||||
select
|
||||
timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,
|
||||
function_id,
|
||||
count(*) as count
|
||||
from
|
||||
function_edge_logs
|
||||
CROSS JOIN UNNEST(metadata) AS m
|
||||
CROSS JOIN UNNEST(m.request) AS request
|
||||
CROSS JOIN UNNEST(m.response) AS response
|
||||
${
|
||||
functionIds && functionIds.length > 0
|
||||
? `WHERE function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
|
||||
: ''
|
||||
}
|
||||
group by
|
||||
timestamp,
|
||||
function_id
|
||||
order by
|
||||
timestamp desc;
|
||||
`
|
||||
},
|
||||
ExecutionStatusCodes: (interval, functionIds) => {
|
||||
return `
|
||||
--edgefn-report-execution-status-codes
|
||||
select
|
||||
timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,
|
||||
response.status_code as status_code,
|
||||
count(response.status_code) as count
|
||||
from
|
||||
function_edge_logs
|
||||
cross join unnest(metadata) as m
|
||||
cross join unnest(m.response) as response
|
||||
${
|
||||
functionIds && functionIds.length > 0
|
||||
? `where function_id in (${functionIds.map((id) => `'${id}'`).join(',')})`
|
||||
: ''
|
||||
}
|
||||
group by
|
||||
timestamp,
|
||||
status_code
|
||||
order by
|
||||
timestamp desc
|
||||
`
|
||||
},
|
||||
InvocationsByRegion: (interval, functionIds) => {
|
||||
const granularity = analyticsIntervalToGranularity(interval)
|
||||
return `
|
||||
--edgefn-report-invocations-by-region
|
||||
select
|
||||
timestamp_trunc(timestamp, ${granularity}) as timestamp,
|
||||
h.x_sb_edge_region as region,
|
||||
count(*) as count
|
||||
from
|
||||
function_edge_logs
|
||||
cross join unnest(metadata) as m
|
||||
cross join unnest(m.response) as r
|
||||
cross join unnest(r.headers) as h
|
||||
where h.x_sb_edge_region is not null
|
||||
${
|
||||
functionIds && functionIds.length > 0
|
||||
? `and function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
|
||||
: ''
|
||||
}
|
||||
group by
|
||||
timestamp,
|
||||
region
|
||||
order by
|
||||
timestamp desc
|
||||
`
|
||||
},
|
||||
ExecutionTime: (interval, functionIds) => {
|
||||
const granularity = analyticsIntervalToGranularity(interval)
|
||||
const hasFunctions = functionIds && functionIds.length > 0
|
||||
return `
|
||||
--edgefn-report-execution-time
|
||||
select
|
||||
timestamp_trunc(timestamp, ${granularity}) as timestamp,
|
||||
${hasFunctions ? 'function_id,' : ''}
|
||||
avg(m.execution_time_ms) as avg_execution_time
|
||||
from
|
||||
function_edge_logs
|
||||
cross join unnest(metadata) as m
|
||||
cross join unnest(m.request) as request
|
||||
${hasFunctions ? `where function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})` : ''}
|
||||
group by
|
||||
timestamp
|
||||
${hasFunctions ? ', function_id' : ''}
|
||||
order by
|
||||
timestamp desc
|
||||
`
|
||||
},
|
||||
}
|
||||
|
||||
async function runQuery(projectRef: string, sql: string, startDate: string, endDate: string) {
|
||||
const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {
|
||||
params: {
|
||||
path: { ref: projectRef },
|
||||
query: {
|
||||
sql,
|
||||
iso_timestamp_start: startDate,
|
||||
iso_timestamp_end: endDate,
|
||||
},
|
||||
},
|
||||
})
|
||||
if (error) throw error
|
||||
return data
|
||||
}
|
||||
|
||||
export function extractStatusCodesFromData(data: any[]): string[] {
|
||||
const statusCodes = new Set<string>()
|
||||
|
||||
data.forEach((item: any) => {
|
||||
if (item.status_code) {
|
||||
statusCodes.add(String(item.status_code))
|
||||
}
|
||||
})
|
||||
|
||||
return Array.from(statusCodes).sort()
|
||||
}
|
||||
|
||||
export function generateStatusCodeAttributes(statusCodes: string[]) {
|
||||
return statusCodes.map((code) => ({
|
||||
attribute: code,
|
||||
label: `${code} ${getHttpStatusCodeInfo(parseInt(code)).label}`,
|
||||
color: REPORT_STATUS_CODE_COLORS[code] || REPORT_STATUS_CODE_COLORS.default,
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a list of { timestamp, status_code, count }
|
||||
* to a list of { timestamp, [status_code]: count }
|
||||
* That we can pass to the chart for rendering
|
||||
*/
|
||||
export function transformStatusCodeData(data: any[], statusCodes: string[]) {
|
||||
const pivotedData = data.reduce((acc: Record<string, any>, d: any) => {
|
||||
const timestamp = isUnixMicro(d.timestamp)
|
||||
? unixMicroToIsoTimestamp(d.timestamp)
|
||||
: dayjs.utc(d.timestamp).toISOString()
|
||||
if (!acc[timestamp]) {
|
||||
acc[timestamp] = { timestamp }
|
||||
statusCodes.forEach((code) => {
|
||||
acc[timestamp][code] = 0
|
||||
})
|
||||
}
|
||||
acc[timestamp][d.status_code] = d.count
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
return Object.values(pivotedData)
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms raw invocation data by normalizing timestamps and adding function names
|
||||
* @param data - Raw data from the database
|
||||
* @param functions - Array of function objects with id and name
|
||||
* @returns Transformed data with normalized timestamps and function names
|
||||
*/
|
||||
export function transformInvocationData(data: any[], functions: { id: string; name: string }[]) {
|
||||
return data.map((log: any) => ({
|
||||
...log,
|
||||
timestamp: isUnixMicro(log.timestamp)
|
||||
? unixMicroToIsoTimestamp(log.timestamp)
|
||||
: dayjs.utc(log.timestamp).toISOString(),
|
||||
function_name: functions.find((f) => f.id === log.function_id)?.name ?? log.function_id,
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregates invocation data by timestamp, summing counts for each timestamp
|
||||
* @param data - Transformed invocation data
|
||||
* @returns Aggregated data with one entry per timestamp
|
||||
*/
|
||||
export function aggregateInvocationsByTimestamp(data: any[]) {
|
||||
const aggregatedData = data.reduce((acc: Record<string, any>, item: any) => {
|
||||
const timestamp = item.timestamp
|
||||
if (!acc[timestamp]) {
|
||||
acc[timestamp] = { timestamp, count: 0 }
|
||||
}
|
||||
acc[timestamp].count += item.count
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
return Object.values(aggregatedData)
|
||||
}
|
||||
|
||||
export const edgeFunctionReports = ({
|
||||
projectRef,
|
||||
functions,
|
||||
startDate,
|
||||
endDate,
|
||||
interval,
|
||||
filters,
|
||||
}: {
|
||||
projectRef: string
|
||||
functions: { id: string; name: string }[]
|
||||
startDate: string
|
||||
endDate: string
|
||||
interval: AnalyticsInterval
|
||||
filters: {
|
||||
functionIds?: string[]
|
||||
}
|
||||
}): ReportConfig[] => [
|
||||
{
|
||||
id: 'total-invocations',
|
||||
label: 'Total Edge Function Invocations',
|
||||
valuePrecision: 0,
|
||||
hide: false,
|
||||
showTooltip: true,
|
||||
showLegend: true,
|
||||
showMaxValue: false,
|
||||
hideChartType: false,
|
||||
defaultChartStyle: 'line',
|
||||
titleTooltip: 'The total number of edge function invocations over time.',
|
||||
availableIn: ['free', 'pro', 'team', 'enterprise'],
|
||||
dataProvider: async () => {
|
||||
const sql = METRIC_SQL.TotalInvocations(interval, filters.functionIds)
|
||||
const response = await runQuery(projectRef, sql, startDate, endDate)
|
||||
|
||||
if (!response?.result) return { data: [] }
|
||||
|
||||
// Transform and aggregate the data using extracted functions
|
||||
const transformedData = transformInvocationData(response.result, functions)
|
||||
const data = aggregateInvocationsByTimestamp(transformedData)
|
||||
|
||||
const attributes = [
|
||||
{
|
||||
attribute: 'count',
|
||||
label: 'Count',
|
||||
},
|
||||
]
|
||||
|
||||
return { data, attributes, query: sql }
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'execution-status-codes',
|
||||
label: 'Edge Function Status Codes',
|
||||
valuePrecision: 0,
|
||||
hide: false,
|
||||
showTooltip: true,
|
||||
showLegend: true,
|
||||
showMaxValue: false,
|
||||
hideChartType: false,
|
||||
defaultChartStyle: 'line',
|
||||
titleTooltip: 'The total number of edge function executions by status code.',
|
||||
availableIn: ['free', 'pro', 'team', 'enterprise'],
|
||||
dataProvider: async (
|
||||
projectRef: string,
|
||||
startDate: string,
|
||||
endDate: string,
|
||||
interval: AnalyticsInterval,
|
||||
functionIds?: string[]
|
||||
) => {
|
||||
const sql = METRIC_SQL.ExecutionStatusCodes(interval, functionIds)
|
||||
const rawData = await runQuery(projectRef, sql, startDate, endDate)
|
||||
|
||||
if (!rawData?.result) return { data: [] }
|
||||
|
||||
/**
|
||||
* The query returns { timestamp, status_code: 500, count: 10 }
|
||||
* and we have to transform it to { timestamp, 500: 10 }
|
||||
* to be able to render the chart.
|
||||
*/
|
||||
|
||||
const statusCodes = extractStatusCodesFromData(rawData.result)
|
||||
const attributes = generateStatusCodeAttributes(statusCodes)
|
||||
|
||||
const data = transformStatusCodeData(rawData.result, statusCodes)
|
||||
|
||||
return { data, attributes, query: sql }
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'execution-time',
|
||||
label: 'Edge Function Execution Time',
|
||||
valuePrecision: 0,
|
||||
hide: false,
|
||||
showTooltip: true,
|
||||
showLegend: true,
|
||||
showMaxValue: false,
|
||||
hideChartType: false,
|
||||
defaultChartStyle: 'line',
|
||||
titleTooltip: 'Average execution time for edge functions.',
|
||||
availableIn: ['free', 'pro', 'team', 'enterprise'],
|
||||
YAxisProps: {
|
||||
width: 50,
|
||||
tickFormatter: (value: number) => `${value}ms`,
|
||||
},
|
||||
format: (value: unknown) => `${Number(value).toFixed(0)}ms`,
|
||||
dataProvider: async () => {
|
||||
const sql = METRIC_SQL.ExecutionTime(interval, filters.functionIds)
|
||||
const rawData = await runQuery(projectRef, sql, startDate, endDate)
|
||||
|
||||
if (!rawData?.result) return { data: [] }
|
||||
|
||||
// Transform the raw data to ensure one data point per timestamp
|
||||
const transformedData = rawData.result?.map((point: any) => ({
|
||||
...point,
|
||||
timestamp: isUnixMicro(point.timestamp)
|
||||
? unixMicroToIsoTimestamp(point.timestamp)
|
||||
: dayjs.utc(point.timestamp).toISOString(),
|
||||
function_name: functions.find((f) => f.id === point.function_id)?.name ?? point.function_id,
|
||||
}))
|
||||
|
||||
// If we have multiple function IDs, we need to aggregate the execution times per timestamp
|
||||
const aggregatedData = transformedData.reduce((acc: Record<string, any>, item: any) => {
|
||||
const timestamp = item.timestamp
|
||||
if (!acc[timestamp]) {
|
||||
acc[timestamp] = {
|
||||
timestamp,
|
||||
avg_execution_time: item.avg_execution_time,
|
||||
count: 1,
|
||||
}
|
||||
} else {
|
||||
// Calculate weighted average for multiple functions at the same timestamp
|
||||
const totalTime =
|
||||
acc[timestamp].avg_execution_time * acc[timestamp].count + item.avg_execution_time
|
||||
acc[timestamp].count += 1
|
||||
acc[timestamp].avg_execution_time = totalTime / acc[timestamp].count
|
||||
}
|
||||
return acc
|
||||
}, {})
|
||||
|
||||
const data = Object.values(aggregatedData).map(({ count, ...item }) => item)
|
||||
|
||||
const attributes = [
|
||||
{
|
||||
attribute: 'avg_execution_time',
|
||||
label: 'Avg. execution time (ms)',
|
||||
},
|
||||
]
|
||||
return { data, attributes, query: sql }
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'invocations-by-region',
|
||||
label: 'Edge Function Invocations by Region',
|
||||
valuePrecision: 0,
|
||||
hide: false,
|
||||
showTooltip: true,
|
||||
showLegend: true,
|
||||
showMaxValue: false,
|
||||
hideChartType: false,
|
||||
defaultChartStyle: 'line',
|
||||
titleTooltip: 'The total number of edge function invocations by region.',
|
||||
availableIn: ['pro', 'team', 'enterprise'],
|
||||
dataProvider: async () => {
|
||||
const sql = METRIC_SQL.InvocationsByRegion(interval, filters.functionIds)
|
||||
const rawData = await runQuery(projectRef, sql, startDate, endDate)
|
||||
const data = rawData.result?.map((point: any) => ({
|
||||
...point,
|
||||
timestamp: isUnixMicro(point.timestamp)
|
||||
? unixMicroToIsoTimestamp(point.timestamp)
|
||||
: dayjs.utc(point.timestamp).toISOString(),
|
||||
}))
|
||||
|
||||
const attributes = [
|
||||
{
|
||||
attribute: 'region',
|
||||
label: 'Region',
|
||||
provider: 'logs',
|
||||
enabled: true,
|
||||
},
|
||||
{
|
||||
attribute: 'count',
|
||||
label: 'Count',
|
||||
provider: 'logs',
|
||||
enabled: true,
|
||||
},
|
||||
]
|
||||
|
||||
return { data, attributes, query: sql }
|
||||
},
|
||||
},
|
||||
]
|
||||
@@ -0,0 +1,251 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
extractStatusCodesFromData,
|
||||
generateStatusCodeAttributes,
|
||||
transformStatusCodeData,
|
||||
transformInvocationData,
|
||||
aggregateInvocationsByTimestamp,
|
||||
} from './edge-functions.config'
|
||||
|
||||
describe('extractStatusCodesFromData', () => {
|
||||
it('should extract and sort unique status codes from the data', () => {
|
||||
const data = [
|
||||
{ status_code: 200 },
|
||||
{ status_code: 500 },
|
||||
{ status_code: 200 },
|
||||
{ status_code: 404 },
|
||||
]
|
||||
const result = extractStatusCodesFromData(data)
|
||||
expect(result).toEqual(['200', '404', '500'])
|
||||
})
|
||||
|
||||
it('should handle an empty array', () => {
|
||||
const data: any[] = []
|
||||
const result = extractStatusCodesFromData(data)
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('should handle data with missing status_code properties', () => {
|
||||
const data = [{ status_code: 200 }, {}, { status_code: 500 }]
|
||||
const result = extractStatusCodesFromData(data)
|
||||
expect(result).toEqual(['200', '500'])
|
||||
})
|
||||
|
||||
it('should handle various data types for status_code', () => {
|
||||
const data = [{ status_code: 200 }, { status_code: '500' }, { status_code: 404 }]
|
||||
const result = extractStatusCodesFromData(data)
|
||||
expect(result).toEqual(['200', '404', '500'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('generateStatusCodeAttributes', () => {
|
||||
it('should generate the correct attributes for a list of status codes', () => {
|
||||
const statusCodes = ['200', '404', '500']
|
||||
const result = generateStatusCodeAttributes(statusCodes)
|
||||
expect(result.map(({ color, ...rest }) => rest)).toEqual([
|
||||
{
|
||||
attribute: '200',
|
||||
label: '200 OK',
|
||||
},
|
||||
{
|
||||
attribute: '404',
|
||||
label: '404 Not Found',
|
||||
},
|
||||
{
|
||||
attribute: '500',
|
||||
label: '500 Internal Server Error',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('should handle an empty array', () => {
|
||||
const statusCodes: string[] = []
|
||||
const result = generateStatusCodeAttributes(statusCodes)
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('transformStatusCodeData', () => {
|
||||
it('should pivot the data correctly', () => {
|
||||
const data = [
|
||||
{ timestamp: '2023-01-01T00:00:00Z', status_code: 200, count: 10 },
|
||||
{ timestamp: '2023-01-01T00:00:00Z', status_code: 500, count: 5 },
|
||||
{ timestamp: '2023-01-02T00:00:00Z', status_code: 200, count: 20 },
|
||||
]
|
||||
const result = transformStatusCodeData(data, ['200', '500'])
|
||||
expect(result).toEqual([
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', '200': 10, '500': 5 },
|
||||
{ timestamp: '2023-01-02T00:00:00.000Z', '200': 20, '500': 0 },
|
||||
])
|
||||
})
|
||||
|
||||
it('should handle an empty array', () => {
|
||||
const data: any[] = []
|
||||
const result = transformStatusCodeData(data, [])
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('should handle a single entry', () => {
|
||||
const data = [{ timestamp: '2023-01-01T00:00:00Z', status_code: 200, count: 10 }]
|
||||
const result = transformStatusCodeData(data, ['200', '404'])
|
||||
expect(result).toEqual([{ timestamp: '2023-01-01T00:00:00.000Z', '200': 10, '404': 0 }])
|
||||
})
|
||||
})
|
||||
|
||||
describe('transformInvocationData', () => {
|
||||
const mockFunctions = [
|
||||
{ id: 'func1', name: 'Function One' },
|
||||
{ id: 'func2', name: 'Function Two' },
|
||||
]
|
||||
|
||||
it('should transform raw invocation data with function names', () => {
|
||||
const rawData = [
|
||||
{
|
||||
timestamp: '2023-01-01T00:00:00Z',
|
||||
function_id: 'func1',
|
||||
count: 10,
|
||||
},
|
||||
{
|
||||
timestamp: '2023-01-01T01:00:00Z',
|
||||
function_id: 'func2',
|
||||
count: 5,
|
||||
},
|
||||
]
|
||||
|
||||
const result = transformInvocationData(rawData, mockFunctions)
|
||||
expect(result).toEqual([
|
||||
{
|
||||
timestamp: '2023-01-01T00:00:00.000Z',
|
||||
function_id: 'func1',
|
||||
count: 10,
|
||||
function_name: 'Function One',
|
||||
},
|
||||
{
|
||||
timestamp: '2023-01-01T01:00:00.000Z',
|
||||
function_id: 'func2',
|
||||
count: 5,
|
||||
function_name: 'Function Two',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('should use function_id as fallback when function name not found', () => {
|
||||
const rawData = [
|
||||
{
|
||||
timestamp: '2023-01-01T00:00:00Z',
|
||||
function_id: 'unknown_func',
|
||||
count: 10,
|
||||
},
|
||||
]
|
||||
|
||||
const result = transformInvocationData(rawData, mockFunctions)
|
||||
expect(result).toEqual([
|
||||
{
|
||||
timestamp: '2023-01-01T00:00:00.000Z',
|
||||
function_id: 'unknown_func',
|
||||
count: 10,
|
||||
function_name: 'unknown_func',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('should handle unix micro timestamps', () => {
|
||||
const rawData = [
|
||||
{
|
||||
timestamp: 1672531200000000, // Unix micro timestamp for 2023-01-01T00:00:00Z
|
||||
function_id: 'func1',
|
||||
count: 10,
|
||||
},
|
||||
]
|
||||
|
||||
const result = transformInvocationData(rawData, mockFunctions)
|
||||
expect(result[0].timestamp).toBe('2023-01-01T00:00:00.000Z')
|
||||
expect(result[0].function_name).toBe('Function One')
|
||||
})
|
||||
|
||||
it('should handle empty data array', () => {
|
||||
const result = transformInvocationData([], mockFunctions)
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('should handle empty functions array', () => {
|
||||
const rawData = [
|
||||
{
|
||||
timestamp: '2023-01-01T00:00:00Z',
|
||||
function_id: 'func1',
|
||||
count: 10,
|
||||
},
|
||||
]
|
||||
|
||||
const result = transformInvocationData(rawData, [])
|
||||
expect(result).toEqual([
|
||||
{
|
||||
timestamp: '2023-01-01T00:00:00.000Z',
|
||||
function_id: 'func1',
|
||||
count: 10,
|
||||
function_name: 'func1',
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('aggregateInvocationsByTimestamp', () => {
|
||||
it('should aggregate counts by timestamp', () => {
|
||||
const data = [
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func1', count: 10 },
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func2', count: 5 },
|
||||
{ timestamp: '2023-01-01T01:00:00.000Z', function_id: 'func1', count: 20 },
|
||||
]
|
||||
|
||||
const result = aggregateInvocationsByTimestamp(data)
|
||||
expect(result).toEqual([
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', count: 15 },
|
||||
{ timestamp: '2023-01-01T01:00:00.000Z', count: 20 },
|
||||
])
|
||||
})
|
||||
|
||||
it('should handle single entry per timestamp', () => {
|
||||
const data = [
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func1', count: 10 },
|
||||
{ timestamp: '2023-01-01T01:00:00.000Z', function_id: 'func2', count: 5 },
|
||||
]
|
||||
|
||||
const result = aggregateInvocationsByTimestamp(data)
|
||||
expect(result).toEqual([
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', count: 10 },
|
||||
{ timestamp: '2023-01-01T01:00:00.000Z', count: 5 },
|
||||
])
|
||||
})
|
||||
|
||||
it('should handle empty data array', () => {
|
||||
const result = aggregateInvocationsByTimestamp([])
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('should handle multiple entries with same timestamp and different counts', () => {
|
||||
const data = [
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func1', count: 1 },
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func2', count: 2 },
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func3', count: 3 },
|
||||
]
|
||||
|
||||
const result = aggregateInvocationsByTimestamp(data)
|
||||
expect(result).toEqual([{ timestamp: '2023-01-01T00:00:00.000Z', count: 6 }])
|
||||
})
|
||||
|
||||
it('should preserve timestamp order from reduce operation', () => {
|
||||
const data = [
|
||||
{ timestamp: '2023-01-01T02:00:00.000Z', function_id: 'func1', count: 30 },
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func1', count: 10 },
|
||||
{ timestamp: '2023-01-01T01:00:00.000Z', function_id: 'func1', count: 20 },
|
||||
]
|
||||
|
||||
const result = aggregateInvocationsByTimestamp(data)
|
||||
expect(result).toHaveLength(3)
|
||||
expect(result.map((item) => item.timestamp)).toEqual([
|
||||
'2023-01-01T02:00:00.000Z',
|
||||
'2023-01-01T00:00:00.000Z',
|
||||
'2023-01-01T01:00:00.000Z',
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { AnalyticsInterval } from 'data/analytics/constants'
|
||||
import { YAxisProps } from 'recharts'
|
||||
|
||||
type ReportDataProviderFilter = {
|
||||
functionIds?: string[]
|
||||
}
|
||||
|
||||
export interface ReportDataProvider {
|
||||
(
|
||||
projectRef: string,
|
||||
startDate: string,
|
||||
endDate: string,
|
||||
interval: AnalyticsInterval,
|
||||
functionIds?: string[],
|
||||
edgeFnIdToName?: (id: string) => string | undefined,
|
||||
filters?: ReportDataProviderFilter[]
|
||||
): Promise<{
|
||||
data: any
|
||||
attributes?: {
|
||||
attribute: string
|
||||
label: string
|
||||
color?: { light: string; dark: string }
|
||||
}[]
|
||||
query?: string // The SQL used to fetch the data if any
|
||||
}> // [jordi] would be cool to have a type that forces data keys to match the attributes
|
||||
}
|
||||
|
||||
export interface ReportConfig {
|
||||
id: string
|
||||
label: string
|
||||
dataProvider: ReportDataProvider
|
||||
valuePrecision: number
|
||||
hide: boolean
|
||||
showTooltip: boolean
|
||||
showLegend: boolean
|
||||
showMaxValue: boolean
|
||||
hideChartType: boolean
|
||||
defaultChartStyle: string
|
||||
titleTooltip: string
|
||||
availableIn: string[]
|
||||
format?: (value: unknown) => string
|
||||
YAxisProps?: YAxisProps
|
||||
xAxisKey?: string
|
||||
yAxisKey?: string
|
||||
}
|
||||
@@ -201,13 +201,15 @@ export const useEdgeFunctionsDiff = ({
|
||||
const mainBody = mainBodiesMap[slug]
|
||||
if (!currentBody || !mainBody) return
|
||||
|
||||
const allFileKeys = new Set([...currentBody, ...mainBody].map((f) => fileKey(f.name)))
|
||||
const allFileKeys = new Set(
|
||||
[...currentBody.files, ...mainBody.files].map((f) => fileKey(f.name))
|
||||
)
|
||||
const fileInfos: FileInfo[] = []
|
||||
let hasModifications = false
|
||||
|
||||
for (const key of allFileKeys) {
|
||||
const currentFile = currentBody.find((f) => fileKey(f.name) === key)
|
||||
const mainFile = mainBody.find((f) => fileKey(f.name) === key)
|
||||
const currentFile = currentBody.files.find((f) => fileKey(f.name) === key)
|
||||
const mainFile = mainBody.files.find((f) => fileKey(f.name) === key)
|
||||
|
||||
let status: FileStatus = 'unchanged'
|
||||
|
||||
@@ -236,7 +238,7 @@ export const useEdgeFunctionsDiff = ({
|
||||
addedSlugs.forEach((slug) => {
|
||||
const body = addedBodiesMap[slug]
|
||||
if (body) {
|
||||
functionFileInfo[slug] = body.map((file) => ({
|
||||
functionFileInfo[slug] = body.files.map((file) => ({
|
||||
key: fileKey(file.name),
|
||||
status: 'added' as FileStatus,
|
||||
}))
|
||||
@@ -247,7 +249,7 @@ export const useEdgeFunctionsDiff = ({
|
||||
removedSlugs.forEach((slug) => {
|
||||
const body = removedBodiesMap[slug]
|
||||
if (body) {
|
||||
functionFileInfo[slug] = body.map((file) => ({
|
||||
functionFileInfo[slug] = body.files.map((file) => ({
|
||||
key: fileKey(file.name),
|
||||
status: 'removed' as FileStatus,
|
||||
}))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ConnectionType } from 'components/interfaces/Connect/Connect.constants'
|
||||
import { CONNECTION_TYPES } from 'components/interfaces/Connect/Connect.constants'
|
||||
import type { CloudProvider } from 'shared-data'
|
||||
|
||||
export type CustomContentTypes = {
|
||||
organizationLegalDocuments: {
|
||||
@@ -25,9 +26,7 @@ export type CustomContentTypes = {
|
||||
*
|
||||
* These could be helpful in rendering, for e.g an environment file like `.env`
|
||||
*/
|
||||
connectFrameworks: {
|
||||
key: string
|
||||
label: string
|
||||
obj: ConnectionType[]
|
||||
}
|
||||
connectFrameworks: (typeof CONNECTION_TYPES)[number]
|
||||
|
||||
infraCloudProviders: CloudProvider[]
|
||||
}
|
||||
@@ -7,5 +7,7 @@
|
||||
|
||||
"logs:default_query": null,
|
||||
|
||||
"connect:frameworks": null
|
||||
"connect:frameworks": null,
|
||||
|
||||
"infra:cloud_providers": ["AWS", "AWS_K8S", "FLY"]
|
||||
}
|
||||
@@ -72,5 +72,7 @@
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
"infra:cloud_providers": ["AWS_NIMBUS"]
|
||||
}
|
||||
@@ -72,13 +72,23 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
"infra:cloud_providers": {
|
||||
"type": ["array"],
|
||||
"description": "Filters the valid cloud providers",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["AWS", "AWS_K8S", "AWS_NIMBUS", "FLY"]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"organization:legal_documents",
|
||||
"project_homepage:example_projects",
|
||||
"logs:default_query",
|
||||
"connect:frameworks"
|
||||
"connect:frameworks",
|
||||
"infra:cloud_providers"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -28,16 +28,16 @@ const useCustomContent = <T extends CustomContent[]>(
|
||||
contents: T
|
||||
): {
|
||||
[key in CustomContentToCamelCase<T[number]>]:
|
||||
| (typeof customContentStaticObj)[CustomContent]
|
||||
| CustomContentTypes[CustomContentToCamelCase<T[number]>]
|
||||
| null
|
||||
} => {
|
||||
// [Joshen] Running into some TS errors without the `as` here - must be overlooking something super simple
|
||||
return Object.fromEntries(
|
||||
contents.map((content) => [contentToCamelCase(content), customContentStaticObj[content]])
|
||||
) as {
|
||||
[key in CustomContentToCamelCase<T[number]>]:
|
||||
| (typeof customContentStaticObj)[CustomContent]
|
||||
| CustomContentTypes[CustomContentToCamelCase<T[number]>]
|
||||
| null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
} from 'components/interfaces/Reports/Reports.constants'
|
||||
import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'
|
||||
import { maybeShowUpgradePrompt } from 'components/interfaces/Settings/Logs/Logs.utils'
|
||||
import { AnalyticsInterval } from 'data/analytics/constants'
|
||||
|
||||
export const DATERANGE_LIMITS: { [key: string]: number } = {
|
||||
free: 1,
|
||||
@@ -20,7 +21,7 @@ export const DATERANGE_LIMITS: { [key: string]: number } = {
|
||||
export interface ReportDateRange {
|
||||
period_start: { date: string; time_period: string }
|
||||
period_end: { date: string; time_period: string }
|
||||
interval: string
|
||||
interval: AnalyticsInterval
|
||||
}
|
||||
|
||||
// Create parsers for individual URL parameters
|
||||
|
||||
@@ -15,7 +15,6 @@ import type { AnalyticsInterval, DataPoint } from 'data/analytics/constants'
|
||||
import { useAuthLogsReport } from 'data/reports/auth-report-query'
|
||||
import type { ChartData } from 'components/ui/Charts/Charts.types'
|
||||
import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'
|
||||
import { useEdgeFunctionReport } from 'data/reports/edgefn-query'
|
||||
|
||||
export const useChartData = ({
|
||||
attributes,
|
||||
@@ -56,25 +55,9 @@ export const useChartData = ({
|
||||
enabled: enabled && logsAttributes.length > 0 && !isEdgeFunctionRoute,
|
||||
})
|
||||
|
||||
const {
|
||||
data: edgeFunctionData,
|
||||
attributes: edgeFunctionChartAttributes,
|
||||
isLoading: isEdgeFunctionLoading,
|
||||
} = useEdgeFunctionReport({
|
||||
projectRef: ref as string,
|
||||
attributes: logsAttributes,
|
||||
startDate,
|
||||
endDate,
|
||||
interval: interval as AnalyticsInterval,
|
||||
enabled: enabled && logsAttributes.length > 0 && isEdgeFunctionRoute,
|
||||
functionIds,
|
||||
})
|
||||
|
||||
const logsData = isEdgeFunctionRoute ? edgeFunctionData : authData
|
||||
const logsChartAttributes = isEdgeFunctionRoute
|
||||
? edgeFunctionChartAttributes
|
||||
: authChartAttributes
|
||||
const isLogsLoading = isEdgeFunctionRoute ? isEdgeFunctionLoading : isAuthLoading
|
||||
const logsData = authData
|
||||
const logsChartAttributes = authChartAttributes
|
||||
const isLogsLoading = isAuthLoading
|
||||
|
||||
const combinedData = useMemo(() => {
|
||||
if (data) return data
|
||||
|
||||
@@ -64,7 +64,7 @@ Sentry.init({
|
||||
`Failed to construct 'URL': Invalid URL`
|
||||
)
|
||||
// [Joshen] Similar behaviour for this error from SessionTimeoutModal to control the quota usage
|
||||
const isSessionTimeoutEvent = (hint.originalException as any)?.message.includes(
|
||||
const isSessionTimeoutEvent = (hint.originalException as any)?.message?.includes(
|
||||
'Session error detected'
|
||||
)
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { CloudProvider } from 'shared-data'
|
||||
import { AWS_REGIONS, FLY_REGIONS } from 'shared-data'
|
||||
|
||||
import type { components } from 'data/api'
|
||||
import { useCustomContent } from 'hooks/custom-content/useCustomContent'
|
||||
|
||||
export const AWS_REGIONS_DEFAULT =
|
||||
process.env.NEXT_PUBLIC_ENVIRONMENT !== 'prod'
|
||||
@@ -33,11 +34,21 @@ export const PRICING_TIER_PRODUCT_IDS = {
|
||||
ENTERPRISE: 'tier_enterprise',
|
||||
}
|
||||
|
||||
export const DEFAULT_PROVIDER: CloudProvider =
|
||||
process.env.NEXT_PUBLIC_ENVIRONMENT &&
|
||||
['staging', 'preview'].includes(process.env.NEXT_PUBLIC_ENVIRONMENT)
|
||||
? 'AWS_K8S'
|
||||
: 'AWS'
|
||||
export function useDefaultProvider() {
|
||||
const defaultProvider: CloudProvider =
|
||||
process.env.NEXT_PUBLIC_ENVIRONMENT &&
|
||||
['staging', 'preview'].includes(process.env.NEXT_PUBLIC_ENVIRONMENT)
|
||||
? 'AWS_K8S'
|
||||
: 'AWS'
|
||||
|
||||
const { infraCloudProviders: validCloudProviders } = useCustomContent(['infra:cloud_providers'])
|
||||
|
||||
if (validCloudProviders?.includes(defaultProvider)) {
|
||||
return defaultProvider
|
||||
}
|
||||
|
||||
return (validCloudProviders?.[0] ?? 'AWS') as CloudProvider
|
||||
}
|
||||
|
||||
export const PROVIDERS = {
|
||||
FLY: {
|
||||
@@ -60,6 +71,12 @@ export const PROVIDERS = {
|
||||
default_region: AWS_REGIONS_DEFAULT,
|
||||
regions: { ...AWS_REGIONS },
|
||||
},
|
||||
AWS_NIMBUS: {
|
||||
id: 'AWS_NIMBUS',
|
||||
name: 'AWS (Nimbus)',
|
||||
default_region: AWS_REGIONS_DEFAULT,
|
||||
regions: { ...AWS_REGIONS },
|
||||
},
|
||||
} as const
|
||||
|
||||
export const PROJECT_STATUS: {
|
||||
|
||||
@@ -62,6 +62,7 @@ describe('eszip-parser', () => {
|
||||
mockParser.parseBytes.mockResolvedValue(mockSpecifiers)
|
||||
mockParser.load.mockResolvedValue(undefined)
|
||||
mockParser.getModuleSource
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(mockModuleSource1)
|
||||
.mockResolvedValueOnce(mockModuleSource2)
|
||||
|
||||
@@ -70,12 +71,13 @@ describe('eszip-parser', () => {
|
||||
expect(Parser.createInstance).toHaveBeenCalledTimes(1)
|
||||
expect(mockParser.parseBytes).toHaveBeenCalledWith(mockBytes)
|
||||
expect(mockParser.load).toHaveBeenCalled()
|
||||
expect(result).toHaveLength(2)
|
||||
expect(result[0]).toEqual({
|
||||
expect(result.version).toEqual(0)
|
||||
expect(result.files).toHaveLength(2)
|
||||
expect(result.files[0]).toEqual({
|
||||
name: 'file1.ts',
|
||||
content: mockModuleSource1,
|
||||
})
|
||||
expect(result[1]).toEqual({
|
||||
expect(result.files[1]).toEqual({
|
||||
name: 'file2.ts',
|
||||
content: mockModuleSource2,
|
||||
})
|
||||
@@ -111,9 +113,10 @@ describe('eszip-parser', () => {
|
||||
|
||||
const result = await parseEszip(mockBytes)
|
||||
// Only file1.ts and file2.ts should be included
|
||||
expect(result).toHaveLength(2)
|
||||
expect(result[0].name).toBe('file1.ts')
|
||||
expect(result[1].name).toBe('file2.ts')
|
||||
expect(result.version).toEqual(0)
|
||||
expect(result.files).toHaveLength(2)
|
||||
expect(result.files[0].name).toBe('file1.ts')
|
||||
expect(result.files[1].name).toBe('file2.ts')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -63,8 +63,14 @@ export async function parseEszip(bytes: Uint8Array) {
|
||||
throw loadError
|
||||
}
|
||||
|
||||
// Extract version
|
||||
let version = parseInt(await parser.getModuleSource('---SUPABASE-ESZIP-VERSION-ESZIP---'))
|
||||
if (isNaN(version)) {
|
||||
version = 0
|
||||
}
|
||||
|
||||
// Extract files from the eszip
|
||||
const files = await extractEszip(parser, specifiers)
|
||||
const files = await extractEszip(parser, specifiers, version >= 2)
|
||||
|
||||
// Convert files to the expected format
|
||||
const responseFiles = await Promise.all(
|
||||
@@ -77,14 +83,17 @@ export async function parseEszip(bytes: Uint8Array) {
|
||||
})
|
||||
)
|
||||
|
||||
return responseFiles
|
||||
return {
|
||||
version,
|
||||
files: responseFiles,
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error in parseEszip:', error)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function extractEszip(parser: any, specifiers: string[]) {
|
||||
async function extractEszip(parser: any, specifiers: string[], isDeno2: boolean) {
|
||||
const files = []
|
||||
|
||||
// First, filter out the specifiers we want to keep
|
||||
@@ -114,9 +123,13 @@ async function extractEszip(parser: any, specifiers: string[]) {
|
||||
try {
|
||||
// Try to get the module source
|
||||
const moduleSource = await parser.getModuleSource(specifier)
|
||||
let qualifiedSpecifier = specifier
|
||||
|
||||
// Get the file path
|
||||
const filePath = url2path(specifier)
|
||||
if (isDeno2 && !specifier.startsWith('file://')) {
|
||||
qualifiedSpecifier = `file://${specifier}`
|
||||
}
|
||||
const filePath = url2path(qualifiedSpecifier)
|
||||
|
||||
// Create a file object
|
||||
const file = new File([moduleSource], filePath)
|
||||
|
||||
@@ -30,12 +30,12 @@ import timezone from 'dayjs/plugin/timezone'
|
||||
import utc from 'dayjs/plugin/utc'
|
||||
import Head from 'next/head'
|
||||
import { NuqsAdapter } from 'nuqs/adapters/next/pages'
|
||||
import { ErrorInfo } from 'react'
|
||||
import { ErrorInfo, useCallback } from 'react'
|
||||
import { ErrorBoundary } from 'react-error-boundary'
|
||||
|
||||
import {
|
||||
FeatureFlagProvider,
|
||||
getFlags as getConfigCatFlags,
|
||||
getFlags,
|
||||
TelemetryTagManager,
|
||||
ThemeProvider,
|
||||
useThemeSandbox,
|
||||
@@ -51,7 +51,7 @@ import { GlobalErrorBoundaryState } from 'components/ui/GlobalErrorBoundaryState
|
||||
import { useRootQueryClient } from 'data/query-client'
|
||||
import { customFont, sourceCodePro } from 'fonts'
|
||||
import { AuthProvider } from 'lib/auth'
|
||||
import { API_URL, BASE_PATH, IS_PLATFORM } from 'lib/constants'
|
||||
import { API_URL, BASE_PATH, IS_PLATFORM, useDefaultProvider } from 'lib/constants'
|
||||
import { ProfileProvider } from 'lib/profile'
|
||||
import { Telemetry } from 'lib/telemetry'
|
||||
import { AppPropsWithLayout } from 'types'
|
||||
@@ -100,6 +100,16 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
|
||||
|
||||
const isTestEnv = process.env.NEXT_PUBLIC_NODE_ENV === 'test'
|
||||
|
||||
const cloudProvider = useDefaultProvider()
|
||||
const getConfigCatFlags = useCallback(
|
||||
(userEmail?: string) => {
|
||||
const customAttributes = cloudProvider ? { cloud_provider: cloudProvider } : undefined
|
||||
|
||||
return getFlags(userEmail, customAttributes)
|
||||
},
|
||||
[cloudProvider]
|
||||
)
|
||||
|
||||
return (
|
||||
<ErrorBoundary FallbackComponent={GlobalErrorBoundaryState} onError={errorBoundaryHandler}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
|
||||
@@ -81,11 +81,9 @@ async function handlePost(req: NextApiRequest, res: NextApiResponse) {
|
||||
const uint8Array = new Uint8Array(arrayBuffer)
|
||||
|
||||
// Parse the eszip file using our utility
|
||||
const files = await parseEszip(uint8Array)
|
||||
const parsed = await parseEszip(uint8Array)
|
||||
|
||||
return res.status(200).json({
|
||||
files,
|
||||
})
|
||||
return res.status(200).json(parsed)
|
||||
} catch (error) {
|
||||
console.error('Error processing edge function body:', error)
|
||||
return res.status(500).json({ error: 'Internal server error' })
|
||||
|
||||
@@ -224,7 +224,7 @@ const CreateProject = () => {
|
||||
<div className="py-2">
|
||||
<Input
|
||||
id="dbPass"
|
||||
label="Database Password"
|
||||
label="Database password"
|
||||
type="password"
|
||||
placeholder="Type in a strong password"
|
||||
value={dbPass}
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
} from 'data/projects/project-create-mutation'
|
||||
import { useProjectsQuery } from 'data/projects/projects-query'
|
||||
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
|
||||
import { useCustomContent } from 'hooks/custom-content/useCustomContent'
|
||||
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
|
||||
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
|
||||
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
|
||||
@@ -57,11 +58,11 @@ import { getCloudProviderArchitecture } from 'lib/cloudprovider-utils'
|
||||
import {
|
||||
AWS_REGIONS_DEFAULT,
|
||||
DEFAULT_MINIMUM_PASSWORD_STRENGTH,
|
||||
DEFAULT_PROVIDER,
|
||||
FLY_REGIONS_DEFAULT,
|
||||
MANAGED_BY,
|
||||
PROJECT_STATUS,
|
||||
PROVIDERS,
|
||||
useDefaultProvider,
|
||||
} from 'lib/constants'
|
||||
import passwordStrength from 'lib/password-strength'
|
||||
import { generateStrongPassword } from 'lib/project'
|
||||
@@ -141,6 +142,8 @@ const Wizard: NextPageWithLayout = () => {
|
||||
|
||||
const showAdvancedConfig = useIsFeatureEnabled('project_creation:show_advanced_config')
|
||||
|
||||
const { infraCloudProviders: validCloudProviders } = useCustomContent(['infra:cloud_providers'])
|
||||
|
||||
// This is to make the database.new redirect work correctly. The database.new redirect should be set to supabase.com/dashboard/new/last-visited-org
|
||||
if (slug === 'last-visited-org') {
|
||||
if (lastVisitedOrganization) {
|
||||
@@ -221,9 +224,11 @@ const Wizard: NextPageWithLayout = () => {
|
||||
project.organization_id === currentOrg?.id && project.status !== PROJECT_STATUS.INACTIVE
|
||||
) ?? []
|
||||
|
||||
const defaultProvider = useDefaultProvider()
|
||||
|
||||
const { data: _defaultRegion, error: defaultRegionError } = useDefaultRegionQuery(
|
||||
{
|
||||
cloudProvider: PROVIDERS[DEFAULT_PROVIDER].id,
|
||||
cloudProvider: PROVIDERS[defaultProvider].id,
|
||||
},
|
||||
{
|
||||
enabled: !smartRegionEnabled,
|
||||
@@ -239,7 +244,7 @@ const Wizard: NextPageWithLayout = () => {
|
||||
useOrganizationAvailableRegionsQuery(
|
||||
{
|
||||
slug: slug,
|
||||
cloudProvider: PROVIDERS[DEFAULT_PROVIDER].id,
|
||||
cloudProvider: PROVIDERS[defaultProvider].id,
|
||||
},
|
||||
{
|
||||
enabled: smartRegionEnabled,
|
||||
@@ -304,7 +309,7 @@ const Wizard: NextPageWithLayout = () => {
|
||||
organization: slug,
|
||||
projectName: projectName || '',
|
||||
postgresVersion: '',
|
||||
cloudProvider: PROVIDERS[DEFAULT_PROVIDER].id,
|
||||
cloudProvider: PROVIDERS[defaultProvider].id,
|
||||
dbPass: '',
|
||||
dbPassStrength: 0,
|
||||
dbRegion: defaultRegion || undefined,
|
||||
@@ -455,7 +460,7 @@ const Wizard: NextPageWithLayout = () => {
|
||||
|
||||
useEffect(() => {
|
||||
if (regionError) {
|
||||
form.setValue('dbRegion', PROVIDERS[DEFAULT_PROVIDER].default_region.displayName)
|
||||
form.setValue('dbRegion', PROVIDERS[defaultProvider].default_region.displayName)
|
||||
}
|
||||
}, [regionError])
|
||||
|
||||
@@ -489,7 +494,7 @@ const Wizard: NextPageWithLayout = () => {
|
||||
canCreateProject &&
|
||||
additionalMonthlySpend > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span>Additional Costs</span>
|
||||
<span>Additional costs</span>
|
||||
<div className="text-brand flex gap-1 items-center font-mono font-medium">
|
||||
<span>${additionalMonthlySpend}/m</span>
|
||||
<InfoTooltip side="top" className="max-w-[450px] p-0">
|
||||
@@ -707,15 +712,20 @@ const Wizard: NextPageWithLayout = () => {
|
||||
</FormControl_Shadcn_>
|
||||
<SelectContent_Shadcn_>
|
||||
<SelectGroup_Shadcn_>
|
||||
{Object.values(PROVIDERS).map((providerObj) => {
|
||||
const label = providerObj['name']
|
||||
const value = providerObj['id']
|
||||
return (
|
||||
<SelectItem_Shadcn_ key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem_Shadcn_>
|
||||
{Object.values(PROVIDERS)
|
||||
.filter(
|
||||
(provider) =>
|
||||
validCloudProviders?.includes(provider.id) ?? true
|
||||
)
|
||||
})}
|
||||
.map((providerObj) => {
|
||||
const label = providerObj['name']
|
||||
const value = providerObj['id']
|
||||
return (
|
||||
<SelectItem_Shadcn_ key={value} value={value}>
|
||||
{label}
|
||||
</SelectItem_Shadcn_>
|
||||
)
|
||||
})}
|
||||
</SelectGroup_Shadcn_>
|
||||
</SelectContent_Shadcn_>
|
||||
</Select_Shadcn_>
|
||||
@@ -735,7 +745,7 @@ const Wizard: NextPageWithLayout = () => {
|
||||
layout="horizontal"
|
||||
label={
|
||||
<div className="flex flex-col gap-y-4">
|
||||
<span>Compute Size</span>
|
||||
<span>Compute size</span>
|
||||
|
||||
<div className="flex flex-col gap-y-2">
|
||||
<Link
|
||||
@@ -744,7 +754,7 @@ const Wizard: NextPageWithLayout = () => {
|
||||
href="https://supabase.com/docs/guides/platform/compute-add-ons"
|
||||
>
|
||||
<div className="flex items-center space-x-2 opacity-75 hover:opacity-100 transition">
|
||||
<p className="text-sm m-0">Compute Add-Ons</p>
|
||||
<p className="text-sm m-0">Compute add-ons</p>
|
||||
<ExternalLink size={16} strokeWidth={1.5} />
|
||||
</div>
|
||||
</Link>
|
||||
@@ -754,7 +764,7 @@ const Wizard: NextPageWithLayout = () => {
|
||||
href="https://supabase.com/docs/guides/platform/manage-your-usage/compute"
|
||||
>
|
||||
<div className="flex items-center space-x-2 opacity-75 hover:opacity-100 transition">
|
||||
<p className="text-sm m-0">Compute Billing</p>
|
||||
<p className="text-sm m-0">Compute billing</p>
|
||||
<ExternalLink size={16} strokeWidth={1.5} />
|
||||
</div>
|
||||
</Link>
|
||||
@@ -845,7 +855,7 @@ const Wizard: NextPageWithLayout = () => {
|
||||
|
||||
return (
|
||||
<FormItemLayout
|
||||
label="Database Password"
|
||||
label="Database password"
|
||||
layout="horizontal"
|
||||
description={
|
||||
<>
|
||||
@@ -926,7 +936,7 @@ const Wizard: NextPageWithLayout = () => {
|
||||
<FormItemLayout
|
||||
label="Custom Postgres version"
|
||||
layout="horizontal"
|
||||
description="Specify a custom version of Postgres (Defaults to the latest). This is only applicable for local/staging projects"
|
||||
description="Specify a custom version of Postgres (defaults to the latest). This is only applicable for local/staging projects."
|
||||
>
|
||||
<FormControl_Shadcn_>
|
||||
<Input_Shadcn_
|
||||
|
||||
@@ -35,7 +35,7 @@ const CodePage = () => {
|
||||
|
||||
const { data: selectedFunction } = useEdgeFunctionQuery({ projectRef: ref, slug: functionSlug })
|
||||
const {
|
||||
data: functionFiles,
|
||||
data: functionBody,
|
||||
isLoading: isLoadingFiles,
|
||||
isError: isErrorLoadingFiles,
|
||||
isSuccess: isSuccessLoadingFiles,
|
||||
@@ -123,15 +123,29 @@ const CodePage = () => {
|
||||
}
|
||||
}
|
||||
|
||||
function getBasePath(entrypoint: string | undefined): string {
|
||||
function getBasePath(
|
||||
entrypoint: string | undefined,
|
||||
fileNames: string[],
|
||||
version: number
|
||||
): string {
|
||||
if (!entrypoint) {
|
||||
return '/'
|
||||
}
|
||||
|
||||
let qualifiedEntrypoint = entrypoint
|
||||
|
||||
if (version >= 2) {
|
||||
const candidate = fileNames.find((name) => entrypoint.endsWith(name))
|
||||
if (candidate) {
|
||||
qualifiedEntrypoint = `file://${candidate}`
|
||||
} else {
|
||||
qualifiedEntrypoint = entrypoint
|
||||
}
|
||||
}
|
||||
try {
|
||||
return dirname(new URL(entrypoint).pathname)
|
||||
return dirname(new URL(qualifiedEntrypoint).pathname)
|
||||
} catch (e) {
|
||||
console.error('Failed to parse entrypoint', entrypoint)
|
||||
console.error('Failed to parse entrypoint', qualifiedEntrypoint)
|
||||
return '/'
|
||||
}
|
||||
}
|
||||
@@ -155,9 +169,13 @@ const CodePage = () => {
|
||||
|
||||
useEffect(() => {
|
||||
// Set files from API response when available
|
||||
if (selectedFunction?.entrypoint_path && functionFiles) {
|
||||
const base_path = getBasePath(selectedFunction?.entrypoint_path)
|
||||
const filesWithRelPath = functionFiles
|
||||
if (selectedFunction?.entrypoint_path && functionBody) {
|
||||
const base_path = getBasePath(
|
||||
selectedFunction?.entrypoint_path,
|
||||
functionBody.files.map((file) => file.name),
|
||||
functionBody.version
|
||||
)
|
||||
const filesWithRelPath = functionBody.files
|
||||
// ignore empty files
|
||||
.filter((file: { name: string; content: string }) => !!file.content.length)
|
||||
// set file paths relative to entrypoint
|
||||
@@ -192,7 +210,7 @@ const CodePage = () => {
|
||||
})
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [functionFiles])
|
||||
}, [functionBody])
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
|
||||
@@ -4,7 +4,7 @@ import dayjs from 'dayjs'
|
||||
import { ArrowRight, RefreshCw } from 'lucide-react'
|
||||
import { useState } from 'react'
|
||||
|
||||
import ReportChart from 'components/interfaces/Reports/ReportChart'
|
||||
import { ReportChart } from 'components/interfaces/Reports/ReportChart'
|
||||
import ReportHeader from 'components/interfaces/Reports/ReportHeader'
|
||||
import ReportPadding from 'components/interfaces/Reports/ReportPadding'
|
||||
import ReportStickyNav from 'components/interfaces/Reports/ReportStickyNav'
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useEffect, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
import { useFlag, useParams } from 'common'
|
||||
import ReportChart from 'components/interfaces/Reports/ReportChart'
|
||||
import { ReportChart } from 'components/interfaces/Reports/ReportChart'
|
||||
import ReportHeader from 'components/interfaces/Reports/ReportHeader'
|
||||
import ReportPadding from 'components/interfaces/Reports/ReportPadding'
|
||||
import { REPORT_DATERANGE_HELPER_LABELS } from 'components/interfaces/Reports/Reports.constants'
|
||||
@@ -22,7 +22,7 @@ import Table from 'components/to-be-cleaned/Table'
|
||||
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
|
||||
import ChartHandler from 'components/ui/Charts/ChartHandler'
|
||||
import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'
|
||||
import ComposedChartHandler from 'components/ui/Charts/ComposedChartHandler'
|
||||
import { LazyComposedChartHandler } from 'components/ui/Charts/ComposedChartHandler'
|
||||
import { ReportSettings } from 'components/ui/Charts/ReportSettings'
|
||||
import GrafanaPromoBanner from 'components/ui/GrafanaPromoBanner'
|
||||
import Panel from 'components/ui/Panel'
|
||||
@@ -269,7 +269,7 @@ const DatabaseUsage = () => {
|
||||
orgPlan?.id &&
|
||||
(showChartsV2
|
||||
? REPORT_ATTRIBUTES_V2.filter((chart) => !chart.hide).map((chart) => (
|
||||
<ComposedChartHandler
|
||||
<LazyComposedChartHandler
|
||||
key={chart.id}
|
||||
{...chart}
|
||||
attributes={chart.attributes as MultiAttribute[]}
|
||||
@@ -288,7 +288,7 @@ const DatabaseUsage = () => {
|
||||
))
|
||||
: REPORT_ATTRIBUTES.filter((chart) => !chart.hide).map((chart, i) =>
|
||||
chart.availableIn?.includes(orgPlan?.id) ? (
|
||||
<ComposedChartHandler
|
||||
<LazyComposedChartHandler
|
||||
key={chart.id}
|
||||
{...chart}
|
||||
attributes={chart.attributes as MultiAttribute[]}
|
||||
@@ -310,7 +310,6 @@ const DatabaseUsage = () => {
|
||||
<ReportChart
|
||||
key={`${chart.id}-${i}`}
|
||||
chart={chart}
|
||||
className="!mb-0"
|
||||
interval={selectedDateRange.interval}
|
||||
startDate={selectedDateRange?.period_start?.date}
|
||||
endDate={selectedDateRange?.period_end?.date}
|
||||
|
||||
@@ -2,10 +2,10 @@ import { useQueryClient } from '@tanstack/react-query'
|
||||
import { useParams } from 'common'
|
||||
import dayjs from 'dayjs'
|
||||
import { ArrowRight, ChevronDown, RefreshCw } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
|
||||
import { Label } from '@ui/components/shadcn/ui/label'
|
||||
import ReportChart from 'components/interfaces/Reports/ReportChart'
|
||||
import { ReportChartV2 } from 'components/interfaces/Reports/v2/ReportChartV2'
|
||||
import ReportHeader from 'components/interfaces/Reports/ReportHeader'
|
||||
import ReportPadding from 'components/interfaces/Reports/ReportPadding'
|
||||
import ReportStickyNav from 'components/interfaces/Reports/ReportStickyNav'
|
||||
@@ -14,17 +14,19 @@ import DefaultLayout from 'components/layouts/DefaultLayout'
|
||||
import ReportsLayout from 'components/layouts/ReportsLayout/ReportsLayout'
|
||||
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
|
||||
import { Button, Checkbox, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from 'ui'
|
||||
import { useChartHoverState } from 'components/ui/Charts/useChartHoverState'
|
||||
|
||||
import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
|
||||
import { getEdgeFunctionReportAttributes } from 'data/reports/edgefn-charts'
|
||||
import { edgeFunctionReports } from 'data/reports/v2/edge-functions.config'
|
||||
|
||||
import { REPORT_DATERANGE_HELPER_LABELS } from 'components/interfaces/Reports/Reports.constants'
|
||||
import UpgradePrompt from 'components/interfaces/Settings/Logs/UpgradePrompt'
|
||||
import { useReportDateRange } from 'hooks/misc/useReportDateRange'
|
||||
|
||||
import type { NextPageWithLayout } from 'types'
|
||||
import { ReportSettings } from 'components/ui/Charts/ReportSettings'
|
||||
|
||||
const EdgeFunctionsReport: NextPageWithLayout = () => {
|
||||
const EdgeFunctionsReportV2: NextPageWithLayout = () => {
|
||||
return (
|
||||
<ReportPadding>
|
||||
<EdgeFunctionsUsage />
|
||||
@@ -32,20 +34,23 @@ const EdgeFunctionsReport: NextPageWithLayout = () => {
|
||||
)
|
||||
}
|
||||
|
||||
EdgeFunctionsReport.getLayout = (page) => (
|
||||
EdgeFunctionsReportV2.getLayout = (page) => (
|
||||
<DefaultLayout>
|
||||
<ReportsLayout title="Edge Functions">{page}</ReportsLayout>
|
||||
</DefaultLayout>
|
||||
)
|
||||
|
||||
export type UpdateDateRange = (from: string, to: string) => void
|
||||
export default EdgeFunctionsReport
|
||||
export default EdgeFunctionsReportV2
|
||||
|
||||
const EdgeFunctionsUsage = () => {
|
||||
const { ref } = useParams()
|
||||
const { data: functions, isLoading: isLoadingFunctions } = useEdgeFunctionsQuery({
|
||||
projectRef: ref,
|
||||
})
|
||||
|
||||
const chartSyncId = `edge-functions-${ref}`
|
||||
useChartHoverState(chartSyncId)
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const [functionIds, setFunctionIds] = useState<string[]>([])
|
||||
const [tempFunctionIds, setTempFunctionIds] = useState<string[]>(functionIds)
|
||||
@@ -61,8 +66,6 @@ const EdgeFunctionsUsage = () => {
|
||||
updateDateRange,
|
||||
datePickerValue,
|
||||
datePickerHelpers,
|
||||
isOrgPlanLoading,
|
||||
orgPlan,
|
||||
showUpgradePrompt,
|
||||
setShowUpgradePrompt,
|
||||
handleDatePickerChange,
|
||||
@@ -71,21 +74,27 @@ const EdgeFunctionsUsage = () => {
|
||||
const queryClient = useQueryClient()
|
||||
const [isRefreshing, setIsRefreshing] = useState(false)
|
||||
|
||||
const EDGEFN_CHARTS = getEdgeFunctionReportAttributes()
|
||||
const reportConfig = useMemo(() => {
|
||||
return edgeFunctionReports({
|
||||
projectRef: ref!,
|
||||
functions: functions ?? [],
|
||||
startDate: selectedDateRange?.period_start?.date ?? '',
|
||||
endDate: selectedDateRange?.period_end?.date ?? '',
|
||||
interval: selectedDateRange?.interval ?? 'minute',
|
||||
filters: {
|
||||
functionIds,
|
||||
},
|
||||
})
|
||||
}, [ref, functions, selectedDateRange, functionIds])
|
||||
|
||||
const onRefreshReport = async () => {
|
||||
if (!selectedDateRange) return
|
||||
|
||||
setIsRefreshing(true)
|
||||
queryClient.invalidateQueries(['edge-function-report', ref])
|
||||
queryClient.invalidateQueries(['report-v2'])
|
||||
setTimeout(() => setIsRefreshing(false), 1000)
|
||||
}
|
||||
|
||||
if (!ref) {
|
||||
// Prevent rendering charts until the ref is available
|
||||
return <></>
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ReportHeader title="Edge Functions" showDatabaseSelector={false} />
|
||||
@@ -101,6 +110,8 @@ const EdgeFunctionsUsage = () => {
|
||||
tooltip={{ content: { side: 'bottom', text: 'Refresh report' } }}
|
||||
onClick={onRefreshReport}
|
||||
/>
|
||||
<ReportSettings chartId="edge-functions-charts" />
|
||||
|
||||
<LogsDatePicker
|
||||
onSubmit={handleDatePickerChange}
|
||||
value={datePickerValue}
|
||||
@@ -214,17 +225,21 @@ const EdgeFunctionsUsage = () => {
|
||||
>
|
||||
<div className="mt-8 flex flex-col gap-4">
|
||||
{selectedDateRange &&
|
||||
EDGEFN_CHARTS.filter((attr) => !attr.hide).map((attr, i) => (
|
||||
<ReportChart
|
||||
key={`${attr.id}-${i}`}
|
||||
chart={attr}
|
||||
interval={selectedDateRange.interval}
|
||||
startDate={selectedDateRange?.period_start?.date}
|
||||
endDate={selectedDateRange?.period_end?.date}
|
||||
updateDateRange={updateDateRange}
|
||||
functionIds={functionIds}
|
||||
/>
|
||||
))}
|
||||
reportConfig
|
||||
.filter((report) => !report.hide)
|
||||
.map((report) => (
|
||||
<ReportChartV2
|
||||
key={`${report.id}`}
|
||||
report={report}
|
||||
projectRef={ref!}
|
||||
interval={selectedDateRange.interval}
|
||||
startDate={selectedDateRange?.period_start?.date}
|
||||
endDate={selectedDateRange?.period_end?.date}
|
||||
updateDateRange={updateDateRange}
|
||||
functionIds={functionIds}
|
||||
syncId={chartSyncId}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</ReportStickyNav>
|
||||
</>
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
TopApiRoutesRenderer,
|
||||
TotalRequestsChartRenderer,
|
||||
} from 'components/interfaces/Reports/renderers/ApiRenderers'
|
||||
import ComposedChartHandler from 'components/ui/Charts/ComposedChartHandler'
|
||||
import { LazyComposedChartHandler } from 'components/ui/Charts/ComposedChartHandler'
|
||||
import ReportWidget from 'components/interfaces/Reports/ReportWidget'
|
||||
import ReportFilterBar from 'components/interfaces/Reports/ReportFilterBar'
|
||||
|
||||
@@ -187,7 +187,7 @@ const RealtimeUsage = () => {
|
||||
>
|
||||
{selectedDateRange &&
|
||||
REALTIME_REPORT_ATTRIBUTES.filter((chart) => !chart.hide).map((chart) => (
|
||||
<ComposedChartHandler
|
||||
<LazyComposedChartHandler
|
||||
key={chart.id}
|
||||
{...chart}
|
||||
attributes={chart.attributes as MultiAttribute[]}
|
||||
|
||||
@@ -1654,6 +1654,10 @@ function createStorageExplorerState({
|
||||
const currentColumnItems = currentColumn.items.filter(
|
||||
(item) => item.status !== STORAGE_ROW_STATUS.EDITING
|
||||
)
|
||||
// [Joshen] JFYI storage does support folders of the same name with different casing
|
||||
// but its an issue with the List V1 endpoint that's causing an issue with fetching contents
|
||||
// for folders of the same name with different casing
|
||||
// We should remove this check once all projects are on the List V2 endpoint
|
||||
const hasSameNameInColumn =
|
||||
currentColumnItems.filter((item) => item.name.toLowerCase() === name.toLowerCase()).length >
|
||||
0
|
||||
|
||||
@@ -2,8 +2,235 @@ import {
|
||||
checkForILIKEClause,
|
||||
checkForWildcard,
|
||||
checkForWithClause,
|
||||
fillTimeseries,
|
||||
unixMicroToIsoTimestamp,
|
||||
} from 'components/interfaces/Settings/Logs/Logs.utils'
|
||||
import { describe, test, expect } from 'vitest'
|
||||
import dayjs from 'dayjs'
|
||||
import utc from 'dayjs/plugin/utc'
|
||||
|
||||
dayjs.extend(utc)
|
||||
|
||||
describe('fillTimeseries', () => {
|
||||
test('should return empty array for empty data without min/max', () => {
|
||||
const result = fillTimeseries([], 'timestamp', 'value', 0)
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
test('should return empty array for empty data with min/max', () => {
|
||||
const min = '2023-01-01T00:00:00.000Z'
|
||||
const max = '2023-01-01T01:00:00.000Z'
|
||||
const result = fillTimeseries([], 'timestamp', 'value', 0, min, max)
|
||||
|
||||
// When min/max are provided, the function fills the time range with default values
|
||||
// This creates 61 data points (one for each minute from 00:00 to 01:00)
|
||||
expect(result).toHaveLength(61)
|
||||
expect(result[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', value: 0 })
|
||||
expect(result[60]).toEqual({ timestamp: '2023-01-01T01:00:00.000Z', value: 0 })
|
||||
})
|
||||
|
||||
test('should normalize timestamps when data exceeds minPointsToFill', () => {
|
||||
const data = [
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', value: 1 },
|
||||
{ timestamp: '2023-01-01T00:01:00.000Z', value: 2 },
|
||||
{ timestamp: '2023-01-01T00:02:00.000Z', value: 3 },
|
||||
{ timestamp: '2023-01-01T00:03:00.000Z', value: 4 },
|
||||
{ timestamp: '2023-01-01T00:04:00.000Z', value: 5 },
|
||||
{ timestamp: '2023-01-01T00:05:00.000Z', value: 6 },
|
||||
{ timestamp: '2023-01-01T00:06:00.000Z', value: 7 },
|
||||
{ timestamp: '2023-01-01T00:07:00.000Z', value: 8 },
|
||||
{ timestamp: '2023-01-01T00:08:00.000Z', value: 9 },
|
||||
{ timestamp: '2023-01-01T00:09:00.000Z', value: 10 },
|
||||
{ timestamp: '2023-01-01T00:10:00.000Z', value: 11 },
|
||||
{ timestamp: '2023-01-01T00:11:00.000Z', value: 12 },
|
||||
{ timestamp: '2023-01-01T00:12:00.000Z', value: 13 },
|
||||
{ timestamp: '2023-01-01T00:13:00.000Z', value: 14 },
|
||||
{ timestamp: '2023-01-01T00:14:00.000Z', value: 15 },
|
||||
{ timestamp: '2023-01-01T00:15:00.000Z', value: 16 },
|
||||
{ timestamp: '2023-01-01T00:16:00.000Z', value: 17 },
|
||||
{ timestamp: '2023-01-01T00:17:00.000Z', value: 18 },
|
||||
{ timestamp: '2023-01-01T00:18:00.000Z', value: 19 },
|
||||
{ timestamp: '2023-01-01T00:19:00.000Z', value: 20 },
|
||||
{ timestamp: '2023-01-01T00:20:00.000Z', value: 21 },
|
||||
]
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 20)
|
||||
|
||||
// Should return normalized data without filling gaps
|
||||
expect(result).toHaveLength(21)
|
||||
result.forEach((item) => {
|
||||
expect(item.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)
|
||||
})
|
||||
})
|
||||
|
||||
test('should fill gaps in sparse data with 1-minute intervals', () => {
|
||||
const min = '2023-01-01T00:00:00.000Z'
|
||||
const max = '2023-01-01T00:04:00.000Z'
|
||||
const data = [
|
||||
{ timestamp: '2023-01-01T00:01:00.000Z', value: 10 },
|
||||
{ timestamp: '2023-01-01T00:03:00.000Z', value: 30 },
|
||||
]
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '2m')
|
||||
|
||||
expect(result).toHaveLength(5)
|
||||
const sortedResult = result.sort((a, b) => a.timestamp.localeCompare(b.timestamp))
|
||||
|
||||
expect(sortedResult[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', value: 0 })
|
||||
expect(sortedResult[1]).toEqual({ timestamp: '2023-01-01T00:01:00.000Z', value: 10 })
|
||||
expect(sortedResult[2]).toEqual({ timestamp: '2023-01-01T00:02:00.000Z', value: 0 })
|
||||
expect(sortedResult[3]).toEqual({ timestamp: '2023-01-01T00:03:00.000Z', value: 30 })
|
||||
expect(sortedResult[4]).toEqual({ timestamp: '2023-01-01T00:04:00.000Z', value: 0 })
|
||||
})
|
||||
|
||||
test('should handle multiple value keys', () => {
|
||||
const min = '2023-01-01T00:00:00.000Z'
|
||||
const max = '2023-01-01T00:02:00.000Z'
|
||||
const data = [{ timestamp: '2023-01-01T00:01:00.000Z', count1: 10, count2: 100 }]
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', ['count1', 'count2'], 5, min, max, 20, '1m')
|
||||
|
||||
expect(result).toHaveLength(3)
|
||||
const sortedResult = result.sort((a, b) => a.timestamp.localeCompare(b.timestamp))
|
||||
|
||||
expect(sortedResult[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', count1: 5, count2: 5 })
|
||||
expect(sortedResult[1]).toEqual({
|
||||
timestamp: '2023-01-01T00:01:00.000Z',
|
||||
count1: 10,
|
||||
count2: 100,
|
||||
})
|
||||
expect(sortedResult[2]).toEqual({ timestamp: '2023-01-01T00:02:00.000Z', count1: 5, count2: 5 })
|
||||
})
|
||||
|
||||
test('should handle different interval formats', () => {
|
||||
const min = '2023-01-01T00:00:00.000Z'
|
||||
const max = '2023-01-01T00:10:00.000Z'
|
||||
const data = [{ timestamp: '2023-01-01T00:05:00.000Z', value: 50 }]
|
||||
|
||||
// Test 5-minute intervals: 00:00, 00:05, 00:10 = 3 points
|
||||
const result5m = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '5m')
|
||||
expect(result5m).toHaveLength(3)
|
||||
|
||||
// Test 2-minute intervals: 00:00, 00:02, 00:04, 00:05, 00:06, 00:08, 00:10 = 7 points
|
||||
const result2m = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '2m')
|
||||
console.log(
|
||||
'2m intervals:',
|
||||
result2m.map((r) => r.timestamp)
|
||||
)
|
||||
expect(result2m).toHaveLength(7)
|
||||
|
||||
// Test 1-hour intervals: 00:00, 01:00, 02:00 with existing data at 00:05 = 4 points
|
||||
const maxHour = '2023-01-01T02:00:00.000Z'
|
||||
const result1h = fillTimeseries(data, 'timestamp', 'value', 0, min, maxHour, 20, '1h')
|
||||
expect(result1h).toHaveLength(4)
|
||||
})
|
||||
|
||||
test('should handle microsecond timestamps correctly', () => {
|
||||
const now = dayjs.utc('2023-01-01T00:00:00.000Z')
|
||||
const data = [
|
||||
{ timestamp: now.valueOf() * 1000, value: 1 },
|
||||
{ timestamp: now.add(1, 'minute').valueOf() * 1000, value: 2 },
|
||||
]
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 1)
|
||||
|
||||
expect(result).toHaveLength(2)
|
||||
result.forEach((item) => {
|
||||
expect(item.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)
|
||||
})
|
||||
})
|
||||
|
||||
test('should handle mixed timestamp formats', () => {
|
||||
const data = [
|
||||
{ timestamp: '2023-01-01T00:00:00.000Z', value: 1 },
|
||||
{ timestamp: dayjs.utc('2023-01-01T00:01:00.000Z').valueOf() * 1000, value: 2 },
|
||||
{ timestamp: '2023-01-01T00:02:00.000Z', value: 3 },
|
||||
]
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 1)
|
||||
|
||||
expect(result).toHaveLength(3)
|
||||
result.forEach((item) => {
|
||||
expect(item.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)
|
||||
})
|
||||
})
|
||||
|
||||
test('should not fill gaps when data is dense enough', () => {
|
||||
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||
timestamp: dayjs.utc('2023-01-01T00:00:00.000Z').add(i, 'minute').toISOString(),
|
||||
value: i,
|
||||
}))
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 20)
|
||||
|
||||
expect(result).toHaveLength(25)
|
||||
expect(result).toEqual(data)
|
||||
})
|
||||
|
||||
test('should handle edge case with single data point', () => {
|
||||
const data = [{ timestamp: '2023-01-01T00:00:00.000Z', value: 1 }]
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0)
|
||||
|
||||
expect(result).toEqual(data)
|
||||
})
|
||||
|
||||
test('should handle edge case with single data point and min/max', () => {
|
||||
const min = '2023-01-01T00:00:00.000Z'
|
||||
const max = '2023-01-01T00:02:00.000Z'
|
||||
const data = [{ timestamp: '2023-01-01T00:01:00.000Z', value: 1 }]
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '1m')
|
||||
|
||||
expect(result).toHaveLength(3)
|
||||
const sortedResult = result.sort((a, b) => a.timestamp.localeCompare(b.timestamp))
|
||||
|
||||
expect(sortedResult[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', value: 0 })
|
||||
expect(sortedResult[1]).toEqual({ timestamp: '2023-01-01T00:01:00.000Z', value: 1 })
|
||||
expect(sortedResult[2]).toEqual({ timestamp: '2023-01-01T00:02:00.000Z', value: 0 })
|
||||
})
|
||||
|
||||
test('should handle invalid interval format gracefully', () => {
|
||||
const min = '2023-01-01T00:00:00.000Z'
|
||||
const max = '2023-01-01T00:02:00.000Z'
|
||||
const data = [{ timestamp: '2023-01-01T00:01:00.000Z', value: 1 }]
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, 'invalid')
|
||||
|
||||
// Should fall back to default behavior
|
||||
expect(result.length).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
test('should preserve all properties of original data', () => {
|
||||
const data = [
|
||||
{
|
||||
timestamp: '2023-01-01T00:00:00.000Z',
|
||||
value: 1,
|
||||
extra: 'data',
|
||||
nested: { prop: 'value' },
|
||||
},
|
||||
]
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', 'value', 0)
|
||||
|
||||
expect(result[0]).toEqual(data[0])
|
||||
expect(result[0].extra).toBe('data')
|
||||
expect(result[0].nested).toEqual({ prop: 'value' })
|
||||
})
|
||||
|
||||
test('should handle empty value keys array', () => {
|
||||
const min = '2023-01-01T00:00:00.000Z'
|
||||
const max = '2023-01-01T00:01:00.000Z'
|
||||
const data = [{ timestamp: '2023-01-01T00:00:30.000Z', value: 1 }]
|
||||
|
||||
const result = fillTimeseries(data, 'timestamp', [], 0, min, max, 20, '30s')
|
||||
|
||||
expect(result).toHaveLength(3)
|
||||
result.forEach((item) => {
|
||||
expect(item).toHaveProperty('timestamp')
|
||||
expect(item).not.toHaveProperty('value')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('checkForWithClause', () => {
|
||||
test('basic queries', () => {
|
||||
|
||||
@@ -4,6 +4,14 @@ import { createDynamicRouteParser } from 'next-router-mock/dist/dynamic-routes'
|
||||
import { afterAll, afterEach, beforeAll, vi } from 'vitest'
|
||||
import { routerMock } from './lib/route-mock'
|
||||
import { mswServer } from './lib/msw'
|
||||
import dayjs from 'dayjs'
|
||||
import utc from 'dayjs/plugin/utc'
|
||||
import timezone from 'dayjs/plugin/timezone'
|
||||
import relativeTime from 'dayjs/plugin/relativeTime'
|
||||
|
||||
dayjs.extend(utc)
|
||||
dayjs.extend(timezone)
|
||||
dayjs.extend(relativeTime)
|
||||
|
||||
// Uncomment this if HTML in errors are being annoying.
|
||||
//
|
||||
@@ -38,7 +46,7 @@ beforeAll(() => {
|
||||
vi.mock('next/compat/router', () => require('next-router-mock'))
|
||||
|
||||
// Mock the useParams hook from common module globally
|
||||
vi.mock('common', async (importOriginal) => {
|
||||
vi.mock('common', async (importOriginal: any) => {
|
||||
const actual = await importOriginal()
|
||||
return {
|
||||
...(typeof actual === 'object' ? actual : {}),
|
||||
|
||||
@@ -1,527 +1,43 @@
|
||||
|
||||
// @ts-nocheck
|
||||
// This file is autogenerated by scripts/build-registry.ts
|
||||
// This file is autogenerated by scripts/build-registry.mts
|
||||
// Do not edit this file directly.
|
||||
import * as React from "react"
|
||||
|
||||
export const Index: Record<string, any> = {
|
||||
export const Index = {
|
||||
"default": {
|
||||
|
||||
"password-based-auth-nextjs": {
|
||||
name: "password-based-auth-nextjs",
|
||||
type: "registry:block",
|
||||
registryDependencies: ["button","card","input","label"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/password-based-auth-nextjs/app/auth/login/page.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/password-based-auth-nextjs/app/auth/login/page.tsx","registry/default/blocks/password-based-auth-nextjs/app/auth/error/page.tsx","registry/default/blocks/password-based-auth-nextjs/app/protected/page.tsx","registry/default/blocks/password-based-auth-nextjs/app/auth/confirm/route.ts","registry/default/blocks/password-based-auth-nextjs/components/login-form.tsx","registry/default/blocks/password-based-auth-nextjs/middleware.ts","registry/default/blocks/password-based-auth-nextjs/app/auth/sign-up/page.tsx","registry/default/blocks/password-based-auth-nextjs/app/auth/sign-up-success/page.tsx","registry/default/blocks/password-based-auth-nextjs/components/sign-up-form.tsx","registry/default/blocks/password-based-auth-nextjs/app/auth/forgot-password/page.tsx","registry/default/blocks/password-based-auth-nextjs/app/auth/update-password/page.tsx","registry/default/blocks/password-based-auth-nextjs/components/forgot-password-form.tsx","registry/default/blocks/password-based-auth-nextjs/components/update-password-form.tsx","registry/default/blocks/password-based-auth-nextjs/components/logout-button.tsx","registry/default/clients/nextjs/lib/supabase/client.ts","registry/default/clients/nextjs/lib/supabase/middleware.ts","registry/default/clients/nextjs/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"password-based-auth-react": {
|
||||
name: "password-based-auth-react",
|
||||
type: "registry:block",
|
||||
registryDependencies: ["button","card","input","label"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/password-based-auth-react/components/login-form.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/password-based-auth-react/components/login-form.tsx","registry/default/blocks/password-based-auth-react/components/sign-up-form.tsx","registry/default/blocks/password-based-auth-react/components/forgot-password-form.tsx","registry/default/blocks/password-based-auth-react/components/update-password-form.tsx","registry/default/clients/react/lib/supabase/client.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"password-based-auth-react-router": {
|
||||
name: "password-based-auth-react-router",
|
||||
type: "registry:block",
|
||||
registryDependencies: ["button","card","input","label"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/password-based-auth-react-router/app/routes/auth.confirm.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/password-based-auth-react-router/app/routes/auth.confirm.tsx","registry/default/blocks/password-based-auth-react-router/app/routes/auth.error.tsx","registry/default/blocks/password-based-auth-react-router/app/routes/forgot-password.tsx","registry/default/blocks/password-based-auth-react-router/app/routes/login.tsx","registry/default/blocks/password-based-auth-react-router/app/routes/logout.tsx","registry/default/blocks/password-based-auth-react-router/app/routes/protected.tsx","registry/default/blocks/password-based-auth-react-router/app/routes/sign-up.tsx","registry/default/blocks/password-based-auth-react-router/app/routes/update-password.tsx","registry/default/blocks/password-based-auth-react-router/app/routes.ts","registry/default/clients/react-router/lib/supabase/client.ts","registry/default/clients/react-router/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"password-based-auth-tanstack": {
|
||||
name: "password-based-auth-tanstack",
|
||||
type: "registry:block",
|
||||
registryDependencies: ["button","card","input","label"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/password-based-auth-tanstack/routes/login.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/password-based-auth-tanstack/routes/login.tsx","registry/default/blocks/password-based-auth-tanstack/routes/auth/error.tsx","registry/default/blocks/password-based-auth-tanstack/routes/_protected.tsx","registry/default/blocks/password-based-auth-tanstack/routes/_protected/protected.tsx","registry/default/blocks/password-based-auth-tanstack/routes/auth/confirm.ts","registry/default/blocks/password-based-auth-tanstack/components/login-form.tsx","registry/default/blocks/password-based-auth-tanstack/routes/sign-up.tsx","registry/default/blocks/password-based-auth-tanstack/routes/sign-up-success.tsx","registry/default/blocks/password-based-auth-tanstack/components/sign-up-form.tsx","registry/default/blocks/password-based-auth-tanstack/routes/forgot-password.tsx","registry/default/blocks/password-based-auth-tanstack/routes/update-password.tsx","registry/default/blocks/password-based-auth-tanstack/components/forgot-password-form.tsx","registry/default/blocks/password-based-auth-tanstack/components/update-password-form.tsx","registry/default/blocks/password-based-auth-tanstack/lib/supabase/fetch-user-server-fn.ts","registry/default/clients/tanstack/lib/supabase/client.ts","registry/default/clients/tanstack/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"social-auth-nextjs": {
|
||||
name: "social-auth-nextjs",
|
||||
type: "registry:block",
|
||||
registryDependencies: ["button","card"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/social-auth-nextjs/app/auth/login/page.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/social-auth-nextjs/app/auth/login/page.tsx","registry/default/blocks/social-auth-nextjs/app/auth/error/page.tsx","registry/default/blocks/social-auth-nextjs/app/protected/page.tsx","registry/default/blocks/social-auth-nextjs/app/auth/oauth/route.ts","registry/default/blocks/social-auth-nextjs/components/login-form.tsx","registry/default/blocks/social-auth-nextjs/middleware.ts","registry/default/blocks/social-auth-nextjs/components/logout-button.tsx","registry/default/clients/nextjs/lib/supabase/client.ts","registry/default/clients/nextjs/lib/supabase/middleware.ts","registry/default/clients/nextjs/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"social-auth-react": {
|
||||
name: "social-auth-react",
|
||||
type: "registry:block",
|
||||
registryDependencies: ["button","card"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/social-auth-react/components/login-form.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/social-auth-react/components/login-form.tsx","registry/default/clients/react/lib/supabase/client.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"social-auth-react-router": {
|
||||
name: "social-auth-react-router",
|
||||
type: "registry:block",
|
||||
registryDependencies: ["button","card"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/social-auth-react-router/app/routes/auth.error.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/social-auth-react-router/app/routes/auth.error.tsx","registry/default/blocks/social-auth-react-router/app/routes/auth.oauth.tsx","registry/default/blocks/social-auth-react-router/app/routes/login.tsx","registry/default/blocks/social-auth-react-router/app/routes/logout.tsx","registry/default/blocks/social-auth-react-router/app/routes/protected.tsx","registry/default/blocks/social-auth-react-router/app/routes.ts","registry/default/clients/react-router/lib/supabase/client.ts","registry/default/clients/react-router/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"social-auth-tanstack": {
|
||||
name: "social-auth-tanstack",
|
||||
type: "registry:block",
|
||||
registryDependencies: ["button","card"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/social-auth-tanstack/components/login-form.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/social-auth-tanstack/components/login-form.tsx","registry/default/blocks/social-auth-tanstack/lib/supabase/fetch-user-server-fn.ts","registry/default/blocks/social-auth-tanstack/routes/_protected.tsx","registry/default/blocks/social-auth-tanstack/routes/_protected/protected.tsx","registry/default/blocks/social-auth-tanstack/routes/auth/error.tsx","registry/default/blocks/social-auth-tanstack/routes/auth/oauth.ts","registry/default/blocks/social-auth-tanstack/routes/login.tsx","registry/default/clients/tanstack/lib/supabase/client.ts","registry/default/clients/tanstack/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"dropzone-nextjs": {
|
||||
name: "dropzone-nextjs",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["button"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/dropzone/components/dropzone.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/dropzone/components/dropzone.tsx","registry/default/blocks/dropzone/hooks/use-supabase-upload.ts","registry/default/clients/nextjs/lib/supabase/client.ts","registry/default/clients/nextjs/lib/supabase/middleware.ts","registry/default/clients/nextjs/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"dropzone-react": {
|
||||
name: "dropzone-react",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["button"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/dropzone/components/dropzone.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/dropzone/components/dropzone.tsx","registry/default/blocks/dropzone/hooks/use-supabase-upload.ts","registry/default/clients/react/lib/supabase/client.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"dropzone-react-router": {
|
||||
name: "dropzone-react-router",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["button"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/dropzone/components/dropzone.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/dropzone/components/dropzone.tsx","registry/default/blocks/dropzone/hooks/use-supabase-upload.ts","registry/default/clients/react-router/lib/supabase/client.ts","registry/default/clients/react-router/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"dropzone-tanstack": {
|
||||
name: "dropzone-tanstack",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["button"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/dropzone/components/dropzone.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/dropzone/components/dropzone.tsx","registry/default/blocks/dropzone/hooks/use-supabase-upload.ts","registry/default/clients/tanstack/lib/supabase/client.ts","registry/default/clients/tanstack/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-cursor-nextjs": {
|
||||
name: "realtime-cursor-nextjs",
|
||||
type: "registry:component",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-cursor/components/cursor.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-cursor/components/cursor.tsx","registry/default/blocks/realtime-cursor/components/realtime-cursors.tsx","registry/default/blocks/realtime-cursor/hooks/use-realtime-cursors.ts","registry/default/clients/nextjs/lib/supabase/client.ts","registry/default/clients/nextjs/lib/supabase/middleware.ts","registry/default/clients/nextjs/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-cursor-react": {
|
||||
name: "realtime-cursor-react",
|
||||
type: "registry:component",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-cursor/components/cursor.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-cursor/components/cursor.tsx","registry/default/blocks/realtime-cursor/components/realtime-cursors.tsx","registry/default/blocks/realtime-cursor/hooks/use-realtime-cursors.ts","registry/default/clients/react/lib/supabase/client.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-cursor-react-router": {
|
||||
name: "realtime-cursor-react-router",
|
||||
type: "registry:component",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-cursor/components/cursor.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-cursor/components/cursor.tsx","registry/default/blocks/realtime-cursor/components/realtime-cursors.tsx","registry/default/blocks/realtime-cursor/hooks/use-realtime-cursors.ts","registry/default/clients/react-router/lib/supabase/client.ts","registry/default/clients/react-router/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-cursor-tanstack": {
|
||||
name: "realtime-cursor-tanstack",
|
||||
type: "registry:component",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-cursor/components/cursor.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-cursor/components/cursor.tsx","registry/default/blocks/realtime-cursor/components/realtime-cursors.tsx","registry/default/blocks/realtime-cursor/hooks/use-realtime-cursors.ts","registry/default/clients/tanstack/lib/supabase/client.ts","registry/default/clients/tanstack/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"current-user-avatar-nextjs": {
|
||||
name: "current-user-avatar-nextjs",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["avatar"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/current-user-avatar/components/current-user-avatar.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/current-user-avatar/components/current-user-avatar.tsx","registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts","registry/default/clients/nextjs/lib/supabase/client.ts","registry/default/clients/nextjs/lib/supabase/middleware.ts","registry/default/clients/nextjs/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"current-user-avatar-react": {
|
||||
name: "current-user-avatar-react",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["avatar"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/current-user-avatar/components/current-user-avatar.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/current-user-avatar/components/current-user-avatar.tsx","registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts","registry/default/clients/react/lib/supabase/client.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"current-user-avatar-react-router": {
|
||||
name: "current-user-avatar-react-router",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["avatar"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/current-user-avatar/components/current-user-avatar.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/current-user-avatar/components/current-user-avatar.tsx","registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts","registry/default/clients/react-router/lib/supabase/client.ts","registry/default/clients/react-router/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"current-user-avatar-tanstack": {
|
||||
name: "current-user-avatar-tanstack",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["avatar"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/current-user-avatar/components/current-user-avatar.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/current-user-avatar/components/current-user-avatar.tsx","registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts","registry/default/clients/tanstack/lib/supabase/client.ts","registry/default/clients/tanstack/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-avatar-stack-nextjs": {
|
||||
name: "realtime-avatar-stack-nextjs",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["avatar","tooltip"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-avatar-stack/components/avatar-stack.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-avatar-stack/components/avatar-stack.tsx","registry/default/blocks/realtime-avatar-stack/components/realtime-avatar-stack.tsx","registry/default/blocks/realtime-avatar-stack/hooks/use-realtime-presence-room.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts","registry/default/clients/nextjs/lib/supabase/client.ts","registry/default/clients/nextjs/lib/supabase/middleware.ts","registry/default/clients/nextjs/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-avatar-stack-react": {
|
||||
name: "realtime-avatar-stack-react",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["avatar","tooltip"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-avatar-stack/components/avatar-stack.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-avatar-stack/components/avatar-stack.tsx","registry/default/blocks/realtime-avatar-stack/components/realtime-avatar-stack.tsx","registry/default/blocks/realtime-avatar-stack/hooks/use-realtime-presence-room.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts","registry/default/clients/react/lib/supabase/client.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-avatar-stack-react-router": {
|
||||
name: "realtime-avatar-stack-react-router",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["avatar","tooltip"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-avatar-stack/components/avatar-stack.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-avatar-stack/components/avatar-stack.tsx","registry/default/blocks/realtime-avatar-stack/components/realtime-avatar-stack.tsx","registry/default/blocks/realtime-avatar-stack/hooks/use-realtime-presence-room.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts","registry/default/clients/react-router/lib/supabase/client.ts","registry/default/clients/react-router/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-avatar-stack-tanstack": {
|
||||
name: "realtime-avatar-stack-tanstack",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["avatar","tooltip"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-avatar-stack/components/avatar-stack.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-avatar-stack/components/avatar-stack.tsx","registry/default/blocks/realtime-avatar-stack/components/realtime-avatar-stack.tsx","registry/default/blocks/realtime-avatar-stack/hooks/use-realtime-presence-room.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-name.ts","registry/default/blocks/current-user-avatar/hooks/use-current-user-image.ts","registry/default/clients/tanstack/lib/supabase/client.ts","registry/default/clients/tanstack/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-chat-nextjs": {
|
||||
name: "realtime-chat-nextjs",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["input","button"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-chat/components/chat-message.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-chat/components/chat-message.tsx","registry/default/blocks/realtime-chat/components/realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx","registry/default/clients/nextjs/lib/supabase/client.ts","registry/default/clients/nextjs/lib/supabase/middleware.ts","registry/default/clients/nextjs/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-chat-react": {
|
||||
name: "realtime-chat-react",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["input","button"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-chat/components/chat-message.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-chat/components/chat-message.tsx","registry/default/blocks/realtime-chat/components/realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx","registry/default/clients/react/lib/supabase/client.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-chat-react-router": {
|
||||
name: "realtime-chat-react-router",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["input","button"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-chat/components/chat-message.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-chat/components/chat-message.tsx","registry/default/blocks/realtime-chat/components/realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx","registry/default/clients/react-router/lib/supabase/client.ts","registry/default/clients/react-router/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-chat-tanstack": {
|
||||
name: "realtime-chat-tanstack",
|
||||
type: "registry:component",
|
||||
registryDependencies: ["input","button"],
|
||||
component: React.lazy(() => import("@/registry/default/blocks/realtime-chat/components/chat-message.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/blocks/realtime-chat/components/chat-message.tsx","registry/default/blocks/realtime-chat/components/realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-realtime-chat.tsx","registry/default/blocks/realtime-chat/hooks/use-chat-scroll.tsx","registry/default/clients/tanstack/lib/supabase/client.ts","registry/default/clients/tanstack/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"infinite-query-hook": {
|
||||
name: "infinite-query-hook",
|
||||
type: "registry:block",
|
||||
registryDependencies: [],
|
||||
|
||||
source: "",
|
||||
files: ["registry/default/blocks/infinite-query-hook/hooks/use-infinite-query.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"supabase-client-nextjs": {
|
||||
name: "supabase-client-nextjs",
|
||||
type: "registry:lib",
|
||||
registryDependencies: [],
|
||||
|
||||
source: "",
|
||||
files: ["registry/default/clients/nextjs/lib/supabase/client.ts","registry/default/clients/nextjs/lib/supabase/middleware.ts","registry/default/clients/nextjs/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"supabase-client-react": {
|
||||
name: "supabase-client-react",
|
||||
type: "registry:lib",
|
||||
registryDependencies: [],
|
||||
|
||||
source: "",
|
||||
files: ["registry/default/clients/react/lib/supabase/client.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"supabase-client-react-router": {
|
||||
name: "supabase-client-react-router",
|
||||
type: "registry:lib",
|
||||
registryDependencies: [],
|
||||
|
||||
source: "",
|
||||
files: ["registry/default/clients/react-router/lib/supabase/client.ts","registry/default/clients/react-router/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"supabase-client-tanstack": {
|
||||
name: "supabase-client-tanstack",
|
||||
type: "registry:lib",
|
||||
registryDependencies: [],
|
||||
|
||||
source: "",
|
||||
files: ["registry/default/clients/tanstack/lib/supabase/client.ts","registry/default/clients/tanstack/lib/supabase/server.ts"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"platform-kit-nextjs": {
|
||||
name: "platform-kit-nextjs",
|
||||
type: "registry:block",
|
||||
registryDependencies: ["alert","badge","button","card","chart","command","dialog","drawer","form","hover-card","input","label","popover","select","skeleton","switch","table","toggle","toggle-group","tooltip"],
|
||||
component: React.lazy(() => import("@/registry/default/platform/platform-kit-nextjs/components/dynamic-form.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/platform/platform-kit-nextjs/app/api/ai/sql/route.ts","registry/default/platform/platform-kit-nextjs/app/api/supabase-proxy/[...path]/route.ts","registry/default/platform/platform-kit-nextjs/components/dynamic-form.tsx","registry/default/platform/platform-kit-nextjs/components/logo-supabase.tsx","registry/default/platform/platform-kit-nextjs/components/results-table.tsx","registry/default/platform/platform-kit-nextjs/components/sql-editor.tsx","registry/default/platform/platform-kit-nextjs/components/supabase-manager/auth.tsx","registry/default/platform/platform-kit-nextjs/components/supabase-manager/database.tsx","registry/default/platform/platform-kit-nextjs/components/supabase-manager/index.tsx","registry/default/platform/platform-kit-nextjs/components/supabase-manager/logs.tsx","registry/default/platform/platform-kit-nextjs/components/supabase-manager/secrets.tsx","registry/default/platform/platform-kit-nextjs/components/supabase-manager/storage.tsx","registry/default/platform/platform-kit-nextjs/components/supabase-manager/suggestions.tsx","registry/default/platform/platform-kit-nextjs/components/supabase-manager/users.tsx","registry/default/platform/platform-kit-nextjs/components/users-growth-chart.tsx","registry/default/platform/platform-kit-nextjs/hooks/use-auth.ts","registry/default/platform/platform-kit-nextjs/hooks/use-logs.ts","registry/default/platform/platform-kit-nextjs/hooks/use-run-query.ts","registry/default/platform/platform-kit-nextjs/hooks/use-secrets.ts","registry/default/platform/platform-kit-nextjs/hooks/use-storage.ts","registry/default/platform/platform-kit-nextjs/hooks/use-suggestions.ts","registry/default/platform/platform-kit-nextjs/hooks/use-tables.ts","registry/default/platform/platform-kit-nextjs/hooks/use-user-counts.ts","registry/default/platform/platform-kit-nextjs/lib/logs.ts","registry/default/platform/platform-kit-nextjs/lib/management-api-schema.d.ts","registry/default/platform/platform-kit-nextjs/lib/management-api.ts","registry/default/platform/platform-kit-nextjs/lib/pg-meta/sql.ts","registry/default/platform/platform-kit-nextjs/lib/pg-meta/index.ts","registry/default/platform/platform-kit-nextjs/lib/pg-meta/types.ts","registry/default/platform/platform-kit-nextjs/lib/schemas/auth.ts","registry/default/platform/platform-kit-nextjs/lib/schemas/secrets.ts","registry/default/platform/platform-kit-nextjs/contexts/SheetNavigationContext.tsx"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"ai-editor-rules": {
|
||||
name: "ai-editor-rules",
|
||||
type: "registry:file",
|
||||
registryDependencies: [],
|
||||
|
||||
source: "",
|
||||
files: ["registry/default/ai-editor-rules/create-db-functions.mdc","registry/default/ai-editor-rules/create-migration.mdc","registry/default/ai-editor-rules/create-rls-policies.mdc","registry/default/ai-editor-rules/postgres-sql-style-guide.mdc","registry/default/ai-editor-rules/writing-supabase-edge-functions.mdc","registry/default/ai-editor-rules/use-realtime.mdc"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"dropzone-demo": {
|
||||
name: "dropzone-demo",
|
||||
type: "registry:example",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/examples/dropzone-demo.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/examples/dropzone-demo.tsx"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-cursor-demo": {
|
||||
name: "realtime-cursor-demo",
|
||||
type: "registry:example",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/examples/realtime-cursor-demo.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/examples/realtime-cursor-demo.tsx"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"password-based-auth-demo": {
|
||||
name: "password-based-auth-demo",
|
||||
type: "registry:example",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/examples/password-based-auth.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/examples/password-based-auth.tsx"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"current-user-avatar-demo": {
|
||||
name: "current-user-avatar-demo",
|
||||
type: "registry:example",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/examples/current-user-avatar-demo.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/examples/current-user-avatar-demo.tsx"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"current-user-avatar-preview": {
|
||||
name: "current-user-avatar-preview",
|
||||
type: "registry:example",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/examples/current-user-avatar-preview.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/examples/current-user-avatar-preview.tsx"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-avatar-stack-demo": {
|
||||
name: "realtime-avatar-stack-demo",
|
||||
type: "registry:example",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/examples/realtime-avatar-stack-demo.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/examples/realtime-avatar-stack-demo.tsx"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"realtime-avatar-stack-preview": {
|
||||
name: "realtime-avatar-stack-preview",
|
||||
type: "registry:example",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/examples/realtime-avatar-stack-preview.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/examples/realtime-avatar-stack-preview.tsx"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
,
|
||||
"infinite-query-hook-demo": {
|
||||
name: "infinite-query-hook-demo",
|
||||
type: "registry:example",
|
||||
registryDependencies: [],
|
||||
component: React.lazy(() => import("@/registry/default/examples/infinite-query-hook-demo.tsx")),
|
||||
source: "",
|
||||
files: ["registry/default/examples/infinite-query-hook-demo.tsx"],
|
||||
category: "undefined",
|
||||
subcategory: "undefined",
|
||||
chunks: []
|
||||
}
|
||||
|
||||
},
|
||||
}
|
||||
} as const
|
||||
@@ -19,11 +19,3 @@ export const BlockItem = ({ name }: BlockItemProps) => {
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export const BlockItemPreview = ({ title, src }: { title: string; src: string }) => {
|
||||
return (
|
||||
<div className="flex items-center justify-center relative border rounded-lg">
|
||||
<iframe src={src} className="w-full h-[600px] border-0 rounded-md" title={title} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import * as React from 'react'
|
||||
|
||||
const ClassLabel = React.forwardRef<HTMLSpanElement, { children: React.ReactNode }>(
|
||||
({ children }, ref) => {
|
||||
return (
|
||||
<span
|
||||
ref={ref}
|
||||
className="bg-surface-100 rounded-full border px-2 font-mono text-xs text-foreground-lighter group-data-[state=open]:text-foreground"
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
ClassLabel.displayName = 'ClassLabel'
|
||||
|
||||
export { ClassLabel }
|
||||
@@ -1,16 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
|
||||
export function ClickCounter() {
|
||||
const [count, setCount] = useState(0)
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={() => setCount(count + 1)}
|
||||
className="whitespace-nowrap rounded-lg bg-gray-700 px-3 py-1 text-sm font-medium tabular-nums text-gray-100 hover:bg-gray-500 hover:text-white"
|
||||
>
|
||||
{count} Clicks
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
|
||||
import { cn } from 'ui'
|
||||
import { Button } from 'ui'
|
||||
import {
|
||||
Collapsible_Shadcn_ as Collapsible,
|
||||
CollapsibleContent_Shadcn_ as CollapsibleContent,
|
||||
CollapsibleTrigger_Shadcn_ as CollapsibleTrigger,
|
||||
} from 'ui'
|
||||
|
||||
interface CodeBlockProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
expandButtonTitle?: string
|
||||
}
|
||||
|
||||
export function CodeBlockWrapper({
|
||||
expandButtonTitle = 'View Code',
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: CodeBlockProps) {
|
||||
const [isOpened, setIsOpened] = React.useState(false)
|
||||
|
||||
return (
|
||||
<Collapsible open={isOpened} onOpenChange={setIsOpened}>
|
||||
<div className={cn('relative overflow-hidden', className)} {...props}>
|
||||
<CollapsibleContent forceMount className={cn('overflow-hidden', !isOpened && 'max-h-32')}>
|
||||
<div
|
||||
className={cn(
|
||||
'[&_pre]:my-0 [&_pre]:max-h-[650px] [&_pre]:pb-[100px]',
|
||||
!isOpened ? '[&_pre]:overflow-hidden' : '[&_pre]:overflow-auto]'
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
<div
|
||||
className={cn(
|
||||
'absolute flex items-center justify-center bg-gradient-to-b from-zinc-700/30 to-zinc-950/90 p-2',
|
||||
isOpened ? 'inset-x-0 bottom-0 h-12' : 'inset-0'
|
||||
)}
|
||||
>
|
||||
<CollapsibleTrigger asChild>
|
||||
<Button type="secondary" className="h-8 text-xs">
|
||||
{isOpened ? 'Collapse' : expandButtonTitle}
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
</div>
|
||||
</div>
|
||||
</Collapsible>
|
||||
)
|
||||
}
|
||||
@@ -1,105 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { Index } from '@/__registry__'
|
||||
import * as React from 'react'
|
||||
|
||||
import { useConfig } from '@/hooks/use-config'
|
||||
import { cn } from 'ui'
|
||||
|
||||
import { styles } from '@/registry/styles'
|
||||
|
||||
interface ComponentPreviewProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
name: string
|
||||
extractClassname?: boolean
|
||||
extractedClassNames?: string
|
||||
align?: 'center' | 'start' | 'end'
|
||||
showGrid?: boolean
|
||||
showDottedGrid?: boolean
|
||||
wide?: boolean
|
||||
}
|
||||
|
||||
export function CodeFragment({
|
||||
name,
|
||||
children,
|
||||
className,
|
||||
extractClassname,
|
||||
extractedClassNames,
|
||||
align = 'center',
|
||||
showGrid = false,
|
||||
showDottedGrid = true,
|
||||
wide = false,
|
||||
...props
|
||||
}: ComponentPreviewProps) {
|
||||
const [config] = useConfig()
|
||||
const index = styles.findIndex((style) => style.name === config.style)
|
||||
|
||||
const Codes = React.Children.toArray(children) as React.ReactElement[]
|
||||
const Code = Codes[index]
|
||||
|
||||
const [expand, setExpandState] = React.useState(false)
|
||||
|
||||
const Preview = React.useMemo(() => {
|
||||
// console.log('Index', Index)
|
||||
// console.log('name', name)
|
||||
// console.log('config.style', config.style)
|
||||
|
||||
const Component = Index[config.style][name]?.component
|
||||
// const Component = Index[name]?.component
|
||||
|
||||
if (!Component) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Code fragment{' '}
|
||||
<code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm">
|
||||
{name}
|
||||
</code>{' '}
|
||||
not found in registry.
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
return <Component />
|
||||
}, [name, config.style])
|
||||
|
||||
const ComponentPreview = React.useMemo(() => {
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={cn('preview flex min-h-[350px] w-full justify-center p-10', {
|
||||
'items-center': align === 'center',
|
||||
'items-start': align === 'start',
|
||||
'items-end': align === 'end',
|
||||
})}
|
||||
>
|
||||
<React.Suspense
|
||||
fallback={
|
||||
<div className="flex items-center text-sm text-muted-foreground">Loading...</div>
|
||||
}
|
||||
>
|
||||
{Preview}
|
||||
</React.Suspense>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}, [Preview, align])
|
||||
|
||||
const wideClasses = wide ? '2xl:-ml-12 2xl:-mr-12' : ''
|
||||
|
||||
return (
|
||||
<div className={cn('mt-4 mb-12', wideClasses)}>
|
||||
<div
|
||||
className={cn(
|
||||
'relative rounded-md border-t border-l border-r border-b bg-studio overflow-hidden'
|
||||
)}
|
||||
>
|
||||
{showGrid && (
|
||||
<div className="pointer-events-none absolute h-full w-full bg-[linear-gradient(to_right,hsla(var(--foreground-default)/0.02)_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:24px_24px]"></div>
|
||||
)}
|
||||
{showDottedGrid && (
|
||||
<div className="z-0 pointer-events-none absolute h-full w-full bg-[radial-gradient(hsla(var(--foreground-default)/0.02)_1px,transparent_1px)] [background-size:16px_16px] [mask-image:radial-gradient(ellipse_50%_50%_at_50%_50%,#000_70%,transparent_100%)]"></div>
|
||||
)}
|
||||
<div className="z-10 relative">{ComponentPreview}</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
|
||||
import { cn } from 'ui'
|
||||
import {
|
||||
// CopyButton,
|
||||
CopyWithClassNames,
|
||||
} from '@/components/copy-button'
|
||||
import {
|
||||
Tabs_Shadcn_ as Tabs,
|
||||
TabsContent_Shadcn_ as TabsContent,
|
||||
TabsList_Shadcn_ as TabsList,
|
||||
TabsTrigger_Shadcn_ as TabsTrigger,
|
||||
} from 'ui'
|
||||
|
||||
interface ComponentExampleProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
extractClassname?: boolean
|
||||
extractedClassNames?: string
|
||||
align?: 'center' | 'start' | 'end'
|
||||
src?: string
|
||||
}
|
||||
|
||||
export function ComponentExample({
|
||||
children,
|
||||
className,
|
||||
extractClassname,
|
||||
extractedClassNames,
|
||||
align = 'center',
|
||||
src: _,
|
||||
...props
|
||||
}: ComponentExampleProps) {
|
||||
const [Example, Code, ...Children] = React.Children.toArray(children) as React.ReactElement[]
|
||||
|
||||
const codeString = React.useMemo(() => {
|
||||
if (typeof Code?.props['data-rehype-pretty-code-fragment'] !== 'undefined') {
|
||||
const [, Button] = React.Children.toArray(Code.props.children) as React.ReactElement[]
|
||||
return Button?.props?.value || Button?.props?.__rawString__ || null
|
||||
}
|
||||
}, [Code])
|
||||
|
||||
return (
|
||||
<div className={cn('group relative my-4 flex flex-col gap-2', className)} {...props}>
|
||||
<Tabs defaultValue="preview" className="relative mr-auto w-full">
|
||||
<div className="flex items-center justify-between pb-3">
|
||||
<TabsList className="w-full justify-start rounded-none border-b bg-transparent p-0">
|
||||
<TabsTrigger
|
||||
value="preview"
|
||||
className="relative rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 font-semibold text-muted-foreground shadow-none transition-none data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none"
|
||||
>
|
||||
Preview
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="code"
|
||||
className="relative rounded-none border-b-2 border-b-transparent bg-transparent px-4 pb-3 pt-2 font-semibold text-muted-foreground shadow-none transition-none data-[state=active]:border-b-primary data-[state=active]:text-foreground data-[state=active]:shadow-none"
|
||||
>
|
||||
Code
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
{
|
||||
extractedClassNames ? (
|
||||
<CopyWithClassNames
|
||||
value={codeString}
|
||||
classNames={extractedClassNames}
|
||||
className="absolute right-4 top-20"
|
||||
/>
|
||||
) : undefined
|
||||
// codeString && <CopyButton value={codeString} className="absolute right-4 top-20" />
|
||||
}
|
||||
</div>
|
||||
<TabsContent value="preview" className="rounded-md border">
|
||||
<div
|
||||
className={cn('flex min-h-[350px] justify-center p-10', {
|
||||
'items-center': align === 'center',
|
||||
'items-start': align === 'start',
|
||||
'items-end': align === 'end',
|
||||
})}
|
||||
>
|
||||
{Example}
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="code">
|
||||
<div className="flex flex-col space-y-4">
|
||||
<div className="w-full rounded-md [&_button]:hidden [&_pre]:my-0 [&_pre]:max-h-[350px] [&_pre]:overflow-auto">
|
||||
{Code}
|
||||
</div>
|
||||
{Children?.length ? (
|
||||
<div className="rounded-md [&_button]:hidden [&_pre]:my-0 [&_pre]:max-h-[350px] [&_pre]:overflow-auto">
|
||||
{Children}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { styles } from '@/registry/styles'
|
||||
import { ChevronRight } from 'lucide-react'
|
||||
|
||||
interface ComponentPreviewProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
name: string
|
||||
name: keyof (typeof Index)['default']
|
||||
extractClassname?: boolean
|
||||
extractedClassNames?: string
|
||||
align?: 'center' | 'start' | 'end'
|
||||
@@ -36,8 +36,6 @@ export function ComponentPreview({
|
||||
const [config] = useConfig()
|
||||
const index = styles.findIndex((style) => style.name === config.style)
|
||||
|
||||
const [expand, setExpandState] = React.useState(false)
|
||||
|
||||
const Preview = React.useMemo(() => {
|
||||
const Component = Index['default'][name]?.component
|
||||
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import fs from 'fs'
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from 'ui'
|
||||
// import { parse } from 'react-docgen'
|
||||
|
||||
export function ComponentProps(props: any) {
|
||||
// map through all props types for this component DropdownMenu
|
||||
// return a table with the prop name, type, default value, and description
|
||||
|
||||
// const code = `
|
||||
// /** My first component */
|
||||
// export default ({ name }: { name: string }) => <div>{{name}}</div>;
|
||||
// `
|
||||
|
||||
// const documentation = parse(code)
|
||||
//
|
||||
// console.log(documentation)
|
||||
|
||||
// console.log('from the component props', JSON.parse(props.docs))
|
||||
|
||||
const docs = JSON.parse(props.docs)
|
||||
|
||||
// console.log(docs.props)
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium text-foreground-light">{props.children}</p>
|
||||
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="font-mono uppercase text-xs font-normal">Prop Name</TableHead>
|
||||
<TableHead className="font-mono uppercase text-xs font-normal">Required</TableHead>
|
||||
<TableHead className="font-mono uppercase text-xs font-normal">Type</TableHead>
|
||||
<TableHead className="font-mono uppercase text-xs text-right font-normal">
|
||||
Description
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{Object.entries(docs.props).map(([propName, prop], index) => (
|
||||
<TableRow key={index}>
|
||||
<TableCell>{propName}</TableCell>
|
||||
{/*
|
||||
// @ts-ignore */}
|
||||
<TableCell>{prop.required ? 'Yes' : 'No'}</TableCell>
|
||||
{/*
|
||||
// @ts-ignore */}
|
||||
<TableCell>{prop.flowType.name}</TableCell>
|
||||
{/*
|
||||
// @ts-ignore */}
|
||||
<TableCell className="text-right">{prop.description}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import * as React from 'react'
|
||||
|
||||
import { cn } from 'ui'
|
||||
import { CodeBlockWrapper } from '@/components/code-block-wrapper'
|
||||
|
||||
interface ComponentSourceProps extends React.HTMLAttributes<HTMLDivElement> {
|
||||
src: string
|
||||
}
|
||||
|
||||
export function ComponentSource({ children, className, ...props }: ComponentSourceProps) {
|
||||
return (
|
||||
<CodeBlockWrapper
|
||||
expandButtonTitle="Expand"
|
||||
className={cn('my-6 overflow-hidden rounded-md', className)}
|
||||
>
|
||||
{children}
|
||||
</CodeBlockWrapper>
|
||||
)
|
||||
}
|
||||
@@ -1,45 +1,16 @@
|
||||
'use client'
|
||||
|
||||
import { Check, Copy } from 'lucide-react'
|
||||
import * as React from 'react'
|
||||
|
||||
// import { NpmCommands } from 'types/unist'
|
||||
|
||||
// import { Event, trackEvent } from '@/lib/events'
|
||||
import { Check, Copy } from 'lucide-react'
|
||||
import {
|
||||
Button,
|
||||
cn,
|
||||
copyToClipboard,
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuTriggerProps,
|
||||
} from 'ui'
|
||||
import { Button, cn, copyToClipboard } from 'ui'
|
||||
|
||||
interface CopyButtonProps extends React.HTMLAttributes<HTMLButtonElement> {
|
||||
value: string
|
||||
src?: string
|
||||
// event?: Event['name']
|
||||
}
|
||||
|
||||
export async function copyToClipboardWithMeta(
|
||||
value: string
|
||||
// event?: Event
|
||||
) {
|
||||
copyToClipboard(value)
|
||||
if (event) {
|
||||
// trackEvent(event)
|
||||
}
|
||||
}
|
||||
|
||||
export function CopyButton({
|
||||
value,
|
||||
className,
|
||||
src,
|
||||
// event,
|
||||
...props
|
||||
}: CopyButtonProps) {
|
||||
export function CopyButton({ value, className, src, ...props }: CopyButtonProps) {
|
||||
const [hasCopied, setHasCopied] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
@@ -57,17 +28,7 @@ export function CopyButton({
|
||||
className
|
||||
)}
|
||||
onClick={() => {
|
||||
copyToClipboardWithMeta(
|
||||
value
|
||||
// event
|
||||
// ? {
|
||||
// name: event,
|
||||
// properties: {
|
||||
// code: value,
|
||||
// },
|
||||
// }
|
||||
// : undefined
|
||||
)
|
||||
copyToClipboard(value)
|
||||
setHasCopied(true)
|
||||
}}
|
||||
{...props}
|
||||
@@ -77,109 +38,3 @@ export function CopyButton({
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
interface CopyWithClassNamesProps extends DropdownMenuTriggerProps {
|
||||
value: string
|
||||
classNames: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function CopyWithClassNames({
|
||||
value,
|
||||
classNames,
|
||||
className,
|
||||
...props
|
||||
}: CopyWithClassNamesProps) {
|
||||
const [hasCopied, setHasCopied] = React.useState(false)
|
||||
|
||||
React.useEffect(() => {
|
||||
setTimeout(() => {
|
||||
setHasCopied(false)
|
||||
}, 2000)
|
||||
}, [hasCopied])
|
||||
|
||||
const copyToClipboard = React.useCallback((value: string) => {
|
||||
copyToClipboardWithMeta(value)
|
||||
setHasCopied(true)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
size="small"
|
||||
type="outline"
|
||||
className={cn(
|
||||
'relative z-10 h-6 w-6 text-zinc-50 hover:bg-zinc-700 hover:text-zinc-50',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{hasCopied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
|
||||
<span className="sr-only">Copy</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => copyToClipboard(value)}>Component</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => copyToClipboard(classNames)}>Classname</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
|
||||
interface CopyNpmCommandButtonProps extends DropdownMenuTriggerProps {
|
||||
// commands: Required<NpmCommands>
|
||||
}
|
||||
|
||||
// export function CopyNpmCommandButton({ commands, className, ...props }: CopyNpmCommandButtonProps) {
|
||||
// const [hasCopied, setHasCopied] = React.useState(false)
|
||||
|
||||
// React.useEffect(() => {
|
||||
// setTimeout(() => {
|
||||
// setHasCopied(false)
|
||||
// }, 2000)
|
||||
// }, [hasCopied])
|
||||
|
||||
// // const copyCommand = React.useCallback((value: string, pm: 'npm' | 'pnpm' | 'yarn' | 'bun') => {
|
||||
// // copyToClipboardWithMeta(value,
|
||||
// // // {
|
||||
// // // name: 'copy_npm_command',
|
||||
// // // properties: {
|
||||
// // // command: value,
|
||||
// // // pm,
|
||||
// // // },
|
||||
// // })
|
||||
// // setHasCopied(true)
|
||||
// // }, [])
|
||||
|
||||
// return (
|
||||
// <DropdownMenu>
|
||||
// <DropdownMenuTrigger asChild>
|
||||
// <Button
|
||||
// // size="icon"
|
||||
// type="outline"
|
||||
// className={cn(
|
||||
// 'relative z-10 h-6 w-6 text-zinc-50 hover:bg-zinc-700 hover:text-zinc-50',
|
||||
// className
|
||||
// )}
|
||||
// >
|
||||
// {hasCopied ? <CheckIcon className="h-3 w-3" /> : <CopyIcon className="h-3 w-3" />}
|
||||
// <span className="sr-only">Copy</span>
|
||||
// </Button>
|
||||
// </DropdownMenuTrigger>
|
||||
// <DropdownMenuContent align="end">
|
||||
// <DropdownMenuItem onClick={() => copyCommand(commands.__npmCommand__, 'npm')}>
|
||||
// npm
|
||||
// </DropdownMenuItem>
|
||||
// <DropdownMenuItem onClick={() => copyCommand(commands.__yarnCommand__, 'yarn')}>
|
||||
// yarn
|
||||
// </DropdownMenuItem>
|
||||
// <DropdownMenuItem onClick={() => copyCommand(commands.__pnpmCommand__, 'pnpm')}>
|
||||
// pnpm
|
||||
// </DropdownMenuItem>
|
||||
// <DropdownMenuItem onClick={() => copyCommand(commands.__bunCommand__, 'bun')}>
|
||||
// bun
|
||||
// </DropdownMenuItem>
|
||||
// </DropdownMenuContent>
|
||||
// </DropdownMenu>
|
||||
// )
|
||||
// }
|
||||
@@ -1,15 +0,0 @@
|
||||
import * as React from 'react'
|
||||
|
||||
const ExampleLabel = React.forwardRef<HTMLSpanElement, { children: React.ReactNode }>(
|
||||
({ children }, ref) => {
|
||||
return (
|
||||
<span ref={ref} className="text-xs flex gap-3 items-center text-foreground-muted">
|
||||
{children}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
ExampleLabel.displayName = 'ExampleLabel'
|
||||
|
||||
export { ExampleLabel }
|
||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user