@rebasepro/studio 0.26.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchesView-Df00LXAI.js → BranchesView-DqIfywjf.js} +3 -13
- package/dist/BranchesView-DqIfywjf.js.map +1 -0
- package/dist/{CronJobsView-CMNK7eWO.js → CronJobsView-CMa1E-Tx.js} +7 -3
- package/dist/CronJobsView-CMa1E-Tx.js.map +1 -0
- package/dist/{JSEditor-BgGMMbJ-.js → JSEditor-CXffIL9J.js} +2 -2
- package/dist/{JSEditor-BgGMMbJ-.js.map → JSEditor-CXffIL9J.js.map} +1 -1
- package/dist/{MonacoEditor-e9vF1eRi.js → MonacoEditor-7IlHFZU5.js} +21 -4
- package/dist/MonacoEditor-7IlHFZU5.js.map +1 -0
- package/dist/{RLSEditor-DEjuy8XH.js → RLSEditor-DCzA167e.js} +49 -21
- package/dist/RLSEditor-DCzA167e.js.map +1 -0
- package/dist/{SQLEditor-Cb9TIAz6.js → SQLEditor-DrqUDpD8.js} +36 -17
- package/dist/SQLEditor-DrqUDpD8.js.map +1 -0
- package/dist/components/RLSEditor/policyListing.d.ts +11 -0
- package/dist/index.es.js +7 -6
- package/dist/index.es.js.map +1 -1
- package/dist/{sql_utils-BZD31xE3.js → sql_utils-DXvmxiCq.js} +20 -2
- package/dist/sql_utils-DXvmxiCq.js.map +1 -0
- package/dist/utils/sql_utils.d.ts +14 -0
- package/package.json +9 -9
- package/dist/BranchesView-Df00LXAI.js.map +0 -1
- package/dist/CronJobsView-CMNK7eWO.js.map +0 -1
- package/dist/MonacoEditor-e9vF1eRi.js.map +0 -1
- package/dist/RLSEditor-DEjuy8XH.js.map +0 -1
- package/dist/SQLEditor-Cb9TIAz6.js.map +0 -1
- package/dist/sql_utils-BZD31xE3.js.map +0 -1
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","names":[],"sources":["../src/components/StudioHomePage.tsx","../src/components/RebaseStudio.tsx"],"sourcesContent":["import type { AppView, HomePageSection, PluginGenericProps } from \"@rebasepro/cms-types\";\nimport React, { useEffect, useMemo, useState } from \"react\";\nimport { Card, cls, Container, ExpandablePanel, Typography } from \"@rebasepro/ui\";\nimport { IconForView, useApiConfig, useNavigationGroupLabel, useRebaseContext, useRebaseRegistry, useRestoreScroll, useSlot, useTranslation } from \"@rebasepro/app\";\nimport { useNavigate } from \"react-router\";\nimport { useStudioBreadcrumbs, SchemaDriftBanner } from \"@rebasepro/app\";\n\n/* ═══════════════════════════════════════════════════════════════\n Studio tool sections, derived from the registered Studio views\n ═══════════════════════════════════════════════════════════════ */\n\ninterface StudioTool {\n path: string;\n name: string;\n description: string;\n icon?: string | React.ReactNode;\n}\n\ninterface StudioSection {\n label: string;\n tools: StudioTool[];\n}\n\n/** The view metadata the cards need — not the rendered `view` itself. */\ntype StudioViewMeta = Pick<AppView, \"slug\" | \"name\" | \"group\" | \"description\" | \"icon\" | \"hideFromNavigation\">;\n\n/** Group order for the home page; unknown groups are appended in view order. */\nconst GROUP_ORDER = [\"Database\", \"Compute\", \"Storage\", \"API\", \"Access Control\"];\n\nconst UNGROUPED_LABEL = \"Tools\";\n\n/**\n * Build the home page sections from the Studio views that are actually\n * registered, so a card exists if and only if its route does. A hand-written\n * list drifts: it used to advertise Users and Roles pages that 404, while\n * omitting the Backups view that does exist.\n */\nfunction buildSections(views: StudioViewMeta[]): StudioSection[] {\n const byGroup = new Map<string, StudioTool[]>();\n\n for (const view of views) {\n if (view.hideFromNavigation) continue;\n const label = view.group ?? UNGROUPED_LABEL;\n const tools = byGroup.get(label) ?? [];\n tools.push({\n path: `/${view.slug}`,\n name: view.name,\n description: view.description ?? \"\",\n icon: view.icon\n });\n byGroup.set(label, tools);\n }\n\n const ordered = [\n ...GROUP_ORDER.filter(g => byGroup.has(g)),\n ...[...byGroup.keys()].filter(g => !GROUP_ORDER.includes(g))\n ];\n\n return ordered.map(label => ({ label,\ntools: byGroup.get(label)! }));\n}\n\n/* ═══════════════════════════════════════════════════════════════ */\n\nconst COLLAPSED_STORAGE_KEY = \"rebase-studio-home-collapsed\";\n\nfunction useStudioCollapsedGroups(groupNames: string[]) {\n const [collapsed, setCollapsed] = useState<Set<string>>(() => {\n try {\n const stored = localStorage.getItem(COLLAPSED_STORAGE_KEY);\n return stored ? new Set(JSON.parse(stored)) : new Set<string>();\n } catch {\n return new Set<string>();\n }\n });\n\n const isGroupCollapsed = (name: string) => collapsed.has(name);\n\n const toggleGroupCollapsed = (name: string) => {\n setCollapsed(prev => {\n const next = new Set(prev);\n if (next.has(name)) {\n next.delete(name);\n } else {\n next.add(name);\n }\n try {\n localStorage.setItem(COLLAPSED_STORAGE_KEY, JSON.stringify([...next]));\n } catch { /* noop */ }\n return next;\n });\n };\n\n return { isGroupCollapsed, toggleGroupCollapsed };\n}\n\nexport function StudioHomePage({\n additionalActions,\n additionalChildrenStart,\n additionalChildrenEnd,\n sections,\n hiddenGroups\n}: {\n additionalActions?: React.ReactNode;\n additionalChildrenStart?: React.ReactNode;\n additionalChildrenEnd?: React.ReactNode;\n sections?: HomePageSection[];\n hiddenGroups?: string[];\n}) {\n const context = useRebaseContext();\n const breadcrumbs = useStudioBreadcrumbs();\n const navigate = useNavigate();\n const registry = useRebaseRegistry();\n const { t } = useTranslation();\n const apiConfig = useApiConfig();\n const apiUrl = absoluteApiUrl(apiConfig?.apiUrl);\n\n useEffect(() => {\n breadcrumbs.set({ breadcrumbs: [] });\n }, [breadcrumbs.set]);\n\n const { containerRef } = useRestoreScroll();\n\n const sectionProps: PluginGenericProps = { context };\n\n const pluginActions = useSlot(\"home.actions\", sectionProps);\n\n // The collection editor (\"schema\") is not part of `devViews` — RebaseNavigation\n // injects it when the admin enables a collection editor. Mirror that condition so\n // the card tracks the route.\n const schemaEnabled = Boolean(registry.studioConfig && registry.cmsConfig?.collectionEditor);\n\n const filteredSections = useMemo(() => {\n const views: StudioViewMeta[] = [];\n if (schemaEnabled) {\n views.push({\n slug: \"schema\",\n name: t(\"studio_tool_schema\"),\n group: \"Database\",\n icon: \"LayoutList\",\n description: t(\"studio_tool_schema_description\")\n });\n }\n views.push(...(registry.studioConfig?.devViews ?? []));\n return buildSections(views).filter(s => !hiddenGroups?.includes(s.label));\n }, [registry.studioConfig?.devViews, schemaEnabled, hiddenGroups, t]);\n\n const groupNames = useMemo(\n () => filteredSections.map(s => s.label),\n [filteredSections]\n );\n\n const { isGroupCollapsed, toggleGroupCollapsed } = useStudioCollapsedGroups(groupNames);\n // The group name is the identifier this page orders and collapses by;\n // only what the reader sees is translated.\n const groupLabel = useNavigationGroupLabel();\n\n return (\n <div ref={containerRef} className=\"py-2 overflow-auto h-full w-full bg-surface-sheet\">\n <Container maxWidth=\"6xl\">\n <div className=\"mb-4 flex flex-col gap-2\">\n <SchemaDriftBanner />\n </div>\n\n {(additionalActions || pluginActions) && (\n <div className=\"w-full sticky py-4 transition-all duration-400 ease-in-out top-0 z-10 flex flex-row gap-4 justify-end\">\n {additionalActions}\n {pluginActions}\n </div>\n )}\n\n {additionalChildrenStart}\n\n {/* ── Tool sections ── */}\n {filteredSections.map((section) => {\n const sectionCollapsed = isGroupCollapsed(section.label);\n\n return (\n <div key={section.label} className=\"my-10\">\n <ExpandablePanel\n invisible\n expanded={!sectionCollapsed}\n onExpandedChange={(open) => {\n if (open !== !sectionCollapsed) {\n toggleGroupCollapsed(section.label);\n }\n }}\n className=\"mt-6\"\n titleClassName={cls(\n \"min-h-0 p-0 border-none\",\n \"rounded flex items-center justify-between w-full\",\n \"hover:bg-transparent\",\n \"cursor-pointer select-none\",\n sectionCollapsed && \"bg-surface-field\"\n )}\n innerClassName=\"mt-4 pt-0\"\n title={\n <Typography\n variant=\"caption\"\n component=\"h2\"\n color=\"secondary\"\n className={cls(\n \"px-4 py-1 rounded\",\n \"font-medium text-[10px] uppercase tracking-[0.08em] text-surface-400 dark:text-surface-400\"\n )}\n >\n {groupLabel(section.label)}\n </Typography>\n }\n >\n <div className=\"mt-4 pt-0\">\n <div className=\"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4\">\n {section.tools.map((tool) => (\n <Card\n key={tool.path}\n onClick={() => {\n navigate(tool.path);\n context.analyticsController?.onAnalyticsEvent?.(\n \"home_navigate_to_view\",\n { path: tool.path }\n );\n }}\n className={cls(\n \"group h-full p-4 cursor-pointer transition-colors duration-150 ease-in-out\",\n \"hover:bg-surface-card-hover\"\n )}\n >\n <div className=\"flex flex-col h-full\">\n {/* Header: icon + title */}\n <div className=\"flex items-center w-full justify-between mb-1\">\n <div className=\"flex items-center gap-3\">\n <div className=\"flex items-center justify-center w-5 h-5 text-surface-400 dark:text-surface-500 transition-colors duration-150 group-hover:text-primary dark:group-hover:text-primary\">\n <IconForView\n collectionOrView={{ slug: tool.path, name: tool.name, icon: tool.icon }}\n size=\"small\"\n />\n </div>\n <Typography variant=\"subtitle1\" component=\"h2\">\n {tool.name}\n </Typography>\n </div>\n </div>\n\n {/* Description indented to align with title */}\n <div className=\"pl-8\">\n {tool.description && (\n <Typography variant=\"caption\" color=\"secondary\" component=\"div\">\n {tool.description}\n </Typography>\n )}\n </div>\n\n {/* Spacer */}\n <div className=\"grow\"/>\n </div>\n </Card>\n ))}\n </div>\n </div>\n </ExpandablePanel>\n </div>\n );\n })}\n\n {/* ── SDK Quick Start ── */}\n <div className=\"mt-10 mb-6\">\n <div className=\"flex items-center mb-1\">\n <Typography\n variant=\"caption\"\n component=\"h2\"\n color=\"secondary\"\n className={cls(\n \"px-4 py-1 rounded\",\n \"font-medium text-[10px] uppercase tracking-[0.08em] text-surface-400 dark:text-surface-400\"\n )}\n >\n Quick Start\n </Typography>\n </div>\n\n <Typography variant=\"body2\" color=\"secondary\" className=\"mb-4 max-w-2xl\">\n Generate a fully-typed SDK from your collections with{\" \"}\n <code className=\"text-emerald-400 font-mono text-xs bg-emerald-400/10 px-1.5 py-0.5 rounded\">\n npx rebase generate-sdk\n </code>\n {\" \"}and start querying your data with full TypeScript autocompletion.\n </Typography>\n\n <div className=\"rounded-lg border border-hairline bg-surface-card overflow-hidden\">\n {/* Title bar */}\n <div className=\"flex items-center justify-between px-4 py-2.5 border-b border-hairline bg-surface-sheet\">\n <div className=\"flex items-center gap-2.5\">\n <div className=\"flex gap-1.5\">\n <span className=\"w-2.5 h-2.5 rounded-full bg-red-400/60\"/>\n <span className=\"w-2.5 h-2.5 rounded-full bg-amber-400/60\"/>\n <span className=\"w-2.5 h-2.5 rounded-full bg-emerald-400/60\"/>\n </div>\n <span className=\"text-xs font-mono text-surface-400 dark:text-surface-500 ml-1\">\n app.ts\n </span>\n </div>\n <span className=\"text-xs font-mono text-surface-400 dark:text-surface-500\">\n TypeScript\n </span>\n </div>\n\n {/* Syntax-highlighted code */}\n <div className=\"px-5 py-4 overflow-x-auto text-[13px] leading-6 font-mono\">\n <SyntaxHighlightedSnippet baseUrl={apiUrl}/>\n </div>\n </div>\n </div>\n\n {/* ── Extra sections from props ── */}\n {sections?.map((s) => (\n <div key={s.key} className=\"my-10\">\n <Typography\n variant=\"caption\"\n component=\"h2\"\n color=\"secondary\"\n className={cls(\n \"px-4 py-1 rounded\",\n \"font-medium text-[10px] uppercase tracking-[0.08em] text-surface-400 dark:text-surface-400\"\n )}\n >\n {s.title}\n </Typography>\n <div className=\"mt-4\">{s.children}</div>\n </div>\n ))}\n\n {additionalChildrenEnd}\n </Container>\n </div>\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Hand-crafted syntax-highlighted code snippet.\n Uses inline spans with Tailwind color classes to avoid\n pulling in a syntax highlighting library.\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The address the panel's API answers on, as a script would write it: absolute\n * (a same-origin panel is configured with a relative one) and without a\n * trailing slash. It is what `baseUrl` takes — the API's path is the client's.\n */\nfunction absoluteApiUrl(apiUrl: string | undefined): string {\n const page = typeof window !== \"undefined\" ? window.location.href : undefined;\n try {\n return new URL(apiUrl || \"/\", page).href.replace(/\\/+$/, \"\");\n } catch {\n return apiUrl ?? \"\";\n }\n}\n\n/** The quick-start client, pointed at `baseUrl`. */\nfunction SyntaxHighlightedSnippet({ baseUrl }: { baseUrl: string }) {\n const kw = \"text-violet-600 dark:text-violet-400\"; // keywords\n const str = \"text-emerald-600 dark:text-emerald-400\"; // strings\n const typ = \"text-amber-600 dark:text-amber-300\"; // types\n const fn = \"text-blue-600 dark:text-blue-400\"; // functions\n const cm = \"text-surface-500 dark:text-surface-400 italic\"; // comments\n const op = \"text-surface-500 dark:text-surface-400\"; // operators / punctuation\n const tx = \"text-surface-950 dark:text-surface-200\"; // plain text\n\n return (\n <pre className=\"m-0 whitespace-pre\">\n <span className={kw}>import</span>\n <span className={tx}>{\" { \"}</span>\n <span className={fn}>createRebaseClient</span>\n <span className={tx}>{\" } \"}</span>\n <span className={kw}>from</span>\n <span className={tx}> </span>\n <span className={str}>'@rebasepro/client'</span>\n <span className={op}>;</span>\n {\"\\n\"}\n\n <span className={kw}>import</span>\n <span className={tx}>{\" { collectionsDictionary, \"}</span>\n <span className={kw}>type</span>\n <span className={tx}> </span>\n <span className={typ}>Database</span>\n <span className={tx}>{\" } \"}</span>\n <span className={kw}>from</span>\n <span className={tx}> </span>\n <span className={str}>'./database.types'</span>\n <span className={op}>;</span>\n {\"\\n\\n\"}\n\n <span className={kw}>const</span>\n <span className={tx}> rebase </span>\n <span className={op}>= </span>\n <span className={fn}>createRebaseClient</span>\n <span className={op}>{\"<\"}</span>\n <span className={typ}>Database</span>\n <span className={op}>{\">(\"}</span>\n <span className={tx}>{\"{\"}</span>\n {\"\\n\"}\n <span className={tx}>{\" baseUrl\"}</span>\n <span className={op}>: </span>\n <span className={str}>'{baseUrl}'</span>\n <span className={op}>,</span>\n {\"\\n\"}\n {/* Maps each accessor back to its slug: without it a hyphenated\n slug is not reachable from the property name, and the copied\n client 404s on that collection. */}\n <span className={tx}>{\" collections\"}</span>\n <span className={op}>: </span>\n <span className={tx}>collectionsDictionary</span>\n <span className={op}>,</span>\n {\"\\n\"}\n <span className={tx}>{\"}\"}</span>\n <span className={op}>);</span>\n {\"\\n\\n\"}\n\n <span className={cm}>{\"// Fully typed — autocompletion for tables and columns\"}</span>\n {\"\\n\"}\n <span className={kw}>const</span>\n <span className={tx}>{\" { \"}</span>\n <span className={tx}>data</span>\n <span className={op}>: </span>\n <span className={tx}>users</span>\n <span className={tx}>{\" } \"}</span>\n <span className={op}>= </span>\n <span className={kw}>await</span>\n <span className={tx}> rebase</span>\n <span className={op}>.</span>\n <span className={tx}>data</span>\n <span className={op}>.</span>\n <span className={tx}>users</span>\n <span className={op}>.</span>\n <span className={fn}>find</span>\n <span className={op}>();</span>\n {\"\\n\"}\n\n <span className={kw}>const</span>\n <span className={tx}>{\" { \"}</span>\n <span className={tx}>data</span>\n <span className={op}>: </span>\n <span className={tx}>posts</span>\n <span className={tx}>{\" } \"}</span>\n <span className={op}>= </span>\n <span className={kw}>await</span>\n <span className={tx}> rebase</span>\n <span className={op}>.</span>\n <span className={tx}>data</span>\n <span className={op}>.</span>\n <span className={fn}>collection</span>\n <span className={op}>(</span>\n <span className={str}>'posts'</span>\n <span className={op}>)</span>\n <span className={op}>.</span>\n <span className={fn}>find</span>\n <span className={op}>();</span>\n </pre>\n );\n}\n","import React, { Suspense, useLayoutEffect, useMemo } from \"react\";\nimport { useRebaseRegistryDispatch, useTranslation } from \"@rebasepro/app\";\nimport type { RebaseStudioConfig, AppView } from \"@rebasepro/cms-types\";\nimport { CircularProgressCenter, lazyChunk } from \"@rebasepro/ui\";\n\n// Lazy-loaded studio tools — each fetched only when its route is visited.\n// This keeps Monaco, @xyflow/react, dagre, pgsql-ast-parser etc. out of the initial bundle.\nconst SQLEditor = lazyChunk(() => import(\"./SQLEditor/SQLEditor\").then(m => ({ default: m.SQLEditor })));\nconst JSEditor = lazyChunk(() => import(\"./JSEditor/JSEditor\").then(m => ({ default: m.JSEditor })));\nconst RLSEditor = lazyChunk(() => import(\"./RLSEditor/RLSEditor\").then(m => ({ default: m.RLSEditor })));\nconst StorageView = lazyChunk(() => import(\"./StorageView/StorageView\").then(m => ({ default: m.StorageView })));\nconst CronJobsView = lazyChunk(() => import(\"./CronJobs/CronJobsView\").then(m => ({ default: m.CronJobsView })));\nconst SchemaVisualizer = lazyChunk(() => import(\"./SchemaVisualizer/SchemaVisualizer\").then(m => ({ default: m.SchemaVisualizer })));\nconst BranchesView = lazyChunk(() => import(\"./Branches/BranchesView\").then(m => ({ default: m.BranchesView })));\nconst BackupsView = lazyChunk(() => import(\"./Backups/BackupsView\").then(m => ({ default: m.BackupsView })));\nconst ApiExplorer = lazyChunk(() => import(\"./ApiExplorer/ApiExplorer\").then(m => ({ default: m.ApiExplorer })));\nconst LogsExplorer = lazyChunk(() => import(\"./LogsExplorer/LogsExplorer\").then(m => ({ default: m.LogsExplorer })));\nconst ApiKeysView = lazyChunk(() => import(\"./ApiKeys/ApiKeysView\").then(m => ({ default: m.ApiKeysView })));\n\nimport { StudioHomePage } from \"./StudioHomePage\";\n\n/**\n * Declarative component to configure the Studio in Rebase.\n * Renders nothing — purely registers config into the RebaseRegistry.\n *\n * The \"schema\" tool (collection editor view) is a Studio tool, but it is not\n * registered here: it ships from the panel package because it needs the project's\n * collection source to write back to. When `<RebaseCMS collectionEditor={...}>`\n * is used, the schema view is automatically injected into Studio — no manual\n * wiring needed. Where it is mounted from is an implementation detail; it is a\n * schema-editing tool and belongs beside SQL and RLS.\n */\nconst DEFAULT_HOME_PAGE = <StudioHomePage/>;\n\nexport function RebaseStudio({ tools, homePage, devViews: extraViews }: RebaseStudioConfig) {\n const dispatch = useRebaseRegistryDispatch();\n const { t, i18n } = useTranslation();\n\n const resolvedHomePage = homePage ?? DEFAULT_HOME_PAGE;\n\n /**\n * The tool list reduced to a value, so that re-rendering the host does not\n * republish the registry.\n *\n * `tools` is an array, and callers write it inline — `tools={[...TOOLS]}`\n * in the hosted console. A fresh array every render meant a fresh\n * `devViews` every render, which meant the effect below unregistered and\n * re-registered on every render. Because each registration builds *new*\n * `<Suspense><SQLEditor/></Suspense>` elements, whatever view was on screen\n * was torn down and remounted each time: a half-typed SQL query, a storage\n * folder you had navigated into, an open policy editor — all discarded, and\n * every mount reissued the view's initial requests.\n */\n const toolsKey = tools ? tools.join(\",\") : \"\";\n\n const devViews: AppView[] = useMemo(() => {\n const views: AppView[] = [];\n const activeTools = tools ?? [\"sql\", \"js\", \"rls\", \"storage\", \"cron\", \"schema-visualizer\", \"branches\", \"backups\", \"api\", \"logs\", \"api-keys\"];\n const suspense = (el: React.ReactNode) => <Suspense fallback={<CircularProgressCenter/>}>{el}</Suspense>;\n\n if (activeTools.includes(\"sql\")) {\n views.push({ slug: \"sql\",\nname: t(\"studio_tool_sql\"),\ngroup: \"Database\",\nicon: \"terminal\",\ndescription: t(\"studio_tool_sql_description\"),\nview: suspense(<SQLEditor/>) });\n }\n if (activeTools.includes(\"js\")) {\n views.push({ slug: \"js\",\nname: t(\"studio_tool_js\"),\ngroup: \"Compute\",\nicon: \"code\",\ndescription: t(\"studio_tool_js_description\"),\nview: suspense(<JSEditor/>) });\n }\n if (activeTools.includes(\"rls\")) {\n views.push({ slug: \"rls\",\nname: t(\"studio_tool_rls\"),\ngroup: \"Database\",\nicon: \"ShieldCheck\",\ndescription: t(\"studio_tool_rls_description\"),\nview: suspense(<RLSEditor/>) });\n }\n if (activeTools.includes(\"storage\")) {\n views.push({ slug: \"storage\",\nname: t(\"studio_tool_storage\"),\ngroup: \"Storage\",\nicon: \"HardDrive\",\ndescription: t(\"studio_tool_storage_description\"),\nview: suspense(<StorageView/>) });\n }\n if (activeTools.includes(\"cron\")) {\n views.push({ slug: \"cron\",\nname: t(\"studio_tool_cron\"),\ngroup: \"Compute\",\nicon: \"Clock\",\ndescription: t(\"studio_tool_cron_description\"),\nview: suspense(<CronJobsView/>) });\n }\n if (activeTools.includes(\"schema-visualizer\")) {\n views.push({ slug: \"schema-visualizer\",\nname: t(\"studio_tool_schema_visualizer\"),\ngroup: \"Database\",\nicon: \"Network\",\ndescription: t(\"studio_tool_schema_visualizer_description\"),\nview: suspense(<SchemaVisualizer/>) });\n }\n if (activeTools.includes(\"branches\")) {\n views.push({ slug: \"branches\",\nname: t(\"studio_tool_branches\"),\ngroup: \"Database\",\nicon: \"GitBranch\",\ndescription: t(\"studio_tool_branches_description\"),\nview: suspense(<BranchesView/>) });\n }\n if (activeTools.includes(\"backups\")) {\n views.push({ slug: \"backups\",\nname: t(\"studio_tool_backups\"),\ngroup: \"Database\",\nicon: \"Database\",\ndescription: t(\"studio_tool_backups_description\"),\nview: suspense(<BackupsView/>) });\n }\n if (activeTools.includes(\"api\")) {\n views.push({ slug: \"api\",\nname: t(\"studio_tool_api\"),\ngroup: \"API\",\nicon: \"BookOpen\",\ndescription: t(\"studio_tool_api_description\"),\nview: suspense(<ApiExplorer/>) });\n }\n if (activeTools.includes(\"logs\")) {\n views.push({ slug: \"logs\",\nname: t(\"studio_tool_logs\"),\ngroup: \"Database\",\nicon: \"Activity\",\ndescription: t(\"studio_tool_logs_description\"),\nview: suspense(<LogsExplorer/>) });\n }\n if (activeTools.includes(\"api-keys\")) {\n views.push({ slug: \"api-keys\",\nname: t(\"studio_tool_api_keys\"),\ngroup: \"Access Control\",\nicon: \"KeyRound\",\ndescription: t(\"studio_tool_api_keys_description\"),\nview: suspense(<ApiKeysView/>) });\n }\n // Note: \"schema\" tool is auto-injected by RebaseShell when collectionEditor is enabled.\n // It is NOT registered here anymore.\n return views;\n // Keyed by the tool list's *contents*; see `toolsKey`. `tools` itself is\n // read inside, and is exactly determined by the key.\n // The strings are now translated, so the active language is part of\n // what this list is.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [toolsKey, t, i18n.language]);\n\n /**\n * Your own tools, keyed the same way `tools` is and for the same reason:\n * callers write `devViews={[…]}` inline, so the array is new on every\n * render. Re-registering would tear down and remount whichever Studio view\n * was on screen — a half-typed SQL query, an open policy editor.\n *\n * The key is the identity of each view, not its element: a view's `view` is\n * resolved by the router at render time, so a fresh element for the same\n * slug is not a configuration change.\n */\n const extraViewsKey = (extraViews ?? [])\n .map((v) => `${v.slug}|${v.name}|${v.group ?? \"\"}|${v.hideFromNavigation ?? false}`)\n .join(\",\");\n const extraViewsRef = React.useRef(extraViews);\n extraViewsRef.current = extraViews;\n\n const allDevViews: AppView[] = useMemo(\n () => [...devViews, ...(extraViewsRef.current ?? [])],\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [devViews, extraViewsKey]\n );\n\n // Use a ref for homePage so it never destabilizes the effect.\n // homePage is a React element — its identity doesn't matter for registration.\n const homePageRef = React.useRef(resolvedHomePage);\n homePageRef.current = resolvedHomePage;\n\n // Same reasoning for `tools`: it is registered as config, but a new array\n // with the same contents must not count as a change.\n const toolsRef = React.useRef(tools);\n toolsRef.current = tools;\n\n useLayoutEffect(() => {\n dispatch.registerStudio({ tools: toolsRef.current,\nhomePage: homePageRef.current,\ndevViews: allDevViews });\n return () => dispatch.unregisterStudio();\n }, [dispatch, allDevViews]);\n\n return null;\n}\n"],"mappings":";;;;;;;AA2BA,IAAM,cAAc;CAAC;CAAY;CAAW;CAAW;CAAO;AAAgB;AAE9E,IAAM,kBAAkB;;;;;;;AAQxB,SAAS,cAAc,OAA0C;CAC7D,MAAM,0BAAU,IAAI,IAA0B;CAE9C,KAAK,MAAM,QAAQ,OAAO;EACtB,IAAI,KAAK,oBAAoB;EAC7B,MAAM,QAAQ,KAAK,SAAS;EAC5B,MAAM,QAAQ,QAAQ,IAAI,KAAK,KAAK,CAAC;EACrC,MAAM,KAAK;GACP,MAAM,IAAI,KAAK;GACf,MAAM,KAAK;GACX,aAAa,KAAK,eAAe;GACjC,MAAM,KAAK;EACf,CAAC;EACD,QAAQ,IAAI,OAAO,KAAK;CAC5B;CAOA,OAAO,CAJH,GAAG,YAAY,QAAO,MAAK,QAAQ,IAAI,CAAC,CAAC,GACzC,GAAG,CAAC,GAAG,QAAQ,KAAK,CAAC,CAAC,CAAC,QAAO,MAAK,CAAC,YAAY,SAAS,CAAC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vGc,QAAQ,MAAM,KAAK,GAAG,IAAI;EAuG7B;EAAG,KAAK;CAAQ,CAAC;;;;;;;;;;;CAY/B,MAAM,iBAAiB,cAAc,CAAC,EAAA,CACjC,KAAK,MAAM,GAAG,EAAE,KAAK,GAAG,EAAE,KAAK,GAAG,EAAE,SAAS,GAAG,GAAG,EAAE,sBAAsB,OAAO,CAAC,CACnF,KAAK,GAAG;CACb,MAAM,gBAAgB,MAAM,OAAO,UAAU;CAC7C,cAAc,UAAU;CAExB,MAAM,cAAyB,cACrB,CAAC,GAAG,UAAU,GAAI,cAAc,WAAW,CAAC,CAAE,GAEpD,CAAC,UAAU,aAAa,CAC5B;CAIA,MAAM,cAAc,MAAM,OAAO,gBAAgB;CACjD,YAAY,UAAU;CAItB,MAAM,WAAW,MAAM,OAAO,KAAK;CACnC,SAAS,UAAU;CAEnB,sBAAsB;EAClB,SAAS,eAAe;GAAE,OAAO,SAAS;GAClD,UAAU,YAAY;GACtB,UAAU;EAAY,CAAC;EACf,aAAa,SAAS,iBAAiB;CAC3C,GAAG,CAAC,UAAU,WAAW,CAAC;CAE1B,OAAO;AACX"}
|
|
1
|
+
{"version":3,"file":"index.es.js","names":[],"sources":["../src/components/StudioHomePage.tsx","../src/components/RebaseStudio.tsx"],"sourcesContent":["import type { AppView, HomePageSection, PluginGenericProps } from \"@rebasepro/cms-types\";\nimport { studioSchemaToolEnabled } from \"@rebasepro/cms-types\";\nimport React, { useEffect, useMemo, useState } from \"react\";\nimport { Card, cls, Container, ExpandablePanel, Typography } from \"@rebasepro/ui\";\nimport { IconForView, useApiConfig, useNavigationGroupLabel, useRebaseContext, useRebaseRegistry, useRestoreScroll, useSlot, useTranslation } from \"@rebasepro/app\";\nimport { useNavigate } from \"react-router\";\nimport { useStudioBreadcrumbs, SchemaDriftBanner } from \"@rebasepro/app\";\n\n/* ═══════════════════════════════════════════════════════════════\n Studio tool sections, derived from the registered Studio views\n ═══════════════════════════════════════════════════════════════ */\n\ninterface StudioTool {\n path: string;\n name: string;\n description: string;\n icon?: string | React.ReactNode;\n}\n\ninterface StudioSection {\n label: string;\n tools: StudioTool[];\n}\n\n/** The view metadata the cards need — not the rendered `view` itself. */\ntype StudioViewMeta = Pick<AppView, \"slug\" | \"name\" | \"group\" | \"description\" | \"icon\" | \"hideFromNavigation\">;\n\n/** Group order for the home page; unknown groups are appended in view order. */\nconst GROUP_ORDER = [\"Database\", \"Compute\", \"Storage\", \"API\", \"Access Control\"];\n\nconst UNGROUPED_LABEL = \"Tools\";\n\n/**\n * Build the home page sections from the Studio views that are actually\n * registered, so a card exists if and only if its route does. A hand-written\n * list drifts: it used to advertise Users and Roles pages that 404, while\n * omitting the Backups view that does exist.\n */\nfunction buildSections(views: StudioViewMeta[]): StudioSection[] {\n const byGroup = new Map<string, StudioTool[]>();\n\n for (const view of views) {\n if (view.hideFromNavigation) continue;\n const label = view.group ?? UNGROUPED_LABEL;\n const tools = byGroup.get(label) ?? [];\n tools.push({\n path: `/${view.slug}`,\n name: view.name,\n description: view.description ?? \"\",\n icon: view.icon\n });\n byGroup.set(label, tools);\n }\n\n const ordered = [\n ...GROUP_ORDER.filter(g => byGroup.has(g)),\n ...[...byGroup.keys()].filter(g => !GROUP_ORDER.includes(g))\n ];\n\n return ordered.map(label => ({ label,\ntools: byGroup.get(label)! }));\n}\n\n/* ═══════════════════════════════════════════════════════════════ */\n\nconst COLLAPSED_STORAGE_KEY = \"rebase-studio-home-collapsed\";\n\nfunction useStudioCollapsedGroups(groupNames: string[]) {\n const [collapsed, setCollapsed] = useState<Set<string>>(() => {\n try {\n const stored = localStorage.getItem(COLLAPSED_STORAGE_KEY);\n return stored ? new Set(JSON.parse(stored)) : new Set<string>();\n } catch {\n return new Set<string>();\n }\n });\n\n const isGroupCollapsed = (name: string) => collapsed.has(name);\n\n const toggleGroupCollapsed = (name: string) => {\n setCollapsed(prev => {\n const next = new Set(prev);\n if (next.has(name)) {\n next.delete(name);\n } else {\n next.add(name);\n }\n try {\n localStorage.setItem(COLLAPSED_STORAGE_KEY, JSON.stringify([...next]));\n } catch { /* noop */ }\n return next;\n });\n };\n\n return { isGroupCollapsed, toggleGroupCollapsed };\n}\n\nexport function StudioHomePage({\n additionalActions,\n additionalChildrenStart,\n additionalChildrenEnd,\n sections,\n hiddenGroups\n}: {\n additionalActions?: React.ReactNode;\n additionalChildrenStart?: React.ReactNode;\n additionalChildrenEnd?: React.ReactNode;\n sections?: HomePageSection[];\n hiddenGroups?: string[];\n}) {\n const context = useRebaseContext();\n const breadcrumbs = useStudioBreadcrumbs();\n const navigate = useNavigate();\n const registry = useRebaseRegistry();\n const { t } = useTranslation();\n const apiConfig = useApiConfig();\n const apiUrl = absoluteApiUrl(apiConfig?.apiUrl);\n\n useEffect(() => {\n breadcrumbs.set({ breadcrumbs: [] });\n }, [breadcrumbs.set]);\n\n const { containerRef } = useRestoreScroll();\n\n const sectionProps: PluginGenericProps = { context };\n\n const pluginActions = useSlot(\"home.actions\", sectionProps);\n\n // The collection editor (\"schema\") is not part of `devViews` — RebaseNavigation\n // injects it when the admin enables a collection editor and the Studio's\n // tools include it. The same predicate, so the card tracks the route.\n const schemaEnabled = studioSchemaToolEnabled(registry);\n\n const filteredSections = useMemo(() => {\n const views: StudioViewMeta[] = [];\n if (schemaEnabled) {\n views.push({\n slug: \"schema\",\n name: t(\"studio_tool_schema\"),\n group: \"Database\",\n icon: \"LayoutList\",\n description: t(\"studio_tool_schema_description\")\n });\n }\n views.push(...(registry.studioConfig?.devViews ?? []));\n return buildSections(views).filter(s => !hiddenGroups?.includes(s.label));\n }, [registry.studioConfig?.devViews, schemaEnabled, hiddenGroups, t]);\n\n const groupNames = useMemo(\n () => filteredSections.map(s => s.label),\n [filteredSections]\n );\n\n const { isGroupCollapsed, toggleGroupCollapsed } = useStudioCollapsedGroups(groupNames);\n // The group name is the identifier this page orders and collapses by;\n // only what the reader sees is translated.\n const groupLabel = useNavigationGroupLabel();\n\n return (\n <div ref={containerRef} className=\"py-2 overflow-auto h-full w-full bg-surface-sheet\">\n <Container maxWidth=\"6xl\">\n <div className=\"mb-4 flex flex-col gap-2\">\n <SchemaDriftBanner />\n </div>\n\n {(additionalActions || pluginActions) && (\n <div className=\"w-full sticky py-4 transition-all duration-400 ease-in-out top-0 z-10 flex flex-row gap-4 justify-end\">\n {additionalActions}\n {pluginActions}\n </div>\n )}\n\n {additionalChildrenStart}\n\n {/* ── Tool sections ── */}\n {filteredSections.map((section) => {\n const sectionCollapsed = isGroupCollapsed(section.label);\n\n return (\n <div key={section.label} className=\"my-10\">\n <ExpandablePanel\n invisible\n expanded={!sectionCollapsed}\n onExpandedChange={(open) => {\n if (open !== !sectionCollapsed) {\n toggleGroupCollapsed(section.label);\n }\n }}\n className=\"mt-6\"\n titleClassName={cls(\n \"min-h-0 p-0 border-none\",\n \"rounded flex items-center justify-between w-full\",\n \"hover:bg-transparent\",\n \"cursor-pointer select-none\",\n sectionCollapsed && \"bg-surface-field\"\n )}\n innerClassName=\"mt-4 pt-0\"\n title={\n <Typography\n variant=\"caption\"\n component=\"h2\"\n color=\"secondary\"\n className={cls(\n \"px-4 py-1 rounded\",\n \"font-medium text-[10px] uppercase tracking-[0.08em] text-surface-400 dark:text-surface-400\"\n )}\n >\n {groupLabel(section.label)}\n </Typography>\n }\n >\n <div className=\"mt-4 pt-0\">\n <div className=\"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4\">\n {section.tools.map((tool) => (\n <Card\n key={tool.path}\n onClick={() => {\n navigate(tool.path);\n context.analyticsController?.onAnalyticsEvent?.(\n \"home_navigate_to_view\",\n { path: tool.path }\n );\n }}\n className={cls(\n \"group h-full p-4 cursor-pointer transition-colors duration-150 ease-in-out\",\n \"hover:bg-surface-card-hover\"\n )}\n >\n <div className=\"flex flex-col h-full\">\n {/* Header: icon + title */}\n <div className=\"flex items-center w-full justify-between mb-1\">\n <div className=\"flex items-center gap-3\">\n <div className=\"flex items-center justify-center w-5 h-5 text-surface-400 dark:text-surface-500 transition-colors duration-150 group-hover:text-primary dark:group-hover:text-primary\">\n <IconForView\n collectionOrView={{ slug: tool.path, name: tool.name, icon: tool.icon }}\n size=\"small\"\n />\n </div>\n <Typography variant=\"subtitle1\" component=\"h2\">\n {tool.name}\n </Typography>\n </div>\n </div>\n\n {/* Description indented to align with title */}\n <div className=\"pl-8\">\n {tool.description && (\n <Typography variant=\"caption\" color=\"secondary\" component=\"div\">\n {tool.description}\n </Typography>\n )}\n </div>\n\n {/* Spacer */}\n <div className=\"grow\"/>\n </div>\n </Card>\n ))}\n </div>\n </div>\n </ExpandablePanel>\n </div>\n );\n })}\n\n {/* ── SDK Quick Start ── */}\n <div className=\"mt-10 mb-6\">\n <div className=\"flex items-center mb-1\">\n <Typography\n variant=\"caption\"\n component=\"h2\"\n color=\"secondary\"\n className={cls(\n \"px-4 py-1 rounded\",\n \"font-medium text-[10px] uppercase tracking-[0.08em] text-surface-400 dark:text-surface-400\"\n )}\n >\n Quick Start\n </Typography>\n </div>\n\n <Typography variant=\"body2\" color=\"secondary\" className=\"mb-4 max-w-2xl\">\n Generate a fully-typed SDK from your collections with{\" \"}\n <code className=\"text-emerald-400 font-mono text-xs bg-emerald-400/10 px-1.5 py-0.5 rounded\">\n npx rebase generate-sdk\n </code>\n {\" \"}and start querying your data with full TypeScript autocompletion.\n </Typography>\n\n <div className=\"rounded-lg border border-hairline bg-surface-card overflow-hidden\">\n {/* Title bar */}\n <div className=\"flex items-center justify-between px-4 py-2.5 border-b border-hairline bg-surface-sheet\">\n <div className=\"flex items-center gap-2.5\">\n <div className=\"flex gap-1.5\">\n <span className=\"w-2.5 h-2.5 rounded-full bg-red-400/60\"/>\n <span className=\"w-2.5 h-2.5 rounded-full bg-amber-400/60\"/>\n <span className=\"w-2.5 h-2.5 rounded-full bg-emerald-400/60\"/>\n </div>\n <span className=\"text-xs font-mono text-surface-400 dark:text-surface-500 ml-1\">\n app.ts\n </span>\n </div>\n <span className=\"text-xs font-mono text-surface-400 dark:text-surface-500\">\n TypeScript\n </span>\n </div>\n\n {/* Syntax-highlighted code */}\n <div className=\"px-5 py-4 overflow-x-auto text-[13px] leading-6 font-mono\">\n <SyntaxHighlightedSnippet baseUrl={apiUrl}/>\n </div>\n </div>\n </div>\n\n {/* ── Extra sections from props ── */}\n {sections?.map((s) => (\n <div key={s.key} className=\"my-10\">\n <Typography\n variant=\"caption\"\n component=\"h2\"\n color=\"secondary\"\n className={cls(\n \"px-4 py-1 rounded\",\n \"font-medium text-[10px] uppercase tracking-[0.08em] text-surface-400 dark:text-surface-400\"\n )}\n >\n {s.title}\n </Typography>\n <div className=\"mt-4\">{s.children}</div>\n </div>\n ))}\n\n {additionalChildrenEnd}\n </Container>\n </div>\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Hand-crafted syntax-highlighted code snippet.\n Uses inline spans with Tailwind color classes to avoid\n pulling in a syntax highlighting library.\n ═══════════════════════════════════════════════════════════════ */\n\n/**\n * The address the panel's API answers on, as a script would write it: absolute\n * (a same-origin panel is configured with a relative one) and without a\n * trailing slash. It is what `baseUrl` takes — the API's path is the client's.\n */\nfunction absoluteApiUrl(apiUrl: string | undefined): string {\n const page = typeof window !== \"undefined\" ? window.location.href : undefined;\n try {\n return new URL(apiUrl || \"/\", page).href.replace(/\\/+$/, \"\");\n } catch {\n return apiUrl ?? \"\";\n }\n}\n\n/** The quick-start client, pointed at `baseUrl`. */\nfunction SyntaxHighlightedSnippet({ baseUrl }: { baseUrl: string }) {\n const kw = \"text-violet-600 dark:text-violet-400\"; // keywords\n const str = \"text-emerald-600 dark:text-emerald-400\"; // strings\n const typ = \"text-amber-600 dark:text-amber-300\"; // types\n const fn = \"text-blue-600 dark:text-blue-400\"; // functions\n const cm = \"text-surface-500 dark:text-surface-400 italic\"; // comments\n const op = \"text-surface-500 dark:text-surface-400\"; // operators / punctuation\n const tx = \"text-surface-950 dark:text-surface-200\"; // plain text\n\n return (\n <pre className=\"m-0 whitespace-pre\">\n <span className={kw}>import</span>\n <span className={tx}>{\" { \"}</span>\n <span className={fn}>createRebaseClient</span>\n <span className={tx}>{\" } \"}</span>\n <span className={kw}>from</span>\n <span className={tx}> </span>\n <span className={str}>'@rebasepro/client'</span>\n <span className={op}>;</span>\n {\"\\n\"}\n\n <span className={kw}>import</span>\n <span className={tx}>{\" { collectionsDictionary, \"}</span>\n <span className={kw}>type</span>\n <span className={tx}> </span>\n <span className={typ}>Database</span>\n <span className={tx}>{\" } \"}</span>\n <span className={kw}>from</span>\n <span className={tx}> </span>\n <span className={str}>'./database.types'</span>\n <span className={op}>;</span>\n {\"\\n\\n\"}\n\n <span className={kw}>const</span>\n <span className={tx}> rebase </span>\n <span className={op}>= </span>\n <span className={fn}>createRebaseClient</span>\n <span className={op}>{\"<\"}</span>\n <span className={typ}>Database</span>\n <span className={op}>{\">(\"}</span>\n <span className={tx}>{\"{\"}</span>\n {\"\\n\"}\n <span className={tx}>{\" baseUrl\"}</span>\n <span className={op}>: </span>\n <span className={str}>'{baseUrl}'</span>\n <span className={op}>,</span>\n {\"\\n\"}\n {/* Maps each accessor back to its slug: without it a hyphenated\n slug is not reachable from the property name, and the copied\n client 404s on that collection. */}\n <span className={tx}>{\" collections\"}</span>\n <span className={op}>: </span>\n <span className={tx}>collectionsDictionary</span>\n <span className={op}>,</span>\n {\"\\n\"}\n <span className={tx}>{\"}\"}</span>\n <span className={op}>);</span>\n {\"\\n\\n\"}\n\n <span className={cm}>{\"// Fully typed — autocompletion for tables and columns\"}</span>\n {\"\\n\"}\n <span className={kw}>const</span>\n <span className={tx}>{\" { \"}</span>\n <span className={tx}>data</span>\n <span className={op}>: </span>\n <span className={tx}>users</span>\n <span className={tx}>{\" } \"}</span>\n <span className={op}>= </span>\n <span className={kw}>await</span>\n <span className={tx}> rebase</span>\n <span className={op}>.</span>\n <span className={tx}>data</span>\n <span className={op}>.</span>\n <span className={tx}>users</span>\n <span className={op}>.</span>\n <span className={fn}>find</span>\n <span className={op}>();</span>\n {\"\\n\"}\n\n <span className={kw}>const</span>\n <span className={tx}>{\" { \"}</span>\n <span className={tx}>data</span>\n <span className={op}>: </span>\n <span className={tx}>posts</span>\n <span className={tx}>{\" } \"}</span>\n <span className={op}>= </span>\n <span className={kw}>await</span>\n <span className={tx}> rebase</span>\n <span className={op}>.</span>\n <span className={tx}>data</span>\n <span className={op}>.</span>\n <span className={fn}>collection</span>\n <span className={op}>(</span>\n <span className={str}>'posts'</span>\n <span className={op}>)</span>\n <span className={op}>.</span>\n <span className={fn}>find</span>\n <span className={op}>();</span>\n </pre>\n );\n}\n","import React, { Suspense, useLayoutEffect, useMemo } from \"react\";\nimport { useRebaseRegistryDispatch, useTranslation } from \"@rebasepro/app\";\nimport type { RebaseStudioConfig, AppView } from \"@rebasepro/cms-types\";\nimport { CircularProgressCenter, lazyChunk } from \"@rebasepro/ui\";\n\n// Lazy-loaded studio tools — each fetched only when its route is visited.\n// This keeps Monaco, @xyflow/react, dagre, pgsql-ast-parser etc. out of the initial bundle.\nconst SQLEditor = lazyChunk(() => import(\"./SQLEditor/SQLEditor\").then(m => ({ default: m.SQLEditor })));\nconst JSEditor = lazyChunk(() => import(\"./JSEditor/JSEditor\").then(m => ({ default: m.JSEditor })));\nconst RLSEditor = lazyChunk(() => import(\"./RLSEditor/RLSEditor\").then(m => ({ default: m.RLSEditor })));\nconst StorageView = lazyChunk(() => import(\"./StorageView/StorageView\").then(m => ({ default: m.StorageView })));\nconst CronJobsView = lazyChunk(() => import(\"./CronJobs/CronJobsView\").then(m => ({ default: m.CronJobsView })));\nconst SchemaVisualizer = lazyChunk(() => import(\"./SchemaVisualizer/SchemaVisualizer\").then(m => ({ default: m.SchemaVisualizer })));\nconst BranchesView = lazyChunk(() => import(\"./Branches/BranchesView\").then(m => ({ default: m.BranchesView })));\nconst BackupsView = lazyChunk(() => import(\"./Backups/BackupsView\").then(m => ({ default: m.BackupsView })));\nconst ApiExplorer = lazyChunk(() => import(\"./ApiExplorer/ApiExplorer\").then(m => ({ default: m.ApiExplorer })));\nconst LogsExplorer = lazyChunk(() => import(\"./LogsExplorer/LogsExplorer\").then(m => ({ default: m.LogsExplorer })));\nconst ApiKeysView = lazyChunk(() => import(\"./ApiKeys/ApiKeysView\").then(m => ({ default: m.ApiKeysView })));\n\nimport { StudioHomePage } from \"./StudioHomePage\";\n\n/**\n * Declarative component to configure the Studio in Rebase.\n * Renders nothing — purely registers config into the RebaseRegistry.\n *\n * The \"schema\" tool (collection editor view) is a Studio tool, but it is not\n * registered here: it ships from the panel package because it needs the project's\n * collection source to write back to. When `<RebaseCMS collectionEditor={...}>`\n * is used, the schema view is automatically injected into Studio — no manual\n * wiring needed. Where it is mounted from is an implementation detail; it is a\n * schema-editing tool and belongs beside SQL and RLS.\n */\nconst DEFAULT_HOME_PAGE = <StudioHomePage/>;\n\nexport function RebaseStudio({ tools, homePage, devViews: extraViews }: RebaseStudioConfig) {\n const dispatch = useRebaseRegistryDispatch();\n const { t, i18n } = useTranslation();\n\n const resolvedHomePage = homePage ?? DEFAULT_HOME_PAGE;\n\n /**\n * The tool list reduced to a value, so that re-rendering the host does not\n * republish the registry.\n *\n * `tools` is an array, and callers write it inline — `tools={[...TOOLS]}`\n * in the hosted console. A fresh array every render meant a fresh\n * `devViews` every render, which meant the effect below unregistered and\n * re-registered on every render. Because each registration builds *new*\n * `<Suspense><SQLEditor/></Suspense>` elements, whatever view was on screen\n * was torn down and remounted each time: a half-typed SQL query, a storage\n * folder you had navigated into, an open policy editor — all discarded, and\n * every mount reissued the view's initial requests.\n */\n const toolsKey = tools ? tools.join(\",\") : \"\";\n\n const devViews: AppView[] = useMemo(() => {\n const views: AppView[] = [];\n const activeTools = tools ?? [\"sql\", \"js\", \"rls\", \"storage\", \"cron\", \"schema-visualizer\", \"branches\", \"backups\", \"api\", \"logs\", \"api-keys\"];\n const suspense = (el: React.ReactNode) => <Suspense fallback={<CircularProgressCenter/>}>{el}</Suspense>;\n\n if (activeTools.includes(\"sql\")) {\n views.push({ slug: \"sql\",\nname: t(\"studio_tool_sql\"),\ngroup: \"Database\",\nicon: \"terminal\",\ndescription: t(\"studio_tool_sql_description\"),\nview: suspense(<SQLEditor/>) });\n }\n if (activeTools.includes(\"js\")) {\n views.push({ slug: \"js\",\nname: t(\"studio_tool_js\"),\ngroup: \"Compute\",\nicon: \"code\",\ndescription: t(\"studio_tool_js_description\"),\nview: suspense(<JSEditor/>) });\n }\n if (activeTools.includes(\"rls\")) {\n views.push({ slug: \"rls\",\nname: t(\"studio_tool_rls\"),\ngroup: \"Database\",\nicon: \"ShieldCheck\",\ndescription: t(\"studio_tool_rls_description\"),\nview: suspense(<RLSEditor/>) });\n }\n if (activeTools.includes(\"storage\")) {\n views.push({ slug: \"storage\",\nname: t(\"studio_tool_storage\"),\ngroup: \"Storage\",\nicon: \"HardDrive\",\ndescription: t(\"studio_tool_storage_description\"),\nview: suspense(<StorageView/>) });\n }\n if (activeTools.includes(\"cron\")) {\n views.push({ slug: \"cron\",\nname: t(\"studio_tool_cron\"),\ngroup: \"Compute\",\nicon: \"Clock\",\ndescription: t(\"studio_tool_cron_description\"),\nview: suspense(<CronJobsView/>) });\n }\n if (activeTools.includes(\"schema-visualizer\")) {\n views.push({ slug: \"schema-visualizer\",\nname: t(\"studio_tool_schema_visualizer\"),\ngroup: \"Database\",\nicon: \"Network\",\ndescription: t(\"studio_tool_schema_visualizer_description\"),\nview: suspense(<SchemaVisualizer/>) });\n }\n if (activeTools.includes(\"branches\")) {\n views.push({ slug: \"branches\",\nname: t(\"studio_tool_branches\"),\ngroup: \"Database\",\nicon: \"GitBranch\",\ndescription: t(\"studio_tool_branches_description\"),\nview: suspense(<BranchesView/>) });\n }\n if (activeTools.includes(\"backups\")) {\n views.push({ slug: \"backups\",\nname: t(\"studio_tool_backups\"),\ngroup: \"Database\",\nicon: \"Database\",\ndescription: t(\"studio_tool_backups_description\"),\nview: suspense(<BackupsView/>) });\n }\n if (activeTools.includes(\"api\")) {\n views.push({ slug: \"api\",\nname: t(\"studio_tool_api\"),\ngroup: \"API\",\nicon: \"BookOpen\",\ndescription: t(\"studio_tool_api_description\"),\nview: suspense(<ApiExplorer/>) });\n }\n if (activeTools.includes(\"logs\")) {\n views.push({ slug: \"logs\",\nname: t(\"studio_tool_logs\"),\ngroup: \"Database\",\nicon: \"Activity\",\ndescription: t(\"studio_tool_logs_description\"),\nview: suspense(<LogsExplorer/>) });\n }\n if (activeTools.includes(\"api-keys\")) {\n views.push({ slug: \"api-keys\",\nname: t(\"studio_tool_api_keys\"),\ngroup: \"Access Control\",\nicon: \"KeyRound\",\ndescription: t(\"studio_tool_api_keys_description\"),\nview: suspense(<ApiKeysView/>) });\n }\n // Note: \"schema\" tool is auto-injected by RebaseShell when collectionEditor is enabled.\n // It is NOT registered here anymore.\n return views;\n // Keyed by the tool list's *contents*; see `toolsKey`. `tools` itself is\n // read inside, and is exactly determined by the key.\n // The strings are now translated, so the active language is part of\n // what this list is.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [toolsKey, t, i18n.language]);\n\n /**\n * Your own tools, keyed the same way `tools` is and for the same reason:\n * callers write `devViews={[…]}` inline, so the array is new on every\n * render. Re-registering would tear down and remount whichever Studio view\n * was on screen — a half-typed SQL query, an open policy editor.\n *\n * The key is the identity of each view, not its element: a view's `view` is\n * resolved by the router at render time, so a fresh element for the same\n * slug is not a configuration change.\n */\n const extraViewsKey = (extraViews ?? [])\n .map((v) => `${v.slug}|${v.name}|${v.group ?? \"\"}|${v.hideFromNavigation ?? false}`)\n .join(\",\");\n const extraViewsRef = React.useRef(extraViews);\n extraViewsRef.current = extraViews;\n\n const allDevViews: AppView[] = useMemo(\n () => [...devViews, ...(extraViewsRef.current ?? [])],\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [devViews, extraViewsKey]\n );\n\n // Use a ref for homePage so it never destabilizes the effect.\n // homePage is a React element — its identity doesn't matter for registration.\n const homePageRef = React.useRef(resolvedHomePage);\n homePageRef.current = resolvedHomePage;\n\n // Same reasoning for `tools`: it is registered as config, but a new array\n // with the same contents must not count as a change.\n const toolsRef = React.useRef(tools);\n toolsRef.current = tools;\n\n useLayoutEffect(() => {\n dispatch.registerStudio({ tools: toolsRef.current,\nhomePage: homePageRef.current,\ndevViews: allDevViews });\n return () => dispatch.unregisterStudio();\n }, [dispatch, allDevViews]);\n\n return null;\n}\n"],"mappings":";;;;;;;;AA4BA,IAAM,cAAc;CAAC;CAAY;CAAW;CAAW;CAAO;AAAgB;AAE9E,IAAM,kBAAkB;;;;;;;AAQxB,SAAS,cAAc,OAA0C;CAC7D,MAAM,0BAAU,IAAI,IAA0B;CAE9C,KAAK,MAAM,QAAQ,OAAO;EACtB,IAAI,KAAK,oBAAoB;EAC7B,MAAM,QAAQ,KAAK,SAAS;EAC5B,MAAM,QAAQ,QAAQ,IAAI,KAAK,KAAK,CAAC;EACrC,MAAM,KAAK;GACP,MAAM,IAAI,KAAK;GACf,MAAM,KAAK;GACX,aAAa,KAAK,eAAe;GACjC,MAAM,KAAK;EACf,CAAC;EACD,QAAQ,IAAI,OAAO,KAAK;CAC5B;CAOA,OAAO,CAJH,GAAG,YAAY,QAAO,MAAK,QAAQ,IAAI,CAAC,CAAC,GACzC,GAAG,CAAC,GAAG,QAAQ,KAAK,CAAC,CAAC,CAAC,QAAO,MAAK,CAAC,YAAY,SAAS,CAAC,CAAC,CAGxD,CAAA,CAAQ,KAAI,WAAU;EAAE;EACnC,OAAO,QAAQ,IAAI,KAAK;CAAG,EAAE;AAC7B;AAIA,IAAM,wBAAwB;AAE9B,SAAS,yBAAyB,YAAsB;CACpD,MAAM,CAAC,WAAW,gBAAgB,eAA4B;EAC1D,IAAI;GACA,MAAM,SAAS,aAAa,QAAQ,qBAAqB;GACzD,OAAO,SAAS,IAAI,IAAI,KAAK,MAAM,MAAM,CAAC,oBAAI,IAAI,IAAY;EAClE,QAAQ;GACJ,uBAAO,IAAI,IAAY;EAC3B;CACJ,CAAC;CAED,MAAM,oBAAoB,SAAiB,UAAU,IAAI,IAAI;CAE7D,MAAM,wBAAwB,SAAiB;EAC3C,cA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AAM,WAAW,MAAM,OAAO,KAAK;CACnC,SAAS,UAAU;CAEnB,sBAAsB;EAClB,SAAS,eAAe;GAAE,OAAO,SAAS;GAClD,UAAU,YAAY;GACtB,UAAU;EAAY,CAAC;EACf,aAAa,SAAS,iBAAiB;CAC3C,GAAG,CAAC,UAAU,WAAW,CAAC;CAE1B,OAAO;AACX"}
|
|
@@ -88,6 +88,24 @@ function quoteTableName(tableName, schemaName) {
|
|
|
88
88
|
function quoteIdentifier(identifier) {
|
|
89
89
|
return `"${identifier.replace(/"/g, "\"\"")}"`;
|
|
90
90
|
}
|
|
91
|
+
/**
|
|
92
|
+
* The schema browser's statements for `table`, every name in them quoted. A
|
|
93
|
+
* name is folded to lower case unless it is quoted, so `Posts` reads a table
|
|
94
|
+
* `posts` that is not there and a column `createdAt` one called `createdat`;
|
|
95
|
+
* and a reserved word is not a name at all — `SELECT * FROM user` answers
|
|
96
|
+
* with the current role instead of reading the table. A table in `public` is
|
|
97
|
+
* named without its schema.
|
|
98
|
+
*/
|
|
99
|
+
function tableStatementTemplates(schemaName, table) {
|
|
100
|
+
const from = schemaName === "public" ? quoteIdentifier(table.tableName) : quoteTableName(table.tableName, schemaName);
|
|
101
|
+
const columns = table.columns.map((column) => quoteIdentifier(column.name));
|
|
102
|
+
return {
|
|
103
|
+
selectTop: `SELECT * FROM ${from} LIMIT 100;`,
|
|
104
|
+
selectAll: `SELECT \n ${columns.join(",\n ")}\nFROM ${from};`,
|
|
105
|
+
insert: `INSERT INTO ${from} (\n ${columns.join(",\n ")}\n) VALUES (\n ${columns.map(() => "?").join(",\n ")}\n);`,
|
|
106
|
+
update: `UPDATE ${from} \nSET \n ${columns.map((column) => `${column} = ?`).join(",\n ")}\nWHERE id = ?;`
|
|
107
|
+
};
|
|
108
|
+
}
|
|
91
109
|
var refuse = (key, params = {}) => ({ refusal: {
|
|
92
110
|
key,
|
|
93
111
|
params
|
|
@@ -473,6 +491,6 @@ function typedJsonRows(rows, columns) {
|
|
|
473
491
|
return rows.map((row) => Object.fromEntries(Object.entries(row).map(([key, value]) => [key, typedValue(value, typeByName.get(key))])));
|
|
474
492
|
}
|
|
475
493
|
//#endregion
|
|
476
|
-
export { needsDestructiveConfirmation as a, rememberColumnWidth as c, resultsToCsv as d,
|
|
494
|
+
export { needsDestructiveConfirmation as a, rememberColumnWidth as c, resultsToCsv as d, tableStatementTemplates as f, withAutoLimit as h, keepLatestColumnWidths as i, resolveCellEdit as l, typedJsonRows as m, formatSql as n, quoteIdentifier as o, toCsv as p, groupSchemaRows as r, quoteTableName as s, buildExplainSql as t, resolveQueryCollections as u };
|
|
477
495
|
|
|
478
|
-
//# sourceMappingURL=sql_utils-
|
|
496
|
+
//# sourceMappingURL=sql_utils-DXvmxiCq.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sql_utils-DXvmxiCq.js","names":[],"sources":["../src/utils/sql_utils.ts"],"sourcesContent":["import { astVisitor, parse, type Statement } from \"pgsql-ast-parser\";\nimport { csvRecord, toSnakeCase } from \"@rebasepro/utils\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport type { SqlScriptResult } from \"@rebasepro/types\";\nimport type { TableInfo } from \"../components/SQLEditor/sql_editor_types\";\n\n/** The statements in `sqlText`, or `null` when the parser cannot read it. */\nfunction parseStatements(sqlText: string): Statement[] | null {\n try {\n return parse(sqlText);\n } catch {\n return null;\n }\n}\n\n/**\n * The `EXPLAIN` for one statement, or `null` when `sqlText` is not exactly one.\n *\n * Never `ANALYZE`: that executes the statement to time it, so explaining a\n * `DELETE` deleted the rows — without the confirmation \"Run\" asks for.\n *\n * And never more than one statement. Sent as one simple query, `EXPLAIN (…)\n * SELECT 1; DELETE …` explains the SELECT and *runs* the DELETE. Text the\n * parser cannot read is still explained, as long as no `;` could be hiding a\n * second statement in it.\n */\nexport function buildExplainSql(sqlText: string): string | null {\n const statement = sqlText.trim().replace(/;+$/, \"\").trim();\n if (!statement) return null;\n const statements = parseStatements(statement);\n const single = statements ? statements.length === 1 : !statement.includes(\";\");\n return single ? `EXPLAIN (FORMAT JSON) ${statement}` : null;\n}\n\n/**\n * Whether the console's automatic `LIMIT` may be appended to `sqlText`: one\n * top-level SELECT that has no limit of its own.\n *\n * Decided on the parsed statement, not the text. A search for the word SELECT\n * also found it inside `INSERT INTO … SELECT` and `CREATE TABLE … AS SELECT`,\n * which then copied a thousand rows and reported success, and at the start of\n * a script whose last statement the appended `LIMIT` turned into a syntax\n * error. Text the parser cannot read is left as written.\n */\nexport function acceptsAutoLimit(sqlText: string): boolean {\n const statements = parseStatements(sqlText);\n if (!statements || statements.length !== 1) return false;\n const [statement] = statements;\n return statement.type === \"select\" && !statement.limit;\n}\n\n/** A destructive command named anywhere in a text, comments included. */\nconst DESTRUCTIVE_COMMAND = /\\b(DELETE|UPDATE|DROP|TRUNCATE)\\b/i;\n\nfunction isDestructiveStatement(statement: Statement): boolean {\n switch (statement.type) {\n case \"delete\":\n case \"update\":\n return !statement.where;\n case \"truncate table\":\n case \"drop table\":\n case \"drop sequence\":\n case \"drop index\":\n case \"drop type\":\n case \"drop trigger\":\n case \"drop function\":\n return true;\n case \"alter table\":\n return statement.changes.some(change => change.type === \"drop column\" || change.type === \"drop constraint\");\n case \"with\":\n return statement.bind.some(binding => isDestructiveStatement(binding.statement)) ||\n isDestructiveStatement(statement.in);\n case \"with recursive\":\n return isDestructiveStatement(statement.in);\n case \"do\":\n return DESTRUCTIVE_COMMAND.test(statement.code);\n default:\n return false;\n }\n}\n\n/**\n * Whether \"Run\" asks before running `sqlText`: a statement in it deletes or\n * updates without a WHERE of its own, drops or truncates.\n *\n * Decided per parsed statement, not on the text. A search of the text for the\n * word WHERE found it in another statement or in a comment, so `DELETE FROM\n * posts; SELECT * FROM posts WHERE id = 1` deleted every post without asking.\n * Text the parser cannot read is confirmed whenever it names a destructive\n * command.\n */\nexport function needsDestructiveConfirmation(sqlText: string): boolean {\n const statements = parseStatements(sqlText);\n if (!statements) return DESTRUCTIVE_COMMAND.test(sqlText);\n return statements.some(isDestructiveStatement);\n}\n\n/**\n * A table as SQL: `\"schema\".\"table\"` when a schema is given, a bare `\"table\"`\n * otherwise.\n */\nexport function quoteTableName(tableName: string, schemaName?: string): string {\n return schemaName ? `${quoteIdentifier(schemaName)}.${quoteIdentifier(tableName)}` : quoteIdentifier(tableName);\n}\n\n/** An identifier as SQL, whatever it holds: double-quoted, with `\"` doubled. */\nexport function quoteIdentifier(identifier: string): string {\n return `\"${identifier.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n\n/**\n * The schema browser's statements for `table`, every name in them quoted. A\n * name is folded to lower case unless it is quoted, so `Posts` reads a table\n * `posts` that is not there and a column `createdAt` one called `createdat`;\n * and a reserved word is not a name at all — `SELECT * FROM user` answers\n * with the current role instead of reading the table. A table in `public` is\n * named without its schema.\n */\nexport function tableStatementTemplates(schemaName: string, table: Pick<TableInfo, \"tableName\" | \"columns\">): {\n selectTop: string;\n selectAll: string;\n insert: string;\n update: string;\n} {\n const from = schemaName === \"public\" ? quoteIdentifier(table.tableName) : quoteTableName(table.tableName, schemaName);\n const columns = table.columns.map(column => quoteIdentifier(column.name));\n return {\n selectTop: `SELECT * FROM ${from} LIMIT 100;`,\n selectAll: `SELECT \\n ${columns.join(\",\\n \")}\\nFROM ${from};`,\n insert: `INSERT INTO ${from} (\\n ${columns.join(\",\\n \")}\\n) VALUES (\\n ${columns.map(() => \"?\").join(\",\\n \")}\\n);`,\n update: `UPDATE ${from} \\nSET \\n ${columns.map(column => `${column} = ?`).join(\",\\n \")}\\nWHERE id = ?;`\n };\n}\n\n/** What the console knows about a result: its columns, and the tables they came from. */\nexport type ResultProvenance = Pick<SqlScriptResult, \"columns\" | \"tables\">;\n\n/**\n * The stored cell a result cell is, and the key that finds its row.\n */\nexport interface CellEditTarget {\n schema: string;\n table: string;\n /** The table column the edited value is written to. */\n column: string;\n /** Each primary key column of the table, and the result column holding its value for the row. */\n key: { column: string; resultColumn: string }[];\n}\n\n/**\n * Why a cell cannot be edited: a translation key of the console's, and its\n * parameters.\n */\nexport interface CellEditRefusal {\n key:\n | \"studio_sql_edit_unreadable_query\"\n | \"studio_sql_edit_not_a_select\"\n | \"studio_sql_edit_duplicate_column\"\n | \"studio_sql_edit_computed_column\"\n | \"studio_sql_edit_not_a_table\"\n | \"studio_sql_edit_inherited_table\"\n | \"studio_sql_edit_no_primary_key\"\n | \"studio_sql_edit_key_missing\"\n | \"studio_sql_edit_table_read_twice\";\n params: Record<string, string>;\n}\n\nexport type CellEditResolution =\n | { target: CellEditTarget; refusal?: undefined }\n | { target?: undefined; refusal: CellEditRefusal };\n\nconst refuse = (key: CellEditRefusal[\"key\"], params: Record<string, string> = {}): CellEditResolution =>\n ({ refusal: { key, params } });\n\n/**\n * Which stored cell an edit of the result column `resultColumn` writes, and\n * how its row is found again — or why no edit is safe.\n *\n * Decided on what the database reported, not on the query's text. Each\n * column of the result says which table column it was read from, or that it\n * was computed; a cell is editable only when it was read from a column of a\n * table, every column of that table's primary key was read too, and each of\n * them is the only column of the result with its name — a row holds one value\n * per name.\n *\n * The text was the only evidence before, and it was wrong twice over. For\n * `SELECT p.id, a.name FROM posts p JOIN authors a …` it took the post's `id`\n * for the author's key and updated whichever author shared the post's id.\n * For `SELECT id, lower(email) AS name FROM users` it wrote the edited text\n * to `users.name`.\n *\n * The database reports a table, not which mention of it: in a self-join both\n * sides are `authors`, and a key from one with a value from the other finds\n * the wrong row. So the query is still read, for one thing — the table must\n * be read once, and nothing it is read through may be read twice.\n */\nexport function resolveCellEdit(sqlText: string, provenance: ResultProvenance, resultColumn: string): CellEditResolution {\n const sameName = provenance.columns.filter(column => column.name === resultColumn);\n if (sameName.length !== 1) return refuse(\"studio_sql_edit_duplicate_column\", { column: resultColumn });\n const source = sameName[0].source;\n if (!source) return refuse(\"studio_sql_edit_computed_column\", { column: resultColumn });\n\n const tableLabel = `${source.schema}.${source.table}`;\n const table = provenance.tables.find(t => t.schema === source.schema && t.table === source.table);\n if (!table || (table.kind !== \"table\" && table.kind !== \"partitioned table\")) {\n return refuse(\"studio_sql_edit_not_a_table\", { column: resultColumn, table: tableLabel });\n }\n if (table.hasInheritors) return refuse(\"studio_sql_edit_inherited_table\", { table: tableLabel });\n if (table.primaryKey.length === 0) return refuse(\"studio_sql_edit_no_primary_key\", { table: tableLabel });\n\n const key: CellEditTarget[\"key\"] = [];\n for (const keyColumn of table.primaryKey) {\n const holders = provenance.columns.filter(column =>\n column.source?.schema === source.schema &&\n column.source.table === source.table &&\n column.source.column === keyColumn);\n const holder = holders.length === 1 && provenance.columns.filter(column => column.name === holders[0].name).length === 1\n ? holders[0]\n : undefined;\n if (!holder) return refuse(\"studio_sql_edit_key_missing\", { table: tableLabel, columns: table.primaryKey.join(\", \") });\n key.push({ column: keyColumn, resultColumn: holder.name });\n }\n\n const readOnce = tableReadOnce(sqlText, source.table);\n if (readOnce !== true) return readOnce;\n\n return { target: { schema: source.schema, table: source.table, column: source.column, key } };\n}\n\n/**\n * Whether `sqlText` is one SELECT that reads `table` once — counting every\n * mention of a table of that name, in any schema and at any depth, and every\n * mention of a `WITH` query, since one read twice reads its tables twice.\n */\nfunction tableReadOnce(sqlText: string, table: string): true | CellEditResolution {\n const statements = parseStatements(sqlText);\n if (!statements) return refuse(\"studio_sql_edit_unreadable_query\");\n if (statements.length !== 1) return refuse(\"studio_sql_edit_not_a_select\");\n const [statement] = statements;\n const isRead = statement.type === \"select\" ||\n (statement.type === \"with\" &&\n statement.in.type === \"select\" &&\n statement.bind.every(binding => binding.statement.type === \"select\"));\n if (!isRead) return refuse(\"studio_sql_edit_not_a_select\");\n\n const mentions = new Map<string, number>();\n const withNames: string[] = [];\n astVisitor(visitor => ({\n fromTable: from => {\n const name = from.name.name.toLowerCase();\n mentions.set(name, (mentions.get(name) ?? 0) + 1);\n visitor.super().fromTable(from);\n },\n with: withStatement => {\n withNames.push(...withStatement.bind.map(binding => binding.alias.name.toLowerCase()));\n visitor.super().with(withStatement);\n }\n })).statement(statement);\n\n const readTwice = (mentions.get(table.toLowerCase()) ?? 0) !== 1 ||\n withNames.some(name => (mentions.get(name) ?? 0) > 1);\n return readTwice ? refuse(\"studio_sql_edit_table_read_twice\", { table }) : true;\n}\n\n/**\n * A collection whose records a query's rows can be opened as.\n */\nexport interface ResolvedQueryCollection {\n /** The table, as the database named it. */\n tableName: string;\n schemaName: string;\n /** The matched collection */\n collection: AdminCollection;\n /** The result column that holds the table's primary key. */\n pkColumn: string;\n}\n\n/**\n * The collections a result's rows can be opened as: those whose table one of\n * the result's columns was read from, with the table's (single-column) primary\n * key read too, under a name no other column of the result has.\n *\n * Matched on the provenance the database reported. A text match took the\n * result's `id` for every table of a join: `SELECT p.id, a.name FROM posts p\n * JOIN authors a …` offered to open the author whose id was the post's.\n */\nexport function resolveQueryCollections(provenance: ResultProvenance, collections: AdminCollection[]): ResolvedQueryCollection[] {\n const results: ResolvedQueryCollection[] = [];\n for (const table of provenance.tables) {\n const collection = collections.find(c => {\n const tableName = (\"table\" in c ? c.table : undefined) || toSnakeCase(c.slug);\n const schemaName = (\"schema\" in c ? c.schema : undefined) || \"public\";\n return tableName === table.table && schemaName === table.schema;\n });\n if (!collection || table.primaryKey.length !== 1) continue;\n const [keyColumn] = table.primaryKey;\n const holders = provenance.columns.filter(column =>\n column.source?.schema === table.schema &&\n column.source.table === table.table &&\n column.source.column === keyColumn);\n if (holders.length !== 1) continue;\n const pkColumn = holders[0].name;\n if (provenance.columns.filter(column => column.name === pkColumn).length !== 1) continue;\n results.push({ tableName: table.table, schemaName: table.schema, collection, pkColumn });\n }\n return results;\n}\n\n/**\n * A stretch of SQL text, by what it is to the database: code, or text that is\n * data and must not be rewritten — a string literal (quoted, `E'…'` or\n * dollar-quoted), a quoted identifier, or a comment.\n */\ninterface SqlSegment {\n text: string;\n kind: \"code\" | \"literal\" | \"identifier\" | \"line comment\" | \"block comment\";\n}\n\n/** A character an unquoted identifier or keyword can hold, `$` included. */\nconst IDENTIFIER_CHARACTER = /[A-Za-z0-9_$]/;\n\n/**\n * Cut `sqlText` into code and the things in it whose text is data.\n *\n * A lexer, not a parser: it reads text the parser refuses as well, which is\n * most of what a person types while writing a query.\n */\nfunction splitSql(sqlText: string): SqlSegment[] {\n const segments: SqlSegment[] = [];\n let code = \"\";\n const push = (text: string, kind: SqlSegment[\"kind\"]) => {\n if (code) segments.push({ text: code, kind: \"code\" });\n code = \"\";\n segments.push({ text, kind });\n };\n let i = 0;\n while (i < sqlText.length) {\n const ch = sqlText[i];\n const next = sqlText[i + 1];\n if (ch === \"-\" && next === \"-\") {\n const newline = sqlText.indexOf(\"\\n\", i);\n const end = newline === -1 ? sqlText.length : newline + 1;\n push(sqlText.slice(i, end), \"line comment\");\n i = end;\n continue;\n }\n if (ch === \"/\" && next === \"*\") {\n // Block comments nest in Postgres.\n let depth = 1;\n let j = i + 2;\n while (j < sqlText.length && depth > 0) {\n if (sqlText[j] === \"/\" && sqlText[j + 1] === \"*\") {\n depth++;\n j += 2;\n } else if (sqlText[j] === \"*\" && sqlText[j + 1] === \"/\") {\n depth--;\n j += 2;\n } else {\n j++;\n }\n }\n push(sqlText.slice(i, j), \"block comment\");\n i = j;\n continue;\n }\n if (ch === \"'\" || ch === \"\\\"\") {\n // `E'…'` takes backslash escapes; every quoted text takes its\n // quote doubled.\n const backslashEscapes = ch === \"'\" && /(^|[^A-Za-z0-9_$])[eE]$/.test(code);\n let j = i + 1;\n while (j < sqlText.length) {\n if (backslashEscapes && sqlText[j] === \"\\\\\") {\n j += 2;\n } else if (sqlText[j] === ch && sqlText[j + 1] === ch) {\n j += 2;\n } else if (sqlText[j] === ch) {\n j++;\n break;\n } else {\n j++;\n }\n }\n push(sqlText.slice(i, j), ch === \"'\" ? \"literal\" : \"identifier\");\n i = j;\n continue;\n }\n if (ch === \"$\" && !IDENTIFIER_CHARACTER.test(code.slice(-1))) {\n // `$tag$…$tag$` — not `$1`, a parameter, whose tag would start\n // with a digit.\n const tag = /^\\$(?:[A-Za-z_][A-Za-z0-9_]*)?\\$/.exec(sqlText.slice(i));\n if (tag) {\n const close = sqlText.indexOf(tag[0], i + tag[0].length);\n const end = close === -1 ? sqlText.length : close + tag[0].length;\n push(sqlText.slice(i, end), \"literal\");\n i = end;\n continue;\n }\n }\n code += ch;\n i++;\n }\n if (code) segments.push({ text: code, kind: \"code\" });\n return segments;\n}\n\n/**\n * The console's \"Format SQL\": runs of whitespace become one space, a comma is\n * followed by one, and an `=` standing alone gets one on each side — in the\n * code only.\n *\n * A literal, a quoted identifier and a comment are copied as they are: their\n * text is data, and rewriting `'a,b'` to `'a, b'` changes the value the next\n * Run writes. A line comment keeps the line break that ends it, or it would\n * swallow the code after it. `>=`, `<=`, `!=`, `:=` and `=>` are operators of\n * their own and are left whole.\n */\nexport function formatSql(sqlText: string): string {\n const segments = splitSql(sqlText);\n return segments.map((segment, index) => {\n if (segment.kind !== \"code\") return segment.text;\n const tidied = segment.text\n .replace(/\\s+/g, \" \")\n .replace(/\\s*,\\s*/g, \", \")\n .replace(/(?<![<>!:=~*+\\-/%^&|#@?])\\s*=\\s*(?![=>~*<])/g, \" = \");\n return segments[index - 1]?.kind === \"line comment\" ? tidied.trimStart() : tidied;\n }).join(\"\").trim();\n}\n\n/**\n * `sqlText` with the console's automatic `LIMIT` on it, or `null` when it\n * takes none (see {@link acceptsAutoLimit}).\n *\n * The limit goes straight after the statement's last token — before a\n * trailing comment, which would otherwise swallow it, and in place of a\n * trailing `;`. A query that computes an aggregate is limited like any other:\n * the limit applies to the rows it returns, so a `count(*)` still counts every\n * row, and a window `count(*) OVER ()` is no longer a way past the cap.\n */\nexport function withAutoLimit(sqlText: string, limit: number): string | null {\n if (!acceptsAutoLimit(sqlText)) return null;\n const segments = splitSql(sqlText);\n const isComment = (segment: SqlSegment) => segment.kind === \"line comment\" || segment.kind === \"block comment\";\n const isFiller = (segment: SqlSegment) => isComment(segment) || (segment.kind === \"code\" && /^[\\s;]*$/.test(segment.text));\n let last = segments.length - 1;\n while (last >= 0 && isFiller(segments[last])) last--;\n if (last < 0) return null;\n\n const lastSegment = segments[last];\n const head = lastSegment.kind === \"code\" ? lastSegment.text.replace(/[\\s;]+$/, \"\") : lastSegment.text;\n const after = lastSegment.kind === \"code\" ? lastSegment.text.slice(head.length) : \"\";\n // What follows the statement is comments and the space between them; its\n // `;` are dropped, the limit brings its own.\n const tail = after.replace(/;/g, \"\") + segments.slice(last + 1)\n .map(segment => segment.kind === \"code\" ? segment.text.replace(/;/g, \"\") : segment.text)\n .join(\"\");\n const before = segments.slice(0, last).map(segment => segment.text).join(\"\");\n return `${before}${head} LIMIT ${limit};${tail.trimEnd()}`;\n}\n\n/**\n * Rows as CSV text: a header record of column names, then one record per\n * row, each value under its own column.\n *\n * RFC 4180 with every record ended by CRLF — byte for byte what\n * `POST /api/admin/sql/csv` streams for the same result, so \"Export CSV\" and\n * \"Download full result as CSV\" write one format. They used to differ in\n * the line break (LF here), which a diff, a checksum or a strict reader\n * notices.\n */\nexport function toCsv(columns: readonly string[], rows: readonly Record<string, unknown>[]): string {\n const records = [csvRecord(columns), ...rows.map(row => csvRecord(columns.map(column => row[column])))];\n return records.map(record => record + \"\\r\\n\").join(\"\");\n}\n\n/**\n * The rows on screen as CSV text — {@link toCsv} over the first row's\n * columns.\n *\n * A value was quoted only when it held a comma, and a quote in it was never\n * doubled nor a line break quoted, so `say \"hi\"` or a two-line note broke the\n * row it was in.\n */\nexport function resultsToCsv(rows: Record<string, unknown>[]): string {\n if (rows.length === 0) return \"\";\n return toCsv(Object.keys(rows[0]), rows);\n}\n\n/** Column widths per query, as the console keeps them: SQL text → column → width. */\nexport type ColumnWidthsByQuery = Record<string, Record<string, number>>;\n\n/** How many queries' column widths the console remembers. */\nexport const COLUMN_WIDTHS_REMEMBERED = 50;\n\n/**\n * The widths kept, at most `limit` queries' worth, the most recently resized\n * last.\n *\n * They are kept per query text, in `localStorage`, and used to be kept\n * forever: every query anybody ever resized a column of stayed, whole SQL\n * text and all, in an origin's storage — which the console's tabs, snippets\n * and history share, and which a full store refuses to write at all. The\n * oldest go first; resizing a query's column again makes it the newest.\n */\nexport function rememberColumnWidth(\n widths: ColumnWidthsByQuery,\n sql: string,\n column: string,\n width: number,\n limit: number = COLUMN_WIDTHS_REMEMBERED\n): ColumnWidthsByQuery {\n const { [sql]: current, ...others } = widths;\n return keepLatestColumnWidths({ ...others, [sql]: { ...current, [column]: width } }, limit);\n}\n\n/**\n * The `limit` most recent queries' widths — the last ones in insertion\n * order — and only entries that are a column → width record.\n */\nexport function keepLatestColumnWidths(widths: Record<string, unknown>, limit: number = COLUMN_WIDTHS_REMEMBERED): ColumnWidthsByQuery {\n const kept: ColumnWidthsByQuery = {};\n for (const [sql, value] of Object.entries(widths).slice(-limit)) {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) continue;\n const columns: Record<string, number> = {};\n for (const [column, width] of Object.entries(value)) {\n if (typeof width === \"number\" && Number.isFinite(width)) columns[column] = width;\n }\n kept[sql] = columns;\n }\n return kept;\n}\n\n/**\n * The schema browser's tables, by schema, from `information_schema.columns`\n * rows: each table in the order it first appears, its columns in row order.\n *\n * A table is found by its key, not looked up among the schema's tables: that\n * lookup ran once per row over every table so far — 142 ms at 2,000 tables,\n * 923 ms at 5,000, on every open of the console.\n */\nexport function groupSchemaRows(data: Record<string, unknown>[]): Record<string, TableInfo[]> {\n const grouped: Record<string, TableInfo[]> = {};\n const tables = new Map<string, TableInfo>();\n for (const curr of data) {\n const schema = (curr.schema || curr.SCHEMA || curr.table_schema || \"public\") as string;\n const table = (curr.table || curr.TABLE || curr.table_name) as string;\n const column = (curr.column || curr.COLUMN || curr.column_name) as string;\n const dataType = (curr.data_type || curr.DATA_TYPE || \"\") as string;\n const isPrimaryKey = curr.is_pk === true || curr.is_pk === \"true\";\n\n const key = `${schema}\\u0000${table}`;\n let tableInfo = tables.get(key);\n if (!tableInfo) {\n tableInfo = { schemaName: schema, tableName: table, columns: [] };\n tables.set(key, tableInfo);\n (grouped[schema] ??= []).push(tableInfo);\n }\n tableInfo.columns.push({ name: column, dataType, isPrimaryKey });\n }\n return grouped;\n}\n\nconst INTEGER_TYPES = new Set([\"smallint\", \"integer\", \"bigint\"]);\nconst FLOAT_TYPES = new Set([\"real\", \"double precision\"]);\n\n/** How many significant digits a plain decimal (`-0012.3400`) has. */\nfunction significantDigits(decimal: string): number {\n const digits = decimal.replace(/^-/, \"\").replace(\".\", \"\").replace(/^0+/, \"\");\n return digits.replace(/0+$/, \"\").length;\n}\n\n/**\n * One value of the console's result, read by its column's type: an integer a\n * double holds exactly, a float, a numeric of at most 15 significant digits,\n * a boolean (`t`/`f`), json. Anything else — and any value that would change\n * on the way (a bigint past 2^53, a 20-digit numeric, `NaN`) — stays the\n * database's text. A value that is not text (a backend that returned typed\n * rows) or a column with no type is left as it came.\n */\nfunction typedValue(value: unknown, type: string | undefined): unknown {\n if (typeof value !== \"string\" || !type) return value;\n const base = type.replace(/\\(.*\\)$/, \"\").trim();\n if (INTEGER_TYPES.has(base)) {\n const number = Number(value);\n return /^-?\\d+$/.test(value) && Number.isSafeInteger(number) ? number : value;\n }\n if (FLOAT_TYPES.has(base)) {\n const number = Number(value);\n return value.trim() !== \"\" && Number.isFinite(number) ? number : value;\n }\n if (base === \"numeric\") {\n return /^-?\\d+(\\.\\d+)?$/.test(value) && significantDigits(value) <= 15 ? Number(value) : value;\n }\n if (base === \"boolean\") {\n return value === \"t\" ? true : value === \"f\" ? false : value;\n }\n if (base === \"json\" || base === \"jsonb\") {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n }\n return value;\n}\n\n/**\n * The console's rows for a typed JSON export: each value read by the type of\n * the column it is in (see `typedValue`), where \"Export JSON\" writes the\n * database's text as the console holds it. A row holds the last of two\n * columns that share a name, so that column's type is the one read.\n */\nexport function typedJsonRows(\n rows: Record<string, unknown>[],\n columns: readonly { name: string; type?: string }[]\n): Record<string, unknown>[] {\n const typeByName = new Map<string, string | undefined>();\n for (const column of columns) typeByName.set(column.name, column.type);\n return rows.map(row => Object.fromEntries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AAK,MAAM,KAAK;CAC3B,QAAQ;EACJ,OAAO;CACX;CAEJ,OAAO;AACX;;;;;;;AAQA,SAAgB,cACZ,MACA,SACyB;CACzB,MAAM,6BAAa,IAAI,IAAgC;CACvD,KAAK,MAAM,UAAU,SAAS,WAAW,IAAI,OAAO,MAAM,OAAO,IAAI;CACrE,OAAO,KAAK,KAAI,QAAO,OAAO,YAC1B,OAAO,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,WAAW,OAAO,WAAW,IAAI,GAAG,CAAC,CAAC,CAAC,CAC3F,CAAC;AACL"}
|
|
@@ -42,6 +42,20 @@ export declare function needsDestructiveConfirmation(sqlText: string): boolean;
|
|
|
42
42
|
export declare function quoteTableName(tableName: string, schemaName?: string): string;
|
|
43
43
|
/** An identifier as SQL, whatever it holds: double-quoted, with `"` doubled. */
|
|
44
44
|
export declare function quoteIdentifier(identifier: string): string;
|
|
45
|
+
/**
|
|
46
|
+
* The schema browser's statements for `table`, every name in them quoted. A
|
|
47
|
+
* name is folded to lower case unless it is quoted, so `Posts` reads a table
|
|
48
|
+
* `posts` that is not there and a column `createdAt` one called `createdat`;
|
|
49
|
+
* and a reserved word is not a name at all — `SELECT * FROM user` answers
|
|
50
|
+
* with the current role instead of reading the table. A table in `public` is
|
|
51
|
+
* named without its schema.
|
|
52
|
+
*/
|
|
53
|
+
export declare function tableStatementTemplates(schemaName: string, table: Pick<TableInfo, "tableName" | "columns">): {
|
|
54
|
+
selectTop: string;
|
|
55
|
+
selectAll: string;
|
|
56
|
+
insert: string;
|
|
57
|
+
update: string;
|
|
58
|
+
};
|
|
45
59
|
/** What the console knows about a result: its columns, and the tables they came from. */
|
|
46
60
|
export type ResultProvenance = Pick<SqlScriptResult, "columns" | "tables">;
|
|
47
61
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/studio",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.28.0",
|
|
4
4
|
"description": "Rebase Studio — the SQL editor, schema visualiser, RLS policy editor and API explorer.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"rebase",
|
|
@@ -35,19 +35,19 @@
|
|
|
35
35
|
"pgsql-ast-parser": "12.0.2",
|
|
36
36
|
"prism-react-renderer": "^2.4.1",
|
|
37
37
|
"react-dropzone": "^19.1.1",
|
|
38
|
-
"@rebasepro/cms-types": "0.
|
|
39
|
-
"@rebasepro/
|
|
40
|
-
"@rebasepro/
|
|
41
|
-
"@rebasepro/
|
|
42
|
-
"@rebasepro/
|
|
43
|
-
"@rebasepro/
|
|
44
|
-
"@rebasepro/
|
|
38
|
+
"@rebasepro/cms-types": "0.28.0",
|
|
39
|
+
"@rebasepro/client": "0.28.0",
|
|
40
|
+
"@rebasepro/types": "0.28.0",
|
|
41
|
+
"@rebasepro/common": "0.28.0",
|
|
42
|
+
"@rebasepro/app": "0.28.0",
|
|
43
|
+
"@rebasepro/utils": "0.28.0",
|
|
44
|
+
"@rebasepro/ui": "0.28.0"
|
|
45
45
|
},
|
|
46
46
|
"peerDependencies": {
|
|
47
47
|
"react": "^19.2.7",
|
|
48
48
|
"react-dom": "^19.2.7",
|
|
49
49
|
"react-router": "^8.3.0",
|
|
50
|
-
"@rebasepro/cms": "0.
|
|
50
|
+
"@rebasepro/cms": "0.28.0"
|
|
51
51
|
},
|
|
52
52
|
"peerDependenciesMeta": {
|
|
53
53
|
"@rebasepro/cms": {
|