Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
refactor: migrate API docs from protected to public route
fiber[bot]5e222b2bc09c
diff --git a/apps/erp/app/routes/docs+/api+/$lang.intro.tsx b/apps/erp/app/routes/docs+/api+/$lang.intro.tsxnew file mode 100644index 0000000000..b11081d728--- /dev/null+++ b/apps/erp/app/routes/docs+/api+/$lang.intro.tsx@@ -0,0 +1,103 @@+import { getBrowserEnv, SUPABASE_ANON_KEY } from "@carbon/auth";+import { getAuthSession } from "@carbon/auth/session.server";+import { Alert, AlertDescription, AlertTitle } from "@carbon/react";+import { LuTriangleAlert } from "react-icons/lu";+import type { LoaderFunctionArgs } from "react-router";+import { Link, useLoaderData } from "react-router";+import { useUser } from "~/hooks";+import { CodeSnippet, Snippets, useSelectedLang } from "~/modules/api";+import { path } from "~/utils/path";++const { SUPABASE_URL } = getBrowserEnv();++export async function loader({ request }: LoaderFunctionArgs) {+ const session = await getAuthSession(request);+ return {+ isLoggedIn: !!session+ };+}++export default function Route() {+ const { company } = useUser();+ const { isLoggedIn } = useLoaderData<typeof loader>();+ const selectedLang = useSelectedLang();++ return (+ <>+ <h2 className="doc-heading">Authentication</h2>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>Carbon uses API token authentication for the public API.</p>+ <p>+ First you'll need an <Link to={path.to.apiKeys}>API Key</Link>.+ </p>+ <p>Next save the API Key as an Environment Variable.</p>+ <article>+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.env({+ appUrl: window.location.origin,+ apiKey: "<your-api-key>",+ publicKey: SUPABASE_ANON_KEY,+ apiUrl: SUPABASE_URL,+ companyId: isLoggedIn+ ? (company?.id ?? "<your-company-id>")+ : "<your-company-id>"+ })}+ />+ </article>+ <p>+ The API Key is provided via the <code>carbon-key</code> header when+ making requests to the API.+ </p>+ </article>+ </div>+ {selectedLang == "js" ? (+ <>+ <h2 className="doc-heading">Client Library SDK</h2>+ <div className="doc-section">+ <article className="code-column text-foreground">+ <p>+ The easiest way to interact with the public API is via the+ JavaScript Client Library SDK.+ </p>+ <p>+ To initialize the Client Library SDK, you will need the+ environment variables you set up earlier.+ </p>+ <Alert variant="destructive">+ <LuTriangleAlert className="h-4 w-4 my-1" />+ <AlertTitle className="!my-0 font-bold text-base">+ You should never expose the <code>carbon-key</code> in the+ client+ </AlertTitle>+ <AlertDescription>+ Your API key gives full access to your database. Never expose+ it in a public-facing client.+ </AlertDescription>+ </Alert>++ <p>+ As with your API Key, we recommend setting your Client Key as an+ Environment Variable.+ </p>+ <p>Initialize the client as follows:</p>+ <div className="doc-section doc-section--client-libraries">+ <article className="code">+ <CodeSnippet+ selectedLang={selectedLang}+ snippet={Snippets.init(SUPABASE_URL)}+ />+ </article>+ </div>+ <p>+ You can now make requests to the API using the client. See the+ specific tables and views for more details.+ </p>+ </article>+ </div>+ </>+ ) : null}+ </>+ );+}diff --git a/apps/erp/app/routes/docs+/api+/$lang.rpc.$id.tsx b/apps/erp/app/routes/docs+/api+/$lang.rpc.$id.tsxnew file mode 100644index 0000000000..da90098c64--- /dev/null+++ b/apps/erp/app/routes/docs+/api+/$lang.rpc.$id.tsx@@ -0,0 +1,41 @@+import { useSwaggerDocs } from "~/hooks/useSwaggerDocs";+import { useSelectedLang } from "~/modules/api";+import { snakeToCamel } from "~/utils/string";++const functionPath = "rpc/";++export default function Route() {+ const swaggerDocsSchema = useSwaggerDocs();+ //+ // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration+ const { rpcs } = Object.entries(swaggerDocsSchema?.paths || {}).reduce(+ (a, [name]) => {+ const trimmedName = name.slice(1);+ const id = trimmedName.replace(functionPath, "");++ const displayName = id.replace(/_/g, " ");+ const camelCase = snakeToCamel(id);+ const enriched = { id, displayName, camelCase };++ if (!trimmedName.length) {+ return a;+ }++ return {+ rpcs: {+ ...a.rpcs,+ ...(trimmedName.includes(functionPath)+ ? {+ [id]: enriched+ }+ : {})+ }+ };+ },+ { rpcs: {} }+ );+ // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration+ const selectedLang = useSelectedLang();++ return null;+}diff --git a/apps/erp/app/routes/docs+/api+/$lang.table.$id.tsx b/apps/erp/app/routes/docs+/api+/$lang.table.$id.tsxnew file mode 100644index 0000000000..1f6b7ddd26--- /dev/null+++ b/apps/erp/app/routes/docs+/api+/$lang.table.$id.tsx@@ -0,0 +1,19 @@+import { getBrowserEnv } from "@carbon/auth";+import { useParams } from "react-router";+import { TableDocs, useSelectedLang } from "~/modules/api";++const { SUPABASE_URL } = getBrowserEnv();++export default function Route() {+ const selectedLang = useSelectedLang();+ const { id } = useParams();+ if (!id) throw new Error("Table id not found");++ return (+ <TableDocs+ endpoint={SUPABASE_URL}+ selectedLang={selectedLang}+ resourceId={id}+ />+ );+}diff --git a/apps/erp/app/routes/docs+/api+/_index.tsx b/apps/erp/app/routes/docs+/api+/_index.tsxnew file mode 100644index 0000000000..da13118823--- /dev/null+++ b/apps/erp/app/routes/docs+/api+/_index.tsx@@ -0,0 +1,6 @@+import { redirect } from "react-router";+import { path } from "~/utils/path";++export async function loader() {+ throw redirect(path.to.apiIntroduction);+}diff --git a/apps/erp/app/routes/docs+/api+/_layout.tsx b/apps/erp/app/routes/docs+/api+/_layout.tsxnew file mode 100644index 0000000000..f095cf1dab--- /dev/null+++ b/apps/erp/app/routes/docs+/api+/_layout.tsx@@ -0,0 +1,140 @@+import { Button, ClientOnly } from "@carbon/react";+import { LuEye, LuTable2 } from "react-icons/lu";+import type { MetaFunction } from "react-router";+import { Outlet, useLocation, useNavigate } from "react-router";+import { GroupedContentSidebar } from "~/components/Layout";+import { CollapsibleSidebarProvider } from "~/components/Layout/Navigation";+import { useSwaggerDocs } from "~/hooks/useSwaggerDocs";+import type { ValidLang } from "~/modules/api";+import { useSelectedLang } from "~/modules/api";+import DocsStyle from "~/styles/docs.css?url";+import type { RouteGroup } from "~/types";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | API Docs" }];+};++export const handle: Handle = {+ breadcrumb: "API Docs",+ to: path.to.apiIntroduction,+ module: "api"+};++export function links() {+ return [{ rel: "stylesheet", href: DocsStyle }];+}++export default function ApiDocsRoute() {+ const groups = useApiDocsMenu();+ const selectedLang = useSelectedLang();+ const navigate = useNavigate();+ const { pathname } = useLocation();++ const onChangeLanguage = (newLang: ValidLang) => {+ if (newLang === selectedLang) return;+ let newPath = "";+ switch (selectedLang) {+ case "bash":+ newPath = pathname.replace("/bash/", `/${newLang}/`);+ navigate(newPath);+ break;+ case "js":+ newPath = pathname.replace("/js/", `/${newLang}/`);+ navigate(newPath);+ break;+ default:+ throw new Error(`Invalid language: ${selectedLang}`);+ }+ };++ return (+ <CollapsibleSidebarProvider>+ <div className="relative grid grid-cols-[auto_1fr] w-full h-full">+ <div className="flex absolute top-4 right-4 z-50 gap-2">+ <Button+ variant={selectedLang === "js" ? "primary" : "secondary"}+ onClick={() => {+ onChangeLanguage("js");+ }}+ >+ JS+ </Button>+ <Button+ variant={selectedLang === "bash" ? "primary" : "secondary"}+ onClick={() => {+ onChangeLanguage("bash");+ }}+ >+ Bash+ </Button>+ </div>+ <GroupedContentSidebar groups={groups} width={270} exactMatch />+ <div className="Docs Docs--api-page w-full h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">+ <div className="Docs--inner-wrapper pt-4">+ <ClientOnly>{() => <Outlet />}</ClientOnly>+ </div>+ </div>+ </div>+ </CollapsibleSidebarProvider>+ );+}++const tableBlacklist = new Set([+ "apiKey",+ "challengeAttempt",+ "documentTransaction",+ "feedback",+ "groups_recursive",+ "invite",+ "lessonCompletion",+ "oauthClient",+ "oauthCode",+ "oauthToken",+ "purchaseOrderTransaction",+ "salesOrderTransaction",+ "search"+]);++function useApiDocsMenu(): RouteGroup[] {+ const swaggerDocsSchema = useSwaggerDocs();+ const selectedLang = useSelectedLang();+ const result: RouteGroup[] = [+ {+ name: "Getting Started",+ routes: [+ {+ name: "Introduction",+ to: path.to.apiIntro(selectedLang)+ }+ ]+ }+ ];++ const tables = Object.keys(swaggerDocsSchema?.definitions ?? {}).sort();+ const isTable = (table: string): boolean => {+ if (!swaggerDocsSchema?.paths) return false;+ const tableKey = `/${table}`;+ return Object.keys(swaggerDocsSchema.paths[tableKey] ?? {}).some(+ (x) => x.toUpperCase() === "POST"+ );+ };++ result.push({+ name: "Tables and Views",+ routes: tables+ .filter((table) => !tableBlacklist.has(table))+ .map((table) => ({+ name: table,+ to: path.to.apiTable(selectedLang, table),+ icon: isTable(table) ? (+ <LuTable2 className="flex-shrink-0" />+ ) : (+ <LuEye className="flex-shrink-0" />+ )+ }))+ });++ return result;+}diff --git a/apps/erp/app/routes/x+/api+/_layout.tsx b/apps/erp/app/routes/x+/api+/_layout.tsxindex f095cf1dab..cb55a1024d 100644--- a/apps/erp/app/routes/x+/api+/_layout.tsx+++ b/apps/erp/app/routes/x+/api+/_layout.tsx@@ -1,140 +1,6 @@-import { Button, ClientOnly } from "@carbon/react";-import { LuEye, LuTable2 } from "react-icons/lu";-import type { MetaFunction } from "react-router";-import { Outlet, useLocation, useNavigate } from "react-router";-import { GroupedContentSidebar } from "~/components/Layout";-import { CollapsibleSidebarProvider } from "~/components/Layout/Navigation";-import { useSwaggerDocs } from "~/hooks/useSwaggerDocs";-import type { ValidLang } from "~/modules/api";-import { useSelectedLang } from "~/modules/api";-import DocsStyle from "~/styles/docs.css?url";-import type { RouteGroup } from "~/types";-import type { Handle } from "~/utils/handle";-import { path } from "~/utils/path";+import { redirect } from "react-router";-export const meta: MetaFunction = () => {- return [{ title: "Carbon | API Docs" }];-};--export const handle: Handle = {- breadcrumb: "API Docs",- to: path.to.apiIntroduction,- module: "api"-};--export function links() {- return [{ rel: "stylesheet", href: DocsStyle }];-}--export default function ApiDocsRoute() {- const groups = useApiDocsMenu();- const selectedLang = useSelectedLang();- const navigate = useNavigate();- const { pathname } = useLocation();-- const onChangeLanguage = (newLang: ValidLang) => {- if (newLang === selectedLang) return;- let newPath = "";- switch (selectedLang) {- case "bash":- newPath = pathname.replace("/bash/", `/${newLang}/`);- navigate(newPath);- break;- case "js":- newPath = pathname.replace("/js/", `/${newLang}/`);- navigate(newPath);- break;- default:- throw new Error(`Invalid language: ${selectedLang}`);- }- };-- return (- <CollapsibleSidebarProvider>- <div className="relative grid grid-cols-[auto_1fr] w-full h-full">- <div className="flex absolute top-4 right-4 z-50 gap-2">- <Button- variant={selectedLang === "js" ? "primary" : "secondary"}- onClick={() => {- onChangeLanguage("js");- }}- >- JS- </Button>- <Button- variant={selectedLang === "bash" ? "primary" : "secondary"}- onClick={() => {- onChangeLanguage("bash");- }}- >- Bash- </Button>- </div>- <GroupedContentSidebar groups={groups} width={270} exactMatch />- <div className="Docs Docs--api-page w-full h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">- <div className="Docs--inner-wrapper pt-4">- <ClientOnly>{() => <Outlet />}</ClientOnly>- </div>- </div>- </div>- </CollapsibleSidebarProvider>- );-}--const tableBlacklist = new Set([- "apiKey",- "challengeAttempt",- "documentTransaction",- "feedback",- "groups_recursive",- "invite",- "lessonCompletion",- "oauthClient",- "oauthCode",- "oauthToken",- "purchaseOrderTransaction",- "salesOrderTransaction",- "search"-]);--function useApiDocsMenu(): RouteGroup[] {- const swaggerDocsSchema = useSwaggerDocs();- const selectedLang = useSelectedLang();- const result: RouteGroup[] = [- {- name: "Getting Started",- routes: [- {- name: "Introduction",- to: path.to.apiIntro(selectedLang)- }- ]- }- ];-- const tables = Object.keys(swaggerDocsSchema?.definitions ?? {}).sort();- const isTable = (table: string): boolean => {- if (!swaggerDocsSchema?.paths) return false;- const tableKey = `/${table}`;- return Object.keys(swaggerDocsSchema.paths[tableKey] ?? {}).some(- (x) => x.toUpperCase() === "POST"- );- };-- result.push({- name: "Tables and Views",- routes: tables- .filter((table) => !tableBlacklist.has(table))- .map((table) => ({- name: table,- to: path.to.apiTable(selectedLang, table),- icon: isTable(table) ? (- <LuTable2 className="flex-shrink-0" />- ) : (- <LuEye className="flex-shrink-0" />- )- }))- });-- return result;+export async function loader() {+ // Redirect from the old protected x+ route to the new public docs+ route+ throw redirect("/docs/api/js/intro");}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 30742e9cc2..e0332a6a2c 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -86,7 +86,9 @@ export const path = {materialForms: `${api}/items/forms`,materials: (materialFormId?: string) =>generatePath(- `${api}/items/materials${materialFormId ? `?materialFormId=${materialFormId}` : ""}`+ `${api}/items/materials${+ materialFormId ? `?materialFormId=${materialFormId}` : ""+ }`),materialGrades: (substanceId: string) =>generatePath(`${api}/items/grades/${substanceId}`),@@ -399,10 +401,10 @@ export const path = {generatePath(`${x}/quality/gauges/activate/${id}`),attribute: (id: string) => generatePath(`${x}/people/attribute/${id}`),attributes: `${x}/people/attributes`,- apiIntroduction: `${x}/api/js/intro`,- apiIntro: (lang: string) => generatePath(`${x}/api/${lang}/intro/`),+ apiIntroduction: `/docs/api/js/intro`,+ apiIntro: (lang: string) => generatePath(`/docs/api/${lang}/intro/`),apiTable: (lang: string, table: string) =>- generatePath(`${x}/api/${lang}/table/${table}`),+ generatePath(`/docs/api/${lang}/table/${table}`),apiKey: (id: string) => generatePath(`${x}/settings/api-keys/${id}`),apiKeys: `${x}/settings/api-keys`,attributeCategory: (id: string) =>