Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/landing/src/shared/icons/brands.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { CodexIcon } from "@onequery/ui/icons/codex-icon";
import { E2BIcon } from "@onequery/ui/icons/e2b-icon";
import { FigmaIcon } from "@onequery/ui/icons/figma-icon";
import { GoogleSearchConsoleIcon } from "@onequery/ui/icons/google-search-console-icon";
import { GranolaIcon } from "@onequery/ui/icons/granola-icon";
import { HermesAgentIcon } from "@onequery/ui/icons/hermes-agent-icon";
Expand Down Expand Up @@ -208,6 +209,7 @@ const BRAND_ICONS = {
curl: createSimpleBrandIcon(siCurl),
discord: createSimpleBrandIcon(siDiscord),
e2b: E2BIcon,
figma: FigmaIcon,
ga: createSimpleBrandIcon(siGoogleanalytics),
github: createSimpleBrandIcon(siGithub),
googledrive: createSimpleBrandIcon(siGoogledrive),
Expand Down
1 change: 1 addition & 0 deletions packages/db/src/__snapshots__/credentials.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ exports[`credentials schemas > credentialSchemaMap > matches supported provider
"confluence",
"discord",
"e2b",
"figma",
"ga",
"github",
"google_search_console",
Expand Down
11 changes: 11 additions & 0 deletions packages/db/src/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,15 @@ export const GitHubCredentialsSchema = z.object({

export type GitHubCredentials = z.infer<typeof GitHubCredentialsSchema>;

export const FigmaCredentialsSchema = z.object({
personalAccessToken: requiredOpaqueString(
"Personal access token is required"
),
type: z.literal("figma"),
});

export type FigmaCredentials = z.infer<typeof FigmaCredentialsSchema>;

export const AirtableCredentialsSchema = z.object({
apiBaseUrl: optionalTrimmedUrl("API base URL must be a valid URL"),
baseId: optionalTrimmedString("Base ID is required"),
Expand Down Expand Up @@ -704,6 +713,7 @@ export const CredentialsSchema = z.union([
PostHogCredentialsSchema,
SentryCredentialsSchema,
GitHubCredentialsSchema,
FigmaCredentialsSchema,
AirtableCredentialsSchema,
DiscordCredentialsSchema,
SlackCredentialsSchema,
Expand Down Expand Up @@ -779,6 +789,7 @@ export const credentialSchemaMap = {
confluence: ConfluenceCredentialsSchema,
discord: DiscordCredentialsSchema,
e2b: E2BCredentialsSchema,
figma: FigmaCredentialsSchema,
ga: GoogleAnalyticsCredentialsSchema,
github: GitHubCredentialsSchema,
google_search_console: GoogleSearchConsoleCredentialsSchema,
Expand Down
42 changes: 42 additions & 0 deletions packages/db/src/figma-credentials.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";

import { FigmaCredentialsSchema } from "./credentials";
import { safeParseSourceProviderCredentials } from "./source-providers";

describe("Figma credentials", () => {
it("accepts a personal access token", () => {
expect(
FigmaCredentialsSchema.safeParse({
personalAccessToken: "figd_test_token",
type: "figma",
}).success
).toBe(true);
});

it("rejects blank personal access tokens", () => {
expect(
FigmaCredentialsSchema.safeParse({
personalAccessToken: " ",
type: "figma",
}).success
).toBe(false);
});

it("injects the credential discriminator from the provider", () => {
const parsed = safeParseSourceProviderCredentials({
credentials: { personalAccessToken: "figd_test_token" },
provider: "figma",
});

expect(parsed).toMatchObject({
data: {
credentials: {
personalAccessToken: "figd_test_token",
type: "figma",
},
provider: "figma",
},
success: true,
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ exports[`data-sources schema > matches provider type snapshots 1`] = `
"posthog",
"sentry",
"github",
"figma",
"airtable",
"discord",
"slack",
Expand Down Expand Up @@ -64,6 +65,7 @@ exports[`data-sources schema > matches provider type snapshots 1`] = `
"posthog",
"sentry",
"github",
"figma",
"airtable",
"discord",
"slack",
Expand Down
30 changes: 30 additions & 0 deletions packages/db/src/source-providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
ConnectorCredentialsSchema,
DiscordCredentialsSchema,
E2BCredentialsSchema,
FigmaCredentialsSchema,
GitHubCredentialsSchema,
GoogleSearchConsoleCredentialsSchema,
GoogleAnalyticsCredentialsSchema,
Expand Down Expand Up @@ -703,6 +704,35 @@ export const SOURCE_PROVIDER_REGISTRY = {
},
},
},
figma: {
label: "Figma",
credentialSchema: FigmaCredentialsSchema,
credentialType: "figma",
connectable: true,
analysisSource: true,
queryInterface: false,
sourceApiInterface: true,
testable: false,
dashboardConnectable: true,
dashboardCredentialForm: "json",
publicCategory: "Developer workflow",
guide: {
summary:
"Connect Figma with a personal access token for read-only REST API and grouped design-context access.",
steps: [
"Create a Figma personal access token with the `file_content:read` scope.",
"Add `file_variables:read` when grouped design-context requests should include local variable definitions.",
"Copy the token into `credentials.personalAccessToken`.",
"Use `fetch_api` for read-only REST paths or `prepare_design_context` to bundle nodes, renders, image fills, and optional variables for selected frames.",
],
exampleInput: {
sourceKey: "figma_product",
credentials: {
personalAccessToken: "figd_personal_access_token",
},
},
},
},
airtable: {
label: "Airtable",
credentialSchema: AirtableCredentialsSchema,
Expand Down
114 changes: 114 additions & 0 deletions packages/server/src/source-api/adapters/figma-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import type { JsonValue } from "@bufbuild/protobuf";
import type { FigmaCredentials } from "@onequery/db/server";
import { z } from "zod";

import { MAX_PROVIDER_ERROR_DETAIL_LENGTH } from "../../services/provider-http";
import { ProviderHttpClient } from "../../services/provider-http-client";

const FIGMA_API_BASE_URL = "https://api.figma.com";

type FigmaDesignContextApiRequest = {
depth?: number;
fileKey: string;
includeImageFills: boolean;
includeVariables: boolean;
nodeIds: readonly string[];
renderFormat: "jpg" | "png" | "svg";
renderScale: number;
timeoutMs?: number;
};

export async function requestFigmaDesignContext(
credentials: FigmaCredentials,
request: FigmaDesignContextApiRequest
): Promise<JsonValue> {
const client = createFigmaHttpClient(credentials);
const fileKey = encodeURIComponent(request.fileKey);
const ids = request.nodeIds.join(",");
const commonParams = {
...(request.depth === undefined ? {} : { depth: request.depth }),
ids,
};
const [nodes, renders, imageFillsResult, variablesResult] = await Promise.all(
[
client.get(`/v1/files/${fileKey}/nodes`, commonParams, request.timeoutMs),
client.get(
`/v1/images/${fileKey}`,
{
format: request.renderFormat,
ids,
scale: request.renderScale,
},
request.timeoutMs
),
request.includeImageFills
? requestOptionalFigmaJson(
client.get(
`/v1/files/${fileKey}/images`,
undefined,
request.timeoutMs
),
"Figma image fills are unavailable"
)
: Promise.resolve({ value: null, warning: null }),
request.includeVariables
? requestOptionalFigmaJson(
client.get(
`/v1/files/${fileKey}/variables/local`,
undefined,
request.timeoutMs
),
"Figma local variables are unavailable"
)
: Promise.resolve({ value: null, warning: null }),
]
);
const warnings = [imageFillsResult.warning, variablesResult.warning].filter(
(warning): warning is string => warning !== null
);

return z.json().parse({
fileKey: request.fileKey,
imageFills: imageFillsResult.value,
localVariables: variablesResult.value,
nodeIds: request.nodeIds,
nodes,
renders,
warnings,
});
}

function createFigmaHttpClient(
credentials: FigmaCredentials
): ProviderHttpClient {
return new ProviderHttpClient({
auth: {
type: "raw",
value: credentials.personalAccessToken,
},
authHeaderName: "X-Figma-Token",
baseUrl: FIGMA_API_BASE_URL,
defaultHeaders: { Accept: "application/json" },
providerName: "Figma",
sanitize: (text) =>
text
.split(credentials.personalAccessToken)
.join("***")
.slice(0, MAX_PROVIDER_ERROR_DETAIL_LENGTH),
});
}

async function requestOptionalFigmaJson(
request: Promise<unknown>,
warningPrefix: string
): Promise<{ value: unknown; warning: string | null }> {
try {
return { value: await request, warning: null };
} catch (error) {
const detail = error instanceof Error ? error.message : String(error);
return {
value: null,
warning: `${warningPrefix}: ${detail}`,
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import type { JsonObject } from "@bufbuild/protobuf";
import { isRecord } from "@onequery/base";
import { z } from "zod";

import { MAX_PROVIDER_REQUEST_TIMEOUT_MS } from "../../services/provider-http";
import { SourceApiInvalidRequestError } from "../errors";
import type { SourceApiRequestBody } from "../types";
import {
figmaFileKeySchema,
figmaNodeIdSchema,
parseFigmaDesignUrl,
} from "./figma-url";

const figmaDesignContextInputSchema = z
.object({
depth: z.number().int().min(1).max(20).optional(),
fileKey: figmaFileKeySchema.optional(),
includeImageFills: z.boolean().default(true),
includeVariables: z.boolean().default(false),
nodeIds: z.array(figmaNodeIdSchema).min(1).max(20).optional(),
renderFormat: z.enum(["jpg", "png", "svg"]).default("png"),
renderScale: z.number().min(0.01).max(4).default(2),
timeoutMs: z
.number()
.int()
.min(1)
.max(MAX_PROVIDER_REQUEST_TIMEOUT_MS)
.optional(),
url: z.url().optional(),
})
.strict();

type FigmaDesignContextInput = z.infer<typeof figmaDesignContextInputSchema>;

export class FigmaDesignContextInvalidRequestError extends SourceApiInvalidRequestError {}

export function parseFigmaDesignContextRequest(value: JsonObject): JsonObject &
Omit<FigmaDesignContextInput, "url"> & {
fileKey: string;
nodeIds: string[];
} {
const parsed = figmaDesignContextInputSchema.safeParse(value);
if (!parsed.success) {
throwInvalidRequest();
}

const reference = parsed.data.url
? parseFigmaReference(parsed.data.url)
: null;
const fileKey = parsed.data.fileKey ?? reference?.fileKey;
const nodeIds = parsed.data.nodeIds ?? (reference ? [reference.nodeId] : []);
if (!fileKey || nodeIds.length === 0) {
throwInvalidRequest();
}

return {
...(parsed.data.depth === undefined ? {} : { depth: parsed.data.depth }),
fileKey,
includeImageFills: parsed.data.includeImageFills,
includeVariables: parsed.data.includeVariables,
nodeIds,
renderFormat: parsed.data.renderFormat,
renderScale: parsed.data.renderScale,
...(parsed.data.timeoutMs === undefined
? {}
: { timeoutMs: parsed.data.timeoutMs }),
};
}

export function parseFigmaDesignContextBody(
body: SourceApiRequestBody
): JsonObject {
if (body.kind === "none") {
return {};
}
if (body.kind === "json" && isRecord(body.value)) {
return body.value;
}
throw new FigmaDesignContextInvalidRequestError(
"Figma design context requests must be JSON objects"
);
}

function parseFigmaReference(url: string) {
try {
return parseFigmaDesignUrl(url);
} catch {
throwInvalidRequest();
}
}

function throwInvalidRequest(): never {
throw new FigmaDesignContextInvalidRequestError(
"Invalid Figma design context request"
);
}
Loading
Loading