Skip to content

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.

feat: forge viewer lib

Brad Barbin52c636d64ddf
diff --git a/apps/carbon/app/config/env.ts b/apps/carbon/app/config/env.ts
index 31aa3f45d0..652e026648 100644
--- a/apps/carbon/app/config/env.ts
+++ b/apps/carbon/app/config/env.ts
@@ -14,12 +14,15 @@ declare global {
declare global {
namespace NodeJS {
interface ProcessEnv {
+ AUTODESK_BUCKET_NAME: string;
+ AUTODESK_CLIENT_ID: string;
+ AUTODESK_CLIENT_SECRET: string;
POSTHOG_API_HOST: string;
POSTHOG_PROJECT_PUBLIC_KEY: string;
- SUPABASE_ANON_PUBLIC: string;
SESSION_SECRET: string;
SESSION_KEY: string;
SESSION_ERROR_KEY: string;
+ SUPABASE_ANON_PUBLIC: string;
SUPABASE_URL: string;
SUPABASE_SERVICE_ROLE: string;
VERCEL_URL: string;
@@ -52,6 +55,9 @@ function getEnv(
/**
* Server env
*/
+export const AUTODESK_BUCKET_NAME = getEnv("AUTODESK_BUCKET_NAME");
+export const AUTODESK_CLIENT_ID = getEnv("AUTODESK_CLIENT_ID");
+export const AUTODESK_CLIENT_SECRET = getEnv("AUTODESK_CLIENT_SECRET");
export const SUPABASE_SERVICE_ROLE = getEnv("SUPABASE_SERVICE_ROLE");
export const SESSION_SECRET = getEnv("SESSION_SECRET");
export const SESSION_KEY = "auth";
diff --git a/apps/carbon/app/lib/autodesk/autodesk.server.ts b/apps/carbon/app/lib/autodesk/autodesk.server.ts
new file mode 100644
index 0000000000..2eea662666
--- /dev/null
+++ b/apps/carbon/app/lib/autodesk/autodesk.server.ts
@@ -0,0 +1,317 @@
+import { redis } from "@carbon/redis";
+import axios from "axios";
+
+import { z } from "zod";
+import {
+ AUTODESK_BUCKET_NAME,
+ AUTODESK_CLIENT_ID,
+ AUTODESK_CLIENT_SECRET,
+} from "~/config/env";
+import type { AutodeskTokenResponse } from "./types";
+
+const SIGNED_URL_EXPIRATION = 15;
+
+const endpoints = {
+ finalizeAutodeskUpload: {
+ url: (bucketName: string, filename: string) =>
+ `https://developer.api.autodesk.com/oss/v2/buckets/${bucketName}/objects/${filename}/signeds3upload?minutesExpiration=${SIGNED_URL_EXPIRATION}`,
+ method: "POST",
+ },
+ getSignedUrl: {
+ url: (bucketName: string, filename: string) =>
+ `https://developer.api.autodesk.com/oss/v2/buckets/${bucketName}/objects/${filename}/signeds3upload?minutesExpiration=${SIGNED_URL_EXPIRATION}`,
+ method: "GET",
+ },
+ getToken: {
+ url: "https://developer.api.autodesk.com/authentication/v2/token",
+ method: "POST",
+ },
+ getTranslationStatus: {
+ url: (urn: string) =>
+ `https://developer.api.autodesk.com/modelderivative/v2/designdata/${urn}/manifest`,
+ method: "GET",
+ },
+ translateFile: {
+ url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
+ method: "POST",
+ },
+};
+
+export async function finalizeAutodeskUpload(
+ encodedFilename: string,
+ token: string,
+ uploadKey: string
+): Promise<{ urn: string }> {
+ const url = endpoints.finalizeAutodeskUpload.url(
+ AUTODESK_BUCKET_NAME,
+ encodedFilename
+ );
+ const body = {
+ ossbucketKey: AUTODESK_BUCKET_NAME,
+ ossSourceFileObjectKey: encodedFilename,
+ access: "full",
+ uploadKey,
+ };
+
+ let response;
+
+ try {
+ response = await axios(url, {
+ method: endpoints.finalizeAutodeskUpload.method,
+ data: body,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+ } catch (err) {
+ const message = (err as Error).message || "Something went wrong";
+ console.error(message, err);
+ }
+
+ const data = response?.data;
+
+ return {
+ urn: data?.objectId,
+ };
+}
+
+export type AutodeskSignedUrl = {
+ uploadKey: string;
+ url: string;
+};
+
+export const signedUrlSchema = z.object({
+ uploadKey: z.string(),
+ urls: z.array(z.string()),
+});
+
+export async function getAutodeskSignedUrl(
+ encodedFilename: string,
+ token: string
+) {
+ let result: AutodeskSignedUrl | null = null;
+ let cacheKey = `autodesk:${AUTODESK_BUCKET_NAME}:${encodedFilename}`;
+
+ try {
+ result = JSON.parse((await redis.get(cacheKey)) || "null");
+ } finally {
+ if (result)
+ return {
+ data: result,
+ error: null,
+ };
+ }
+
+ const uploadUrl = endpoints.getSignedUrl.url(
+ AUTODESK_BUCKET_NAME,
+ encodedFilename
+ );
+
+ let response;
+
+ try {
+ response = await fetch(uploadUrl, {
+ method: endpoints.getSignedUrl.method,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+ } catch (err) {
+ const message = (err as Error).message || "Something went wrong";
+ console.error(message, err);
+ return {
+ data: null,
+ error: {
+ message,
+ },
+ };
+ }
+
+ const reponseJson = await response?.json();
+ const parsed = signedUrlSchema.safeParse(reponseJson);
+
+ if (parsed.success === false) {
+ return {
+ data: null,
+ error: {
+ message: `Invalid response format: ${JSON.stringify(parsed.error)}`,
+ },
+ };
+ }
+
+ result = {
+ uploadKey: parsed.data.uploadKey,
+ url: parsed.data.urls?.[0] ?? "",
+ };
+
+ redis.set(cacheKey, JSON.stringify(result));
+ redis.expire(cacheKey, SIGNED_URL_EXPIRATION - 1);
+
+ return {
+ data: result,
+ error: null,
+ };
+}
+
+export async function getAutodeskToken(refresh = false, scope?: string) {
+ if (!refresh) {
+ try {
+ const [token, ttl] = await Promise.all([
+ redis.get("autodesk_token"),
+ redis.ttl("autodesk_token"),
+ ]);
+ if (token && ttl > 60) {
+ return {
+ data: {
+ token: token as string,
+ expiresAt: Date.now() + ttl * 1000,
+ },
+ error: null,
+ };
+ }
+ } catch {}
+ }
+
+ const url = endpoints.getToken.url;
+ const basic = `Basic ${Buffer.from(
+ `${AUTODESK_CLIENT_ID}:${AUTODESK_CLIENT_SECRET}`
+ ).toString("base64")}`;
+
+ const postBody = {
+ grant_type: "client_credentials",
+ scope: scope || "data:write data:read bucket:create bucket:delete",
+ };
+ let response;
+
+ try {
+ response = await fetch(url, {
+ method: endpoints.getToken.method,
+ cache: "no-store",
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded",
+ Accept: "application/json",
+ Authorization: basic,
+ },
+ body: new URLSearchParams(postBody),
+ });
+ const result = (await response.json()) as AutodeskTokenResponse;
+ if (result?.access_token) {
+ redis.set("autodesk_token", result.access_token);
+ redis.expire("autodesk_token", result.expires_in - 60);
+
+ return {
+ data: {
+ token: result.access_token,
+ expiresAt: Date.now() + (result.expires_in - 60) * 1000,
+ },
+ error: null,
+ };
+ } else {
+ return {
+ data: null,
+ error: {
+ message: "Failed to get token",
+ },
+ };
+ }
+ } catch (err) {
+ const message = (err as Error).message || "Something went wrong";
+ console.error(message, err);
+ return {
+ data: null,
+ error: {
+ message,
+ },
+ };
+ }
+}
+
+export async function getTranslationStatus(urn: string, token: string) {
+ const url = endpoints.getTranslationStatus.url(urn);
+
+ let response;
+ try {
+ response = await fetch(url, {
+ method: endpoints.getTranslationStatus.method,
+ cache: "no-store",
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+
+ const data = await response.json();
+
+ return data.status;
+ } catch (err) {
+ const message = (err as Error).message || "Something went wrong.";
+
+ console.error(`[getTranslationStatus]`, message, err);
+ }
+}
+
+export async function translateFile(urn: string, token: string) {
+ const url = endpoints.translateFile.url;
+
+ const body = {
+ input: {
+ urn: urn,
+ },
+ output: {
+ destination: {
+ region: "us",
+ },
+ formats: [
+ {
+ type: "svf2",
+ views: ["3d"],
+ },
+ {
+ type: "thumbnail",
+ },
+ ],
+ },
+ };
+
+ let response;
+ try {
+ response = await axios(url, {
+ method: endpoints.translateFile.method,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ data: body,
+ });
+
+ const data = response.data;
+ console.log(data);
+ //
+ } catch (err) {
+ const message = (err as Error).message || "Something went wrong";
+ console.error(message, err);
+ }
+
+ const data = response?.data;
+ return { urn: data?.urn, token };
+}
+
+export async function uploadToAutodesk(url: string, file: File, token: string) {
+ let response;
+
+ try {
+ response = await axios(url, {
+ method: "PUT",
+ data: await file.arrayBuffer(),
+ headers: {
+ Authorization: `Bearer ${token}`,
+ "Content-Type": "application/octet-stream",
+ },
+ });
+ } catch (err) {
+ const message = (err as Error).message || "Something went wrong";
+
+ console.error(message, err);
+ }
+
+ const data = response?.data;
+ return data;
+}
diff --git a/apps/carbon/app/lib/autodesk/autodesk.ts b/apps/carbon/app/lib/autodesk/autodesk.ts
new file mode 100644
index 0000000000..82fb8a2d36
--- /dev/null
+++ b/apps/carbon/app/lib/autodesk/autodesk.ts
@@ -0,0 +1,191 @@
+import axios from "axios";
+import { path } from "~/utils/path";
+import type { AutodeskToken } from "./types";
+
+export enum AutodeskKeysEnum {
+ AUTODESK_TOKEN = "autodesk-token",
+ AUTODESK_TOKEN_RENEW = "autodesk-token-renew",
+}
+
+// when expiry time of token is less than 3 minutes.
+const RENEW_TOKEN_TIME = 180 * 1000;
+const TOKEN_CHECKER_INTERVAL = 15 * 1000; // every 15 sec
+
+let tokenCheckerTimerId: ReturnType<typeof setInterval> | null = null;
+
+const autodesk = {
+ _isRenewing: false,
+
+ clear() {
+ this._stopTokenChecker();
+ this.unsubscribe(receiveMessage);
+ window.localStorage.removeItem(AutodeskKeysEnum.AUTODESK_TOKEN);
+ window.localStorage.removeItem(AutodeskKeysEnum.AUTODESK_TOKEN_RENEW);
+ },
+
+ // ensureToken verifies that token is valid and starts
+ // periodically checking and refreshing the token.
+ ensureToken() {
+ this._stopTokenChecker();
+ this._ensureLocalStorageSubscription();
+
+ if (this._shouldRenewToken()) {
+ this._renewToken()
+ .then(() => {
+ this._startTokenChecker();
+ })
+ .catch(this.renewToken.bind(this));
+ } else {
+ this._startTokenChecker();
+ }
+ },
+
+ renewToken(): Promise<number> {
+ return this._renewToken().then((token) => token.expiresAt);
+ },
+
+ isValid(): boolean {
+ return this._timeLeft() > 0;
+ },
+
+ getInactivityTimeout(): number {
+ const autodeskToken = this._getAutodeskToken();
+ if (autodeskToken === null) return 0;
+ const time = Number(autodeskToken.expiresAt);
+ return time ? time : 0;
+ },
+
+ _getAutodeskToken() {
+ let token = null;
+ try {
+ token = this.getAutodeskToken();
+ } catch (err) {
+ console.error("Cannot find bearer token", err);
+ }
+
+ return token;
+ },
+
+ _shouldRenewToken(): boolean {
+ if (this._getIsRenewing()) {
+ return false;
+ }
+
+ console.log(
+ "timeLeft()",
+ this._timeLeft() < RENEW_TOKEN_TIME,
+ this._timeLeft()
+ );
+
+ return this._timeLeft() < RENEW_TOKEN_TIME;
+ },
+
+ _renewToken() {
+ this._setAndBroadcastIsRenewing(true);
+ return axios.get(path.to.api.autodeskToken).then((response) => {
+ const token = response.data;
+ this.setAutodeskToken(token);
+ this._setAndBroadcastIsRenewing(false);
+ return token;
+ });
+ },
+
+ _setAndBroadcastIsRenewing(value: boolean) {
+ this._setIsRenewing(value);
+ this.broadcast(AutodeskKeysEnum.AUTODESK_TOKEN_RENEW, `${value}`);
+ },
+
+ _setIsRenewing(value: boolean) {
+ this._isRenewing = value;
+ },
+
+ _getIsRenewing() {
+ return !!this._isRenewing;
+ },
+
+ _timeLeft() {
+ const token = this._getAutodeskToken();
+ if (!token) {
+ return 0;
+ }
+
+ let { expiresAt } = token;
+ if (!expiresAt) {
+ return 0;
+ }
+
+ return expiresAt - Date.now();
+ },
+
+ _shouldCheckStatus() {
+ if (this._getIsRenewing()) {
+ return false;
+ }
+
+ /*
+ * double the threshold value for slow connections to avoid
+ * access-denied response due to concurrent renew token request
+ * made from other tab
+ */
+ return this._timeLeft() > TOKEN_CHECKER_INTERVAL * 2;
+ },
+
+ // subsribes to localStorage changes (triggered from other browser tabs)
+ _ensureLocalStorageSubscription() {
+ this.subscribe(receiveMessage);
+ },
+
+ _startTokenChecker() {
+ this._stopTokenChecker();
+
+ tokenCheckerTimerId = setInterval(() => {
+ // calling ensureToken() will again invoke _startTokenChecker
+ this.ensureToken();
+ }, TOKEN_CHECKER_INTERVAL);
+ },
+
+ _stopTokenChecker() {
+ clearInterval(tokenCheckerTimerId ?? undefined);
+ tokenCheckerTimerId = null;
+ },
+
+ subscribe(fn: (event: StorageEvent) => void) {
+ window.addEventListener("storage", fn);
+ },
+
+ unsubscribe(fn: (event: StorageEvent) => void) {
+ window.removeEventListener("storage", fn);
+ },
+
+ setAutodeskToken(token: AutodeskToken) {
+ window.localStorage.setItem(
+ AutodeskKeysEnum.AUTODESK_TOKEN,
+ JSON.stringify(token)
+ );
+ },
+
+ getAutodeskToken(): AutodeskToken | null {
+ const item = window.localStorage.getItem(AutodeskKeysEnum.AUTODESK_TOKEN);
+ if (item) {
+ return JSON.parse(item);
+ }
+
+ return null;
+ },
+
+ broadcast(messageType: string, messageBody: string) {
+ window.localStorage.setItem(messageType, messageBody);
+ window.localStorage.removeItem(messageType);
+ },
+};
+
+function receiveMessage(event: StorageEvent) {
+ const { key, newValue } = event;
+
+ // check if token is being renewed from another tab
+ if (key === AutodeskKeysEnum.AUTODESK_TOKEN_RENEW && !!newValue) {
+ autodesk._setIsRenewing(JSON.parse(newValue));
+ }
+}
+
+export default autodesk;
diff --git a/apps/carbon/app/lib/autodesk/index.ts b/apps/carbon/app/lib/autodesk/index.ts
new file mode 100644
index 0000000000..3ebffbcb7b
--- /dev/null
+++ b/apps/carbon/app/lib/autodesk/index.ts
@@ -0,0 +1,3 @@
+import { AutodeskProvider, useAutodeskToken } from "./provider";
+
+export { AutodeskProvider, useAutodeskToken };
diff --git a/apps/carbon/app/lib/autodesk/provider.tsx b/apps/carbon/app/lib/autodesk/provider.tsx
new file mode 100644
index 0000000000..4be91317af
--- /dev/null
+++ b/apps/carbon/app/lib/autodesk/provider.tsx
@@ -0,0 +1,64 @@
+import { useMount } from "@carbon/react";
+import { isBrowser } from "@carbon/utils";
+import type { PropsWithChildren } from "react";
+import { createContext, useCallback, useContext, useState } from "react";
+import service, { AutodeskKeysEnum } from "./autodesk";
+import type { AutodeskToken } from "./types";
+
+const AutodeskContext = createContext<{ autodeskToken: string | null }>({
+ autodeskToken: null,
+});
+
+export const AutodeskProvider = ({
+ children,
+ token,
+}: PropsWithChildren<{
+ token: AutodeskToken | null;
+}>) => {
+ const [autodeskToken, setAutodeskToken] = useState<string | null>(
+ token?.token ?? null
+ );
+
+ const updateToken = useCallback((event: StorageEvent) => {
+ const { key, newValue } = event;
+ if (key === AutodeskKeysEnum.AUTODESK_TOKEN) {
+ const newToken = JSON.parse(newValue ?? "null");
+ if ("token" in newToken) {
+ setAutodeskToken(newToken.token);
+ } else {
+ setAutodeskToken(null);
+ }
+ }
+ }, []);
+
+ useMount(() => {
+ if (token)
+ service.setAutodeskToken({
+ token: token.token,
+ expiresAt: token.expiresAt,
+ });
+
+ service.ensureToken();
+ service.subscribe(updateToken);
+
+ return () => {
+ service.unsubscribe(updateToken);
+ };
+ });
+
+ return (
+ <AutodeskContext.Provider value={{ autodeskToken }}>
+ {children}
+ </AutodeskContext.Provider>
+ );
+};
+
+export const useAutodeskToken = () => {
+ const context = useContext(AutodeskContext);
+
+ if (!isBrowser && context === undefined) {
+ throw new Error("useAutodeskToken must be used within an AutodeskProvder.");
+ }
+
+ return context;
+};
diff --git a/apps/carbon/app/lib/autodesk/types.ts b/apps/carbon/app/lib/autodesk/types.ts
new file mode 100644
index 0000000000..5e9f266484
--- /dev/null
+++ b/apps/carbon/app/lib/autodesk/types.ts
@@ -0,0 +1,9 @@
+export type AutodeskToken = {
+ token: string;
+ expiresAt: number;
+};
+
+export type AutodeskTokenResponse = {
+ access_token?: string;
+ expires_in: number;
+};
diff --git a/apps/carbon/app/lib/supabase/provider.tsx b/apps/carbon/app/lib/supabase/provider.tsx
index 822bf24f1b..290d0df347 100644
--- a/apps/carbon/app/lib/supabase/provider.tsx
+++ b/apps/carbon/app/lib/supabase/provider.tsx
@@ -3,7 +3,7 @@ import { useInterval } from "@carbon/react";
import { isBrowser } from "@carbon/utils";
import { useFetcher } from "@remix-run/react";
import type { SupabaseClient } from "@supabase/supabase-js";
-import type { ReactElement } from "react";
+import type { PropsWithChildren } from "react";
import {
createContext,
useContext,
@@ -16,105 +16,18 @@ import {
import type { AuthSession } from "~/services/auth";
import { path } from "~/utils/path";
import { getSupabase } from "./client";
-/**
- * This is how to use Supabase in the browser
- *
- * In root.tsx
- * 1 : Return the user auth session and browser env (SUPABASE_URL and SUPABASE_ANON_PUBLIC)
- *
- * import { SUPABASE_ANON_PUBLIC, SUPABASE_API_URL } from "./config/env";
- *
- * export async function loader({ request }: LoaderFunctionArgs) {
- * const { accessToken, expiresAt, expiresIn } = (await getAuthSession(request)) || {};
- *
- * return json({
- * env: {
- * SUPABASE_ANON_PUBLIC,
- * SUPABASE_URL,
- * },
- * session: {
- * accessToken,
- * expiresAt,
- * expiresIn,
- * },
- * });
- * }
- *
- *
- * 2 : Inject env in <script> tag.
- * Wrap <Outlet /> with <SupabaseProvider><Outlet /></SupabaseProvider>
- * authSession is used elsewhere with a special Remix hook ;)
- *
- * export default function App() {
- * const { env } = useLoaderData<typeof loader>();
- *
- * return (
- * <html lang="en" className="h-screen bg-neutral-50 text-zinc-900">
- * <head>
- * <Meta />
- * <Links />
- * </head>
- * <body className="h-full">
- * <SupabaseProvider>
- * <Outlet />
- * </SupabaseProvider>
- * <ConditionalScrollRestoration />
- * <script
- * dangerouslySetInnerHTML={{
- * __html: `window.env = ${JSON.stringify(env)}`,
- * }}
- * />
- * <Scripts />
- * <LiveReload />
- * </body>
- * </html>
- * );
- * }
- *
- *
- * 3 : In the component you want to use supabase, use the hook useSupabase()
- *
- * export default function SubscribeToRealtime() {
- * const [data, setData] = useState([])
- * const { supabase, accessToken } = useSupabase()
- *
- * useEffect(() => {
- * if (!supabase || !accessToken) return;
- *
- * const channel = supabase
- * .channel('test')
- * .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'test' }, (payload) => {
- * // do something with the payload. You can even trigger Remix to reload data :)
- * // fetcher.submit(null, { method: "post" }); to trigger a route action that will reload all loaders
- * setData((data) => [...data, payload.new])
- * })
- * .subscribe()
- *
- * channel.socket.setAuth(accessToken);
- *
- * return () => {
- * supabase.removeChannel(channel)
- * }
- * }, [session])
- *
- * return <pre>{JSON.stringify({ data }, null, 2)}</pre>
- * }
- */
const SupabaseContext = createContext<{
supabase: SupabaseClient<Database> | undefined;
accessToken: string | undefined;
}>({ supabase: undefined, accessToken: undefined });
-// in root.tsx, wrap <Outlet /> with <SupabaseProvider authSession={authSession}> to use supabase'browser client
export const SupabaseProvider = ({
children,
session,
-}: {
- children: ReactElement;
+}: PropsWithChildren<{
session: Partial<AuthSession>;
-}) => {
- // what root loader data returns
+}>) => {
const { accessToken, refreshToken, expiresIn, expiresAt } = session;
const [browserSessionExpiresAt, setBrowserSessionExpiresAt] = useState<
number | undefined
@@ -129,10 +42,7 @@ export const SupabaseProvider = ({
);
const refresh = useFetcher();
- // trigger a refresh session at expire time. We'll send a post request to our resource route /refresh-session
useInterval(() => {
- // ask to refresh only if expiresIn is defined
- // prevents trying to refresh when user is not logged in
if (!initialLoad.current && expiresIn) {
refresh.submit(null, {
method: "post",
@@ -143,8 +53,6 @@ export const SupabaseProvider = ({
initialLoad.current = false;
}, expiresIn);
- // when in browser
- // after root loader fetch, if user session is refresh, it's time to create a new supabase client
if (isBrowser && expiresAt !== browserSessionExpiresAt && accessToken) {
// recreate a supabase client to force provider's consumer to rerender
setSupabaseClient(getSupabase(accessToken));
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index b832a3028e..018360d7a1 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -553,10 +553,10 @@ export async function getMethodTreeArray(
function getMethodTreeArrayToTree(items: Method[]): MethodTreeItem[] {
function traverseAndRenameIds(node: MethodTreeItem) {
- const newNode = JSON.parse(JSON.stringify(node));
- newNode.id = `node-${Math.random().toString(16).slice(2)}`;
- newNode.children = node.children.map((n) => traverseAndRenameIds(n));
- return newNode;
+ const clone = structuredClone(node);
+ clone.id = `node-${Math.random().toString(16).slice(2)}`;
+ clone.children = node.children.map((n) => traverseAndRenameIds(n));
+ return clone;
}
const rootItems: MethodTreeItem[] = [];
diff --git a/apps/carbon/app/routes/api+/autodesk.token.ts b/apps/carbon/app/routes/api+/autodesk.token.ts
new file mode 100644
index 0000000000..ece48c3e6d
--- /dev/null
+++ b/apps/carbon/app/routes/api+/autodesk.token.ts
@@ -0,0 +1,13 @@
+import { json, type LoaderFunctionArgs } from "@remix-run/node";
+import { getAutodeskToken } from "~/lib/autodesk/autodesk.server";
+import { requirePermissions } from "~/services/auth/auth.server";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {});
+ const autodesk = await getAutodeskToken();
+
+ return json({
+ token: autodesk.data?.token ?? null,
+ expiresAt: autodesk.data?.expiresAt ?? Date.now(),
+ });
+}
diff --git a/apps/carbon/app/routes/x+/_layout.tsx b/apps/carbon/app/routes/x+/_layout.tsx
index 5352c959b4..492538d330 100644
--- a/apps/carbon/app/routes/x+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/_layout.tsx
@@ -5,6 +5,7 @@ import { Outlet, useLoaderData, useNavigation } from "@remix-run/react";
import NProgress from "nprogress";
import { useEffect } from "react";
import { IconSidebar, Topbar } from "~/components/Layout";
+import { AutodeskProvider } from "~/lib/autodesk";
import { SupabaseProvider, getSupabase } from "~/lib/supabase";
import { getCompanies, getCompanyIntegrations } from "~/modules/settings";
import { RealtimeDataProvider } from "~/modules/shared";
@@ -22,6 +23,7 @@ import {
import { path } from "~/utils/path";
import type { ShouldRevalidateFunction } from "@remix-run/react";
+import { getAutodeskToken } from "~/lib/autodesk/autodesk.server";
export const shouldRevalidate: ShouldRevalidateFunction = ({
currentUrl,
@@ -53,6 +55,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
claims,
groups,
defaults,
+ autodesk,
] = await Promise.all([
getCompanies(client, userId),
getCustomFieldsSchemas(client, { companyId }),
@@ -61,6 +64,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
getUserClaims(userId, companyId),
getUserGroups(client, userId),
getUserDefaults(client, userId, companyId),
+ getAutodeskToken(),
]);
if (!claims || user.error || !user.data || !groups.data) {
@@ -80,6 +84,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
expiresIn,
expiresAt,
},
+ autodesk: autodesk.data,
company,
companies: companies.data ?? [],
customFields: customFields.data ?? [],
@@ -93,7 +98,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function AuthenticatedRoute() {
- const { session } = useLoaderData<typeof loader>();
+ const { autodesk, session } = useLoaderData<typeof loader>();
const transition = useNavigation();
@@ -112,27 +117,29 @@ export default function AuthenticatedRoute() {
return (
<SupabaseProvider session={session}>
<RealtimeDataProvider>
- <TooltipProvider>
- <div className="min-h-full flex flex-col">
- <div className="flex-none" />
- <div className="h-screen min-h-[0px] basis-0 flex-1">
- <div className="flex h-full">
- <IconSidebar />
- <div className="flex w-full h-full">
- <div className="w-full h-full flex-1 overflow-hidden">
- <main className="h-full flex flex-col flex-1 max-w-[100vw] sm:max-w-[calc(100vw-56px)] overflow-x-hidden bg-muted">
- <Topbar />
- <main className="flex-1 overflow-y-auto max-h-[calc(100vh-49px)]">
- <Outlet />
+ <AutodeskProvider token={autodesk}>
+ <TooltipProvider>
+ <div className="min-h-full flex flex-col">
+ <div className="flex-none" />
+ <div className="h-screen min-h-[0px] basis-0 flex-1">
+ <div className="flex h-full">
+ <IconSidebar />
+ <div className="flex w-full h-full">
+ <div className="w-full h-full flex-1 overflow-hidden">
+ <main className="h-full flex flex-col flex-1 max-w-[100vw] sm:max-w-[calc(100vw-56px)] overflow-x-hidden bg-muted">
+ <Topbar />
+ <main className="flex-1 overflow-y-auto max-h-[calc(100vh-49px)]">
+ <Outlet />
+ </main>
</main>
- </main>
+ </div>
</div>
</div>
</div>
</div>
- </div>
- <Toaster position="bottom-right" />
- </TooltipProvider>
+ <Toaster position="bottom-right" />
+ </TooltipProvider>
+ </AutodeskProvider>
</RealtimeDataProvider>
</SupabaseProvider>
);
diff --git a/apps/carbon/app/routes/x+/part+/$itemId.details.tsx b/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
index c428552932..832cb5f20c 100644
--- a/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
+++ b/apps/carbon/app/routes/x+/part+/$itemId.details.tsx
@@ -4,6 +4,7 @@ import type { ActionFunctionArgs } from "@remix-run/node";
import { redirect } from "@remix-run/node";
import { useParams } from "@remix-run/react";
import { useRouteData } from "~/hooks";
+import { useAutodeskToken } from "~/lib/autodesk";
import type { PartSummary } from "~/modules/items";
import { PartForm, partValidator, upsertPart } from "~/modules/items";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -69,9 +70,12 @@ export default function PartDetailsRoute() {
...getCustomFields(partData.partSummary?.customFields ?? {}),
};
+ const { autodeskToken } = useAutodeskToken();
+
return (
<VStack spacing={2} className="p-2">
<PartForm key={partInitialValues.id} initialValues={partInitialValues} />
+ <pre className="p-2">{autodeskToken}</pre>
</VStack>
);
}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 072d5a996c..0d18a02b45 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -15,6 +15,7 @@ export const path = {
accountingSubcategories: (id: string) =>
generatePath(`${api}/accounting/subcategories?accountCategoryId=${id}`),
assign: `${api}/assign`,
+ autodeskToken: `${api}/autodesk/token`,
currencies: `${api}/accounting/currencies`,
customerContacts: (id: string) =>
generatePath(`${api}/sales/customer-contacts?customerId=${id}`),
diff --git a/packages/redis/src/client.ts b/packages/redis/src/client.ts
index 8c7bd98379..5a39270763 100644
--- a/packages/redis/src/client.ts
+++ b/packages/redis/src/client.ts
@@ -1,13 +1,9 @@
import type { Redis as RedisType } from "@upstash/redis";
import { Redis } from "@upstash/redis";
-import type {
- RedisOptions as IoRedisOptions,
- Redis as IoRedisType,
-} from "ioredis";
-import IoRedis from "ioredis";
+import type { Redis as IoRedisType } from "ioredis";
-const USE_LOCAL_REDIS = !!process.env.USE_LOCAL_REDIS;
-const REDIS_URL = process.env.REDIS_URL;
+// const USE_LOCAL_REDIS = !!process.env.USE_LOCAL_REDIS;
+// const REDIS_URL = process.env.REDIS_URL;
const UPSTASH_REDIS_REST_URL = process.env.UPSTASH_REDIS_REST_URL;
const UPSTASH_REDIS_REST_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN;
@@ -17,53 +13,30 @@ declare global {
var __redis: RedisType | IoRedisType | undefined;
}
-if (USE_LOCAL_REDIS) {
- if (!REDIS_URL) {
- throw new Error("REDIS_URL is not defined");
- }
+if (!UPSTASH_REDIS_REST_URL) {
+ throw new Error("UPSTASH_REDIS_REST_URL is not defined");
+}
- const config: IoRedisOptions = {
- enableReadyCheck: false,
- maxRetriesPerRequest: null,
- };
+if (!UPSTASH_REDIS_REST_TOKEN) {
+ throw new Error("UPSTASH_REDIS_REST_TOKEN is not defined");
+}
- // this is needed because in development we don't want to restart
- // the server with every change, but we want to make sure we don't
- // create a new connection to the Redis with every change either.
- if (process.env.NODE_ENV === "production") {
- redis = new IoRedis(REDIS_URL, config);
- } else {
- if (!global.__redis) {
- global.__redis = new IoRedis(REDIS_URL, config);
- }
- redis = global.__redis;
- }
+// this is needed because in development we don't want to restart
+// the server with every change, but we want to make sure we don't
+// create a new connection to the Redis with every change either.
+if (process.env.NODE_ENV === "production") {
+ redis = new Redis({
+ url: UPSTASH_REDIS_REST_URL,
+ token: UPSTASH_REDIS_REST_TOKEN,
+ });
} else {
- if (!UPSTASH_REDIS_REST_URL) {
- throw new Error("UPSTASH_REDIS_REST_URL is not defined");
- }
-
- if (!UPSTASH_REDIS_REST_TOKEN) {
- throw new Error("UPSTASH_REDIS_REST_TOKEN is not defined");
- }
-
- // this is needed because in development we don't want to restart
- // the server with every change, but we want to make sure we don't
- // create a new connection to the Redis with every change either.
- if (process.env.NODE_ENV === "production") {
- redis = new Redis({
+ if (!global.__redis) {
+ global.__redis = new Redis({
url: UPSTASH_REDIS_REST_URL,
token: UPSTASH_REDIS_REST_TOKEN,
});
- } else {
- if (!global.__redis) {
- global.__redis = new Redis({
- url: UPSTASH_REDIS_REST_URL,
- token: UPSTASH_REDIS_REST_TOKEN,
- });
- }
- redis = global.__redis;
}
+ redis = global.__redis;
}
export default redis;