Official

Figma

Connect Figma so your agents can read your design files: their pages, frames and layers, version history, team projects, published components and styles, and comment threads. Agents can also export frames or layers as PNG, JPG, SVG or PDF images to work with them.

With write access, agents can also post comments, reply to them, add reactions and delete their own comments. Figma notifies the people following those threads.

Figma limits how often files can be read and exported, and the limits are much lower for View and Collab seats and the Starter plan. Your credentials stay on Houston's server.

Connect Figma.

Setup instructions

Connect Figma

  1. In Figma, open Settings → Security → Personal access tokens → Generate new token. Set an expiry and the scopes below, then copy the token.
  2. In Houston, choose Personal access token, paste it, choose Read or Write for Access, and save.

Personal tokens expire within 90 days. Replace them in Houston before expiry. Your Figma plan and seat determine API quotas.

Scopes

For Read: current_user:read, file_content:read, file_metadata:read, file_versions:read, file_comments:read, library_assets:read, library_content:read, team_library_content:read and projects:read.

For Write, also file_comments:write.

See Figma's scopes, personal access tokens and OAuth apps guides.

Advanced

Your own OAuth app

  1. In Houston, choose Connect with Figma and copy OAuth callback URL.
  2. Under My apps, create an app owned by your team/organization. Register the callback under OAuth credentials → Add a redirect URL, and save its client ID and secret when shown.
  3. Enable both scope lists above. Publish it as Private for your team; other users need a reviewed public app. Draft apps work only for you and plan admins.
  4. Enter OAuth client ID and OAuth client secret in Houston, select Continue with Figma and allow access.

Each connection has its own callback. Reauthorize after changing access; personal tokens need replacement to add scopes. Missing team projects require membership and projects:read permission.

Files

  • connector.luau
    -- Figma REST API v1. Arguments and results keep Figma's native snake_case field names.
    type Options = {[string]: any}
    type Endpoint = {method: string, path: string, query: {string}?, extra: {string}?, required: {string}?, access: string?, body: (boolean | string)?,
    	doc: string, about: string}
    
    local PROVIDER = "Figma"
    local API = "https://api.figma.com"
    local DOCS = "https://developers.figma.com/docs/rest-api/"
    local CURSORS = {"page_size", "after", "before"}
    
    -- Operations in Figma's public OpenAPI (github.com/figma/rest-api-spec v0.46.0), checked on
    -- 2026-10-27. Path {fields} are required; listed query fields are taken from the options and
    -- the other fields form the JSON body.
    local endpoints: {[string]: Endpoint} = {
    	getMe = {method = "GET", path = "/v1/me", doc = "users-endpoints/#get-me-endpoint", about = "You: {id, handle, email, img_url}."},
    
    	getFile = {method = "GET", path = "/v1/files/{file_key}", query = {"version", "ids", "depth", "geometry", "plugin_data", "branch_data"},
    		doc = "file-endpoints/#get-files-endpoint",
    		about = "A file's document tree with its components and styles. Whole files can be very large: pass depth=1 for its pages, depth=2 for their top-level frames, or ids for some nodes."},
    	getFileNodes = {method = "GET", path = "/v1/files/{file_key}/nodes", query = {"ids", "version", "depth", "geometry", "plugin_data"}, required = {"ids"},
    		doc = "file-endpoints/#get-file-nodes-endpoint", about = "{nodes={[id]={document, components, styles}}} for the given nodes; a missing node maps to null."},
    	getFileMeta = {method = "GET", path = "/v1/files/{file_key}/meta", doc = "file-endpoints/#get-file-metadata-endpoint",
    		about = "{file={name, folder_name, last_touched_at, creator, thumbnail_url, editorType, role, link_access, url, version}} without the document."},
    	listFileVersions = {method = "GET", path = "/v1/files/{file_key}/versions", query = CURSORS, doc = "version-history-endpoints/#get-file-versions-endpoint",
    		about = "Saved versions, newest first, {versions, pagination}. page_size is at most 50; pass a version id as before for older ones."},
    	renderImages = {method = "GET", path = "/v1/images/{file_key}",
    		query = {"ids", "scale", "format", "svg_outline_text", "svg_include_id", "svg_include_node_id", "svg_simplify_stroke", "contents_only", "use_absolute_bounds", "version"},
    		extra = {"save_to"}, required = {"ids"}, doc = "file-endpoints/#get-images-endpoint",
    		about = "Renders nodes, {err, images={[id]=url}}; a node that fails to render maps to null. format: png (default), jpg, svg or pdf; scale 0.01..4 (default 1). With save_to, a session folder, each image is saved there as <id>.<format> (at most 10 ids) and images maps ids to {path, size, url}."},
    	getImageFills = {method = "GET", path = "/v1/files/{file_key}/images", doc = "file-endpoints/#get-image-fills-endpoint",
    		about = "Download links for the images used as fills, {meta={images={[imageRef]=url}}}; they expire within 14 days."},
    
    	listTeamProjects = {method = "GET", path = "/v1/teams/{team_id}/projects", doc = "projects-endpoints/#get-team-projects-endpoint",
    		about = "{name, projects} of a team you can see. Read team_id from a team URL, figma.com/files/team/<team_id>/..."},
    	listProjectFiles = {method = "GET", path = "/v1/projects/{project_id}/files", query = {"branch_data"}, doc = "projects-endpoints/#get-project-files-endpoint",
    		about = "{name, files: [{key, name, thumbnail_url, last_modified}]} of a project."},
    
    	listTeamComponents = {method = "GET", path = "/v1/teams/{team_id}/components", query = CURSORS, doc = "component-endpoints/#get-team-components-endpoint",
    		about = "Published components of a team's libraries, {meta={components, cursor}}. page_size is at most 1000; pass meta.cursor.after as after."},
    	listTeamComponentSets = {method = "GET", path = "/v1/teams/{team_id}/component_sets", query = CURSORS, doc = "component-endpoints/#get-team-component-sets-endpoint",
    		about = "Published component sets (variants), paged like listTeamComponents."},
    	listTeamStyles = {method = "GET", path = "/v1/teams/{team_id}/styles", query = CURSORS, doc = "component-endpoints/#get-team-styles-endpoint",
    		about = "Published styles, paged like listTeamComponents."},
    	listFileComponents = {method = "GET", path = "/v1/files/{file_key}/components", doc = "component-endpoints/#get-file-components-endpoint",
    		about = "Published components of a library file, {meta={components}}."},
    	listFileComponentSets = {method = "GET", path = "/v1/files/{file_key}/component_sets", doc = "component-endpoints/#get-file-component-sets-endpoint",
    		about = "Published component sets of a library file."},
    	listFileStyles = {method = "GET", path = "/v1/files/{file_key}/styles", doc = "component-endpoints/#get-file-styles-endpoint",
    		about = "Published styles of a library file."},
    	getComponent = {method = "GET", path = "/v1/components/{key}", doc = "component-endpoints/#get-component-endpoint",
    		about = "A published component by its key (not its node id)."},
    	getComponentSet = {method = "GET", path = "/v1/component_sets/{key}", doc = "component-endpoints/#get-component-set-endpoint",
    		about = "A published component set by its key."},
    	getStyle = {method = "GET", path = "/v1/styles/{key}", doc = "component-endpoints/#get-style-endpoint", about = "A published style by its key."},
    
    	listComments = {method = "GET", path = "/v1/files/{file_key}/comments", query = {"as_md"}, doc = "comments-endpoints/#get-comments-endpoint",
    		about = "All comments of a file, unpaginated, {comments: [{id, message, parent_id, user, created_at, resolved_at, client_meta, order_id, reactions}]}. parent_id marks a reply; as_md=true returns messages in Markdown."},
    	listCommentReactions = {method = "GET", path = "/v1/files/{file_key}/comments/{comment_id}/reactions", query = {"cursor"},
    		doc = "comments-endpoints/#get-comment-reactions-endpoint", about = "{reactions, pagination}; pass pagination.next_page as cursor for the next page."},
    	postComment = {method = "POST", path = "/v1/files/{file_key}/comments", access = "data:write", required = {"message"}, doc = "comments-endpoints/#post-comments-endpoint",
    		about = "Body {message, comment_id?, client_meta?}. comment_id replies to a top-level comment. client_meta pins it: {x, y}, {node_id, node_offset={x, y}}, or a region adding region_width and region_height. Figma notifies the people mentioned or following the thread."},
    	deleteComment = {method = "DELETE", path = "/v1/files/{file_key}/comments/{comment_id}", access = "data:write", doc = "comments-endpoints/#delete-comments-endpoint",
    		about = "Deletes one of your own comments."},
    	addCommentReaction = {method = "POST", path = "/v1/files/{file_key}/comments/{comment_id}/reactions", access = "data:write", required = {"emoji"},
    		doc = "comments-endpoints/#post-comment-reactions-endpoint", about = "Body {emoji}, a shortcode such as ':+1:' or ':heart:'."},
    	removeCommentReaction = {method = "DELETE", path = "/v1/files/{file_key}/comments/{comment_id}/reactions", access = "data:write", query = {"emoji"}, required = {"emoji"},
    		doc = "comments-endpoints/#delete-comment-reactions-endpoint", about = "Removes your reaction with that emoji."},
    }
    
    -- Request layer shared verbatim by the endpoint-table connectors
    -- (tools/validate checks they match). It uses each connector's PROVIDER, DOCS and Endpoint type.
    local NULL = json.decode("null")
    local NONE: {string} = table.freeze({})
    
    local function options(input: Options?): Options
    	if input == nil then return {} end
    	assert(type(input) == "table", "opts must be an object")
    	for key in input do assert(type(key) == "string", "opts must have named fields") end
    	return table.clone(input)
    end
    
    local function scalar(value: any, field: string): string
    	local kind = type(value)
    	assert(kind == "string" or kind == "boolean" or kind == "number", field .. " must be a string, boolean, number or array of those")
    	return url.encode(value)
    end
    
    -- A query value's encoded parts: one for a scalar, one per item of a nonempty array. Each
    -- connector joins them as its provider expects, comma-separated or with the key repeated.
    local function queryParts(value: any, field: string): {string}
    	if type(value) ~= "table" then return {scalar(value, field)} end
    	local parts: {string} = {}
    	for index, item in value do
    		assert(type(index) == "number" and index == #parts + 1, field .. " must be an array, not an object")
    		table.insert(parts, scalar(item, field))
    	end
    	assert(#parts > 0, field .. " must not be an empty array")
    	return parts
    end
    
    -- POST, PATCH and PUT send the remaining options as the JSON body unless body is false
    -- (no body) or names the one option to send.
    local function hasBody(endpoint: Endpoint): boolean
    	return endpoint.body ~= false and (endpoint.method == "POST" or endpoint.method == "PATCH" or endpoint.method == "PUT")
    end
    
    local function fail(name: string, response: HttpResponse, message: string): never
    	return houston.fail({operation = name, layer = "upstream", upstream_status = response.statusCode,
    		retryable = response.statusCode == 429 or response.statusCode >= 500, message = message})
    end
    
    -- A successful response's JSON object, or nil when a write answers without a body. With arrays,
    -- a top-level JSON array is accepted too, and the second result tells which one came back.
    local function object(name: string, endpoint: Endpoint, response: HttpResponse, arrays: boolean?): (any, boolean)
    	local raw = await(response.body:readAll())
    	if endpoint.method ~= "GET" and endpoint.access and string.match(raw, "^%s*$") then return nil, false end
    	local ok, value = pcall(json.decode, raw)
    	local list = arrays == true and string.match(raw, "^%s*%[") ~= nil
    	if not ok or type(value) ~= "table" or not (list or string.match(raw, "^%s*{")) then
    		fail(name, response, PROVIDER .. " returned an invalid JSON object")
    	end
    	return value, list
    end
    
    -- name({path fields, query fields?, extra fields?, required body fields, ...body}) built from the
    -- endpoint itself.
    -- Extra fields are options the connector's own request consumes, such as a request header.
    local function signature(endpoint: Endpoint): string
    	local fields: {string} = {}
    	for field in string.gmatch(endpoint.path, "{([%w_]+)}") do table.insert(fields, field) end
    	for _, group in {endpoint.query or NONE, endpoint.extra or NONE} do
    		for _, field in group do
    			table.insert(fields, if table.find(endpoint.required or NONE, field) then field else field .. "?")
    		end
    	end
    	if type(endpoint.body) == "string" then
    		table.insert(fields, endpoint.body)
    	elseif hasBody(endpoint) then
    		for _, field in endpoint.required or NONE do
    			if not table.find(fields, field) then table.insert(fields, field) end
    		end
    		table.insert(fields, "...body")
    	end
    	return "({" .. table.concat(fields, ", ") .. "})"
    end
    
    -- A function for each endpoint the connection's access allows, and help listing them after intro.
    local function operations(endpoints: {[string]: Endpoint}, request: (string, Endpoint, Options?) -> any, intro: {string}): {[string]: any}
    	local exports: {[string]: any} = {}
    	for name, endpoint in endpoints do
    		if not endpoint.access or houston.allows(endpoint.access) then
    			exports[name] = function(args: Options?): any return request(name, endpoint, args) end
    		end
    	end
    	exports.help = function(): string
    		local names: {string} = {}
    		for name in exports do if name ~= "help" then table.insert(names, name) end end
    		table.sort(names)
    		local lines = table.clone(intro)
    		table.insert(lines, "Each function below names its route and reference page, " .. DOCS .. "<page>.")
    		for _, name in names do
    			local endpoint = endpoints[name]
    			table.insert(lines, name .. signature(endpoint) .. ": " .. endpoint.about .. " " .. endpoint.method .. " " .. endpoint.path .. " (" .. endpoint.doc .. ")")
    		end
    		return table.concat(lines, "\n")
    	end
    	return exports
    end
    -- End of the shared request layer.
    
    -- A file key, or the key in a Figma file URL such as https://www.figma.com/design/<key>/<name>,
    -- where /branch/<key> names a branch.
    local FILE_KINDS = {file = true, design = true, board = true, proto = true, slides = true, deck = true, site = true, make = true, buzz = true}
    
    local function fileKey(value: any): string
    	assert(type(value) == "string", "file_key must be a Figma file key or URL")
    	local key: string? = value
    	-- Links pasted without a scheme, or with http://, are file URLs too.
    	local link = string.gsub(value, "^http://", "https://")
    	if string.find(link, "^[%w%.%-]*figma%.com/") then link = "https://" .. link end
    	if string.find(link, "^https://") then
    		local host, rest = string.match(link, "^https://([%w%.%-]+)/([^?#]*)")
    		local figma = host ~= nil and (string.lower(host) == "figma.com" or string.sub(string.lower(host), -10) == ".figma.com")
    		assert(figma, "file_key must be a Figma file key or URL")
    		local kind, main, tail = string.match(rest :: string, "^([%w%-]+)/(%w+)(.*)$")
    		key = if kind and FILE_KINDS[kind] then string.match(tail :: string, "^/branch/(%w+)") or main else nil
    	end
    	assert(key and string.match(key, "^%w+$"), "file_key must be a Figma file key or URL")
    	return key :: string
    end
    
    -- Path fields other than file_key: team, project and comment ids are numeric, component and
    -- style keys hexadecimal.
    local function identifier(value: any, field: string): string
    	if field == "file_key" then return fileKey(value) end
    	local pattern = if field == "key" then "^%x+$" else "^%d+$"
    	assert(type(value) == "string" and string.match(value, pattern), field .. (if field == "key" then " must be a Figma key" else " must be a numeric id string"))
    	return value
    end
    
    -- Reaction pages link the next one as a URL; its cursor value is already encoded.
    local function cursor(value: any): string
    	if type(value) == "string" and string.find(value, "^https://api%.figma%.com/") then
    		local encoded = string.match(value, "[?&]cursor=([^&#]+)")
    		assert(encoded and string.match(encoded, "^[%w%%%-%._~]+$"), "cursor must be a cursor or pagination.next_page")
    		return encoded
    	end
    	local parts = queryParts(value, "cursor")
    	assert(#parts == 1, "cursor must be one value")
    	return parts[1]
    end
    
    -- A node id such as 1:2 or I1:2;3:4. URLs write 1:2 as 1-2, and older links percent-encode
    -- : and ;.
    local function nodeId(item: string, field: string): string
    	local id = string.match(item, "^%s*(.-)%s*$") :: string
    	id = string.gsub(id, "%%3[Aa]", ":")
    	id = string.gsub(id, "%%3[Bb]", ";")
    	id = string.gsub(id, "-", ":")
    	assert(string.match(id, "^[%w:;]+$"), field .. " must be node ids such as 1:2")
    	return id
    end
    
    -- Node ids as a list or comma-separated.
    local function nodeIds(value: any): {string}
    	local items: {string} = {}
    	if type(value) == "string" then
    		for item in string.gmatch(value, "[^,]+") do table.insert(items, item) end
    	else
    		assert(type(value) == "table", "ids must be a list or comma-separated string of node ids")
    		for index, item in value do
    			assert(type(index) == "number" and index == #items + 1 and type(item) == "string", "ids must be a list or comma-separated string of node ids")
    			table.insert(items, item)
    		end
    	end
    	assert(#items > 0, "ids must name at least one node")
    	for index, item in items do items[index] = url.encode(nodeId(item, "ids")) end
    	return items
    end
    
    -- Figma errors are {status, err} or {error=true, status, message}; rate limits add Retry-After
    -- and the seat's limit type.
    local function failStatus(name: string, response: HttpResponse): never
    	local message = "Figma HTTP " .. tostring(response.statusCode)
    	local ok, value = pcall(json.decode, await(response.body:readPrefix(16 * 1024)))
    	if ok and type(value) == "table" then
    		local text = if type(value.err) == "string" then value.err else value.message
    		if type(text) == "string" then message ..= ": " .. string.sub(text, 1, 600) end
    	end
    	if response.statusCode == 429 then
    		for _, header in {"retry-after", "x-figma-rate-limit-type", "x-figma-plan-tier"} do
    			local values = response.headers[header]
    			if values and values[1] then message ..= "; " .. header .. " " .. string.sub(values[1], 1, 100) end
    		end
    	end
    	return fail(name, response, message)
    end
    
    local function decode(name: string, endpoint: Endpoint, response: HttpResponse): any
    	if response.statusCode < 200 or response.statusCode >= 300 then failStatus(name, response) end
    	-- Deletions may answer without a body.
    	return object(name, endpoint, response) or {success = true}
    end
    
    -- Renders live on a public bucket, fetched without credentials.
    local RENDERS = "https://figma-alpha-api.s3.us-west-2.amazonaws.com/images/"
    local FORMATS = {png = true, jpg = true, svg = true, pdf = true}
    local MAX_SAVED, CLEANUP_WAIT, DOWNLOAD_WAIT = 10, 1000, 15000
    
    local function failRender(name: string, status: number, retryable: boolean, message: string): never
    	return houston.fail({operation = name, layer = "upstream", upstream_status = status, retryable = retryable, message = message})
    end
    
    -- A render's file name: 1:2 saves as 1-2 and I1:2;3:4 as I1-2_3-4, so distinct ids never share one.
    local function fileName(id: string, format: string): string
    	local name = string.gsub(id, ":", "-")
    	name = string.gsub(name, ";", "_")
    	return name .. "." .. format
    end
    
    local function closeAll(downloads: {any})
    	for _, download in downloads do pcall(function() await(download, CLEANUP_WAIT).body:close() end) end
    end
    
    -- Downloads every render at once, so a batch fits the invocation's 30 seconds.
    local function save(name: string, rendered: any, folder: string, format: string): any
    	if type(rendered) ~= "table" or type(rendered.images) ~= "table" then
    		return failRender(name, 200, false, "Figma rendered no images"
    			.. (if type(rendered) == "table" and type(rendered.err) == "string" then ": " .. string.sub(rendered.err, 1, 600) else ""))
    	end
    	local ids: {string} = {}
    	for id, link in rendered.images do
    		if type(link) ~= "string" then continue end
    		if string.find(link, RENDERS, 1, true) ~= 1 then return failRender(name, 200, false, "Figma returned a render on an unexpected host") end
    		table.insert(ids, id)
    	end
    	table.sort(ids)
    	if #ids == 0 then return rendered end
    	local downloads = {}
    	for index, id in ids do downloads[index] = http.request({method = "GET", url = rendered.images[id], timeoutMs = DOWNLOAD_WAIT}) end
    	local fetched, responses = pcall(awaitAll, downloads)
    	if not fetched then
    		closeAll(downloads)
    		return failRender(name, 0, true, "Downloading the renders failed before Figma's bucket answered")
    	end
    	for index, id in ids do
    		local status = responses[index].statusCode
    		if status ~= 200 then
    			closeAll(downloads)
    			return failRender(name, status, status == 403 or status >= 500, "Downloading the render of " .. id .. " failed with HTTP " .. tostring(status))
    		end
    	end
    	local paths = {}
    	local closes = {}
    	local written = pcall(function()
    		for index, id in ids do
    			paths[index] = folder .. "/" .. fileName(id, format)
    			local output = fs.open(paths[index], "w")
    			output:write(responses[index].body)
    			closes[index] = output:close()
    		end
    		awaitAll(closes)
    	end)
    	if not written then
    		for _, close in closes do pcall(function() await(close, CLEANUP_WAIT) end) end
    		closeAll(downloads)
    		return failRender(name, 0, true, "Saving the renders in " .. string.sub(folder, 1, 200) .. " failed; some renders were not saved")
    	end
    	local stats, links = {}, {}
    	for index in ids do
    		stats[index] = fs.stat(paths[index])
    		links[index] = fs.signedGetUrl(paths[index])
    	end
    	local sizes, urls = awaitAll(stats), awaitAll(links)
    	for index, id in ids do
    		rendered.images[id] = {path = paths[index], size = sizes[index].size, url = urls[index]}
    	end
    	return rendered
    end
    
    local function request(name: string, endpoint: Endpoint, input: Options?): any
    	local args = options(input)
    	local path = string.gsub(endpoint.path, "{([%w_]+)}", function(field: string)
    		local value = identifier(args[field], field)
    		args[field] = nil
    		return value
    	end)
    	for _, field in endpoint.required or NONE do
    		assert(args[field] ~= nil and args[field] ~= NULL, field .. " is required")
    	end
    	-- Comment pins take node ids in their URL form too.
    	if type(args.client_meta) == "table" and type(args.client_meta.node_id) == "string" then
    		args.client_meta = table.clone(args.client_meta)
    		args.client_meta.node_id = nodeId(args.client_meta.node_id, "client_meta.node_id")
    	end
    	local folder: string? = nil
    	local format = args.format or "png"
    	if table.find(endpoint.extra or NONE, "save_to") and args.save_to ~= nil then
    		local target = args.save_to
    		assert(type(target) == "string", "save_to must be a session folder path")
    		folder = (string.gsub(target, "/+$", ""))
    		assert(folder ~= "", "save_to must be a session folder path")
    		assert(FORMATS[format], "format must be png, jpg, svg or pdf")
    		args.save_to = nil
    	end
    	local query: {string} = {}
    	for _, field in endpoint.query or NONE do
    		if args[field] ~= nil then
    			local parts = if field == "ids" then nodeIds(args[field]) elseif field == "cursor" then {cursor(args[field])} else queryParts(args[field], field)
    			if field == "ids" and folder ~= nil then assert(#parts <= MAX_SAVED, "save_to saves at most " .. MAX_SAVED .. " ids at once") end
    			table.insert(query, field .. "=" .. table.concat(parts, ","))
    		end
    		args[field] = nil
    	end
    	if #query > 0 then path ..= "?" .. table.concat(query, "&") end
    	local headers: HttpHeaders = {Accept = {"application/json"}}
    	local body: string? = nil
    	if hasBody(endpoint) then
    		headers["Content-Type"] = {"application/json"}
    		body = json.encode(args)
    		args = {}
    	end
    	local unknown = next(args)
    	assert(unknown == nil, name .. " has no option " .. tostring(unknown))
    	local result = decode(name, endpoint, await(http.request({url = API .. path, method = endpoint.method, headers = headers, body = body})))
    	if folder ~= nil then return save(name, result, folder, format) end
    	return result
    end
    
    local intro = {
    	"Figma REST API v1. Every function takes one named options object with Figma's snake_case names; ? marks optional fields and ...body the JSON body fields. Results are Figma's JSON unchanged. Connector calls return completed values: use them directly, without await.",
    	"file_key takes a file or branch key, or a Figma file URL such as https://www.figma.com/design/<key>/<name>?node-id=1-2. Node ids are like 1:2 or I1:2;3:4; ids takes a list or comma-separated string, and the URL form 1-2 also works. team_id is the number after /team/ in a team's URL in the file browser; no endpoint lists your teams. Keep ids as strings.",
    	"Examples: local file = figma.getFile({file_key=link, depth=2}); figma.getFileNodes({file_key=link, ids={'1:2'}}); figma.renderImages({file_key=link, ids={'1:2', '1:3'}, format='png', scale=2, save_to='renders'}); figma.listComments({file_key=link, as_md=true}).",
    	"Figma limits requests by endpoint tier, seat and plan: file, node and render calls are tier 1, 10 to 20 a minute on Dev and Full seats of paid plans but at most 20 a month on View and Collab seats and 6 a month for files on the Starter plan; comments, versions and projects are tier 2, metadata and libraries tier 3. Houston retries an HTTP 429 twice when Retry-After is 5 seconds or less, then reports Retry-After, the seat's limit type and the plan. Results above 8 MiB fail: narrow getFile with depth or ids. A call, saved renders included, must finish within 30 seconds: save fewer ids or a smaller scale when renders are large.",
    	"Errors report the HTTP status and Figma's message.",
    }
    if houston.allows("data:write") then
    	table.insert(intro, "Side effects: postComment and addCommentReaction notify the file's followers and mentioned people; deleteComment works on your own comments only. Other failures are not retried: after a timeout or 5xx, list the comments before repeating a write.")
    else
    	table.insert(intro, "This read-only connection omits writes.")
    end
    
    return operations(endpoints, request, intro)
    
  • houston.json
    {
      "schema_version": 2,
      "name": "Figma",
      "files": [
        "connector.luau"
      ],
      "icon": "icon.svg",
      "access": [
        {
          "name": "data",
          "label": "Access",
          "levels": [
            {
              "value": "read",
              "label": "Read"
            },
            {
              "value": "write",
              "label": "Write"
            }
          ],
          "default": "read"
        }
      ],
      "config": {
        "client_id": {
          "label": "OAuth client ID",
          "order": 1,
          "type": "string"
        },
        "client_secret": {
          "label": "OAuth client secret",
          "order": 2,
          "type": "secret"
        }
      },
      "auth": {
        "token": {
          "type": "manual",
          "label": "Personal access token",
          "order": 1,
          "config": {
            "token": {
              "label": "Personal access token",
              "required": true,
              "type": "secret"
            }
          }
        },
        "oauth": {
          "type": "oauth2",
          "label": "Connect with Figma",
          "brand": "figma",
          "order": 2,
          "authorize_url": "https://www.figma.com/oauth",
          "token_url": "https://api.figma.com/v1/oauth/token",
          "client_auth": "basic",
          "pkce": "S256",
          "client_id": "{{config.client_id}}",
          "client_secret": "{{config.client_secret}}",
          "require_refresh": true,
          "scopes": [
            {
              "values": [
                "current_user:read",
                "file_content:read",
                "file_metadata:read",
                "file_versions:read",
                "file_comments:read",
                "library_assets:read",
                "library_content:read",
                "team_library_content:read",
                "projects:read"
              ]
            },
            {
              "if": "{{ allows access.data \"write\" }}",
              "values": [
                "file_comments:write"
              ]
            }
          ],
          "account": {
            "url": "https://api.figma.com/v1/me",
            "headers": {
              "Authorization": {
                "value": "Bearer {{auth.oauth.access_token}}"
              }
            },
            "label": "/email"
          }
        }
      },
      "proxy": [
        {
          "if": "{{ isDefined auth.token }}",
          "match": {
            "protocol": "http",
            "host": [
              "api.figma.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/v1/component_sets/{key}",
              "/v1/components/{key}",
              "/v1/files/{file_key}",
              "/v1/files/{file_key}/comments",
              "/v1/files/{file_key}/comments/{comment_id}/reactions",
              "/v1/files/{file_key}/component_sets",
              "/v1/files/{file_key}/components",
              "/v1/files/{file_key}/images",
              "/v1/files/{file_key}/meta",
              "/v1/files/{file_key}/nodes",
              "/v1/files/{file_key}/styles",
              "/v1/files/{file_key}/versions",
              "/v1/images/{file_key}",
              "/v1/me",
              "/v1/projects/{project_id}/files",
              "/v1/styles/{key}",
              "/v1/teams/{team_id}/component_sets",
              "/v1/teams/{team_id}/components",
              "/v1/teams/{team_id}/projects",
              "/v1/teams/{team_id}/styles"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "X-Figma-Token": "{{auth.token.token}}"
              }
            }
          }
        },
        {
          "if": "{{ isDefined auth.oauth }}",
          "match": {
            "protocol": "http",
            "host": [
              "api.figma.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/v1/component_sets/{key}",
              "/v1/components/{key}",
              "/v1/files/{file_key}",
              "/v1/files/{file_key}/comments",
              "/v1/files/{file_key}/comments/{comment_id}/reactions",
              "/v1/files/{file_key}/component_sets",
              "/v1/files/{file_key}/components",
              "/v1/files/{file_key}/images",
              "/v1/files/{file_key}/meta",
              "/v1/files/{file_key}/nodes",
              "/v1/files/{file_key}/styles",
              "/v1/files/{file_key}/versions",
              "/v1/images/{file_key}",
              "/v1/me",
              "/v1/projects/{project_id}/files",
              "/v1/styles/{key}",
              "/v1/teams/{team_id}/component_sets",
              "/v1/teams/{team_id}/components",
              "/v1/teams/{team_id}/projects",
              "/v1/teams/{team_id}/styles"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "X-Figma-Token"
              ],
              "set": {
                "Authorization": "Bearer {{auth.oauth.access_token}}"
              }
            }
          }
        },
        {
          "if": "{{ and (allows access.data \"write\") (isDefined auth.token) }}",
          "match": {
            "protocol": "http",
            "host": [
              "api.figma.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/v1/files/{file_key}/comments",
              "/v1/files/{file_key}/comments/{comment_id}/reactions"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "X-Figma-Token": "{{auth.token.token}}"
              }
            }
          }
        },
        {
          "if": "{{ and (allows access.data \"write\") (isDefined auth.token) }}",
          "match": {
            "protocol": "http",
            "host": [
              "api.figma.com"
            ],
            "method": [
              "DELETE"
            ],
            "path": [
              "/v1/files/{file_key}/comments/{comment_id}",
              "/v1/files/{file_key}/comments/{comment_id}/reactions"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization"
              ],
              "set": {
                "X-Figma-Token": "{{auth.token.token}}"
              }
            }
          }
        },
        {
          "if": "{{ and (allows access.data \"write\") (isDefined auth.oauth) }}",
          "match": {
            "protocol": "http",
            "host": [
              "api.figma.com"
            ],
            "method": [
              "POST"
            ],
            "path": [
              "/v1/files/{file_key}/comments",
              "/v1/files/{file_key}/comments/{comment_id}/reactions"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "X-Figma-Token"
              ],
              "set": {
                "Authorization": "Bearer {{auth.oauth.access_token}}"
              }
            }
          }
        },
        {
          "if": "{{ and (allows access.data \"write\") (isDefined auth.oauth) }}",
          "match": {
            "protocol": "http",
            "host": [
              "api.figma.com"
            ],
            "method": [
              "DELETE"
            ],
            "path": [
              "/v1/files/{file_key}/comments/{comment_id}",
              "/v1/files/{file_key}/comments/{comment_id}/reactions"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "X-Figma-Token"
              ],
              "set": {
                "Authorization": "Bearer {{auth.oauth.access_token}}"
              }
            }
          }
        },
        {
          "match": {
            "protocol": "http",
            "host": [
              "figma-alpha-api.s3.us-west-2.amazonaws.com"
            ],
            "method": [
              "GET"
            ],
            "path": [
              "/images/*"
            ]
          },
          "action": {
            "headers": {
              "remove": [
                "Authorization",
                "X-Figma-Token"
              ]
            }
          }
        }
      ]
    }
    
  • icon.svgicon.svg
  • README.md
    ---
    description: Read Figma files, components, styles and comments, export frames as images, and reply to comments.
    ---
    
    # Figma
    
    Connect Figma so your agents can read your design files: their pages, frames
    and layers, version history, team projects, published components and styles,
    and comment threads. Agents can also export frames or layers as PNG, JPG, SVG or
    PDF images to work with them.
    
    With write access, agents can also post comments, reply to them, add
    reactions and delete their own comments. Figma notifies the people following
    those threads.
    
    Figma limits how often files can be read and exported, and the limits are much
    lower for View and Collab seats and the Starter plan. Your credentials stay on
    Houston's server.
    
    [Connect Figma](SETUP.md).
    
  • SETUP.md
    # Connect Figma
    
    1. In Figma, open **Settings → Security → Personal access tokens → Generate new
       token**. Set an expiry and the scopes below, then copy the token.
    2. In Houston, choose **Personal access token**, paste it, choose **Read** or
       **Write** for **Access**, and save.
    
    > Personal tokens expire within 90 days. Replace them in Houston before expiry.
    > Your Figma plan and seat determine API quotas.
    
    ## Scopes
    
    For **Read**: `current_user:read`, `file_content:read`,
    `file_metadata:read`, `file_versions:read`, `file_comments:read`,
    `library_assets:read`, `library_content:read`, `team_library_content:read` and
    `projects:read`.
    
    For **Write**, also `file_comments:write`.
    
    See Figma's [scopes](https://developers.figma.com/docs/rest-api/scopes/),
    [personal access tokens](https://developers.figma.com/docs/rest-api/personal-access-tokens/)
    and [OAuth apps](https://developers.figma.com/docs/rest-api/oauth-apps/) guides.
    
    ## Advanced
    
    ### Your own OAuth app
    
    1. In Houston, choose **Connect with Figma** and copy **OAuth callback URL**.
    2. Under [My apps](https://www.figma.com/developers/apps), create an app owned by
       your team/organization. Register the callback under **OAuth credentials →
       Add a redirect URL**, and save its client ID and secret when shown.
    3. Enable both scope lists above. Publish it as **Private** for your team;
       other users need a reviewed public app. Draft apps work only for you and plan admins.
    4. Enter **OAuth client ID** and **OAuth client secret** in Houston, select
       **Continue with Figma** and allow access.
    
    Each connection has its own callback. Reauthorize after changing access; personal
    tokens need replacement to add scopes. Missing team projects require membership
    and `projects:read` permission.
    
  • tests
    • authentication.luau
      return {
      	contract = function(m)
      		m.authentication({
      			{
      				auth = {},
      				config = {
      					client_id = "synthetic-public-client",
      					client_secret = "synthetic-client-secret",
      				},
      				endpoint = { "GET", "https://api.figma.com/v1/me" },
      				expected = "Bearer synthetic-oauth-token",
      				header = "Authorization",
      				method = "oauth",
      				oauth = true,
      				publisher = {},
      				scopes = true,
      			},
      			{
      				auth = { token = "synthetic-method-secret" },
      				config = {},
      				endpoint = { "GET", "https://api.figma.com/v1/me" },
      				expected = "synthetic-method-secret",
      				header = "X-Figma-Token",
      				method = "token",
      				publisher = {},
      			},
      		})
      	end,
      }
      
    • endpoints.luau
      return {
      	contract = function(m)
      		local want = {}
      		for _, entry in m.endpoints() do
      			table.insert(want, entry.method .. " " .. entry.path .. " " .. tostring(entry.access ~= nil))
      		end
      		for _, method in { "auth.token", "auth.oauth" } do
      			local got = {}
      			for _, rule in m.raw.proxy do
      				local gate = rule["if"] or ""
      				if
      					not string.find(gate, method .. " ", 1, true)
      					and not string.find(gate, method .. ")", 1, true)
      				then
      					continue
      				end
      				for _, verb in rule.match.method do
      					for _, path in rule.match.path do
      						table.insert(
      							got,
      							verb
      								.. " "
      								.. path
      								.. " "
      								.. tostring(string.find(gate, 'allows access.data "write"', 1, true) ~= nil)
      						)
      					end
      				end
      			end
      			m.sortedEqual(table.clone(want), got)
      		end
      	end,
      }
      
    • errors.luau
      return {
      	scenario = {publisher = {}, access = {data = "write"}, config = {}, auth_method = "token", auth_config = {token = "figd_fixture"}},
      	configure = function()
      		calls = 0
      		status = 200
      		payload = "{}"
      		responseHeaders = {}
      		http = {request = function(req)
      			calls += 1
      			return fixture.operation({statusCode = status, headers = responseHeaders, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(figma)
      		local function upstream(code, body, headers, expected, unexpected)
      			status, payload, responseHeaders = code, body, headers
      			local before = calls
      			local ok, err = pcall(function() figma.postComment({file_key = "aBcDeFgHiJkLmNoPqRsTuV12", message = "Hi"}) end)
      			for _, text in expected do
      				assert(not ok and string.find(tostring(err), text, 1, true), "missing " .. text .. " in " .. tostring(err))
      			end
      			assert(unexpected == nil or not string.find(tostring(err), unexpected, 1, true), "message was not bounded")
      			assert(calls == before + 1, "failed write was retried")
      		end
      		upstream(403, '{"status":403,"err":"Invalid token"}', {}, {"Figma HTTP 403: Invalid token", '"retryable":false'})
      		upstream(400, '{"error":true,"status":400,"message":"Comment message is required"}', {}, {"Figma HTTP 400: Comment message is required"})
      		upstream(404, json.encode({status = 404, err = string.rep("x", 5000)}), {}, {"Figma HTTP 404: xxx"}, string.rep("x", 601))
      		upstream(429, '{"status":429,"err":"Rate limit exceeded"}', {["retry-after"] = {"60"}, ["x-figma-rate-limit-type"] = {"low"}, ["x-figma-plan-tier"] = {"starter"}},
      			{"Figma HTTP 429: Rate limit exceeded; retry-after 60; x-figma-rate-limit-type low; x-figma-plan-tier starter", '"retryable":true'})
      		upstream(500, "<html>Error</html>", {}, {"Figma HTTP 500", '"retryable":true'})
      		upstream(200, "<html>Maintenance</html>", {}, {"invalid JSON object"})
      		upstream(200, "[]", {}, {"invalid JSON object"})
      	end,
      }
      
    • manifest.luau
      return {
      	contract = function(m)
      		local assertFigmaRoutes = function(r, header, value, allowed, ...)
      			local routes = { ... }
      			for _, route in routes do
      				local method, url, _ = m.cut(route, " ")
      				local recipe, err = m.recipe(r, method, url, nil)
      				if (err == nil) ~= allowed then
      					m.fail("%s allowed=%s: %s", route, (err == nil), err)
      				end
      				if err ~= nil then
      					continue
      				end
      				local headers, err = m.prepare(
      					recipe,
      					r.Context,
      					{ Authorization = { "forged" }, ["X-Figma-Token"] = { "forged" } }
      				)
      				local other = "Authorization"
      				if header == other then
      					other = "X-Figma-Token"
      				end
      				if
      					((err ~= nil) or (m.header(headers, header) ~= value)) or (m.header(headers, other) ~= "")
      				then
      					m.fail("credential injection for %s: %s %s", route, headers, err)
      				end
      			end
      		end
      		-- TestFigmaScopesAndAccessRoutes
      		do
      			local readScopes = {
      				"current_user:read",
      				"file_content:read",
      				"file_metadata:read",
      				"file_versions:read",
      				"file_comments:read",
      				"library_assets:read",
      				"library_content:read",
      				"team_library_content:read",
      				"projects:read",
      			}
      			local api, key = "https://api.figma.com", "aBcDeFgHiJkLmNoPqRsTuV12"
      			local entries = m.endpoints()
      			local ids = { file_key = key, team_id = "123", project_id = "77", comment_id = "7", key = "abc" }
      			for _, method in { "token", "oauth" } do
      				for _, access in { "read", "write" } do
      					local config = {}
      					local input = { token = "figd_fixture" }
      					local header, value = "X-Figma-Token", "figd_fixture"
      					if method == "oauth" then
      						config["client_id"], config["client_secret"], input =
      							"fixture-client", "fixture-secret", nil
      					end
      					local r, err = m.resolve(nil, config, input, method, { data = access })
      					assert(not err, tostring(err))
      					if method == "oauth" then
      						local scopes = readScopes
      						if access == "write" then
      							scopes = m.concat(table.clone(readScopes), { "file_comments:write" })
      						end
      						if not (m.equal(r.Scopes, scopes)) then
      							m.fail("access=%s scopes %s", access, r.Scopes)
      						end
      						header, value = "Authorization", "Bearer figu_fixture"
      						r.Context.Auth["oauth"].access_token = "figu_fixture"
      					end
      					for _, entry in entries do
      						assertFigmaRoutes(
      							r,
      							header,
      							value,
      							(not entry.access or (access == "write")),
      							entry.method .. " " .. api .. (string.gsub(entry.path, "{([%w_]+)}", ids))
      						)
      					end
      					assertFigmaRoutes(
      						r,
      						"Authorization",
      						"",
      						true,
      						"GET https://figma-alpha-api.s3.us-west-2.amazonaws.com/images/u1"
      					)
      					assertFigmaRoutes(
      						r,
      						header,
      						value,
      						false,
      						"GET " .. api .. "/v1/files/" .. key .. "/variables/local",
      						"POST " .. api .. "/v1/files/" .. key .. "/variables",
      						"POST " .. api .. "/v1/files/" .. key .. "/duplicate",
      						"GET " .. api .. "/v1/files/" .. key .. "/dev_resources",
      						"POST " .. api .. "/v1/dev_resources",
      						"GET " .. api .. "/v2/webhooks",
      						"POST " .. api .. "/v2/webhooks",
      						"GET " .. api .. "/v2/webhooks/1/requests",
      						"POST " .. api .. "/v1/teams/123/invites",
      						"GET " .. api .. "/v1/activity_logs",
      						"GET " .. api .. "/v1/payments",
      						"POST " .. api .. "/v1/oauth/token",
      						"POST " .. api .. "/v1/oauth/refresh",
      						"PUT " .. api .. "/v1/files/" .. key .. "/comments",
      						"POST " .. api .. "/v1/files/" .. key .. "/comments/7",
      						"GET " .. api .. "/v1/files/%2e%2e/comments",
      						"GET https://www.figma.com/api/v1/me",
      						"GET https://api.figma.com.example.com/v1/me",
      						"GET https://figma-alpha-api.s3.us-west-2.amazonaws.com/other/u1",
      						"PUT https://figma-alpha-api.s3.us-west-2.amazonaws.com/images/u1",
      						"GET https://s3-alpha-sig.figma.com/img/a/b/c"
      					)
      				end
      			end
      		end
      	end,
      }
      
    • oauth_read_only.luau
      return {
      	scenario = {publisher = {}, access = {data = "read"}, config = {client_id = "fixture-client", client_secret = "fixture-secret"},
      		auth_method = "oauth", auth_config = {}},
      	configure = function()
      		requests = {}
      		http = {request = function(req)
      			table.insert(requests, req)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader('{"name":"Design","projects":[]}')})
      		end}
      	end,
      	run = function(figma)
      		for _, name in {"postComment", "deleteComment", "addCommentReaction", "removeCommentReaction"} do
      			assert(figma[name] == nil, "read-only leaked " .. name)
      		end
      		local projects = figma.listTeamProjects({team_id = "1234567890"})
      		assert(#requests == 1 and requests[1].method == "GET" and requests[1].url == "https://api.figma.com/v1/teams/1234567890/projects")
      		assert(requests[1].headers.Authorization == nil and json.encode(projects.projects) == "[]")
      	end,
      }
      
    • read_only.luau
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "token", auth_config = {token = "figd_fixture"}},
      	configure = function()
      		requests = {}
      		payload = "{}"
      		http = {request = function(req)
      			table.insert(requests, req)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(figma)
      		local API = "https://api.figma.com"
      		local KEY = "aBcDeFgHiJkLmNoPqRsTuV12"
      		local NULL = json.decode("null")
      		local function last() return requests[#requests] end
      		local function rejected(fn, expected)
      			local before = #requests
      			local ok, err = pcall(fn)
      			assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err))
      			assert(#requests == before, "invalid input reached Figma")
      		end
      
      		local names = {}
      		for name in figma do table.insert(names, name) end
      		table.sort(names)
      		assert(table.concat(names, ",") == "getComponent,getComponentSet,getFile,getFileMeta,getFileNodes,getImageFills,getMe,getStyle,listCommentReactions,listComments,listFileComponentSets,listFileComponents,listFileStyles,listFileVersions,listProjectFiles,listTeamComponentSets,listTeamComponents,listTeamProjects,listTeamStyles,renderImages",
      			"wrong read-only surface: " .. table.concat(names, ","))
      		assert(#requests == 0, "initialization reached Figma")
      
      		payload = '{"id":"1234567890123456789","handle":"Ada","email":"[email protected]","img_url":"https://s3-alpha.figma.com/profile/x"}'
      		local me = figma.getMe()
      		assert(last().method == "GET" and last().url == API .. "/v1/me" and last().body == nil)
      		assert(last().headers.Accept[1] == "application/json" and last().headers.Authorization == nil and last().headers["X-Figma-Token"] == nil)
      		assert(me.id == "1234567890123456789" and me.email == "[email protected]")
      
      		payload = '{"name":"App","document":{"id":"0:0","children":[{"id":"0:1","type":"CANVAS","children":[]}]},"components":{},"styles":{}}'
      		local file = figma.getFile({file_key = KEY, depth = 2, branch_data = true})
      		assert(last().url == API .. "/v1/files/" .. KEY .. "?depth=2&branch_data=true", last().url)
      		assert(file.document.children[1].type == "CANVAS" and json.encode(file.document.children[1].children) == "[]")
      
      		-- Links work as file keys, branch links name the branch, and URL node ids use dashes.
      		for _, link in {"https://www.figma.com/design/" .. KEY .. "/App?node-id=1-2&m=dev", "https://figma.com/file/" .. KEY, KEY} do
      			figma.getFileMeta({file_key = link})
      			assert(last().url == API .. "/v1/files/" .. KEY .. "/meta", last().url)
      		end
      		figma.getFileMeta({file_key = "https://www.figma.com/design/" .. KEY .. "/branch/BrAnChKeY123/App"})
      		assert(last().url == API .. "/v1/files/BrAnChKeY123/meta", last().url)
      
      		payload = '{"nodes":{"1:2":{"document":{"id":"1:2"}},"9:9":null}}'
      		local nodes = figma.getFileNodes({file_key = KEY, ids = {"1-2", "I1:2;3:4", "9:9"}, depth = 1})
      		assert(last().url == API .. "/v1/files/" .. KEY .. "/nodes?ids=1%3A2,I1%3A2%3B3%3A4,9%3A9&depth=1", last().url)
      		assert(nodes.nodes["1:2"].document.id == "1:2" and nodes.nodes["9:9"] == NULL)
      		figma.getFileNodes({file_key = KEY, ids = " 1:2, 3-4 "})
      		assert(last().url == API .. "/v1/files/" .. KEY .. "/nodes?ids=1%3A2,3%3A4", last().url)
      		figma.getFileNodes({file_key = "www.figma.com/design/" .. KEY .. "/App", ids = {"12%3A34", "I1-2%3B3-4"}})
      		assert(last().url == API .. "/v1/files/" .. KEY .. "/nodes?ids=12%3A34,I1%3A2%3B3%3A4", last().url)
      		figma.getFileMeta({file_key = "http://figma.com/file/" .. KEY})
      		assert(last().url == API .. "/v1/files/" .. KEY .. "/meta", last().url)
      
      		payload = '{"err":null,"images":{"1:2":"https://figma-alpha-api.s3.us-west-2.amazonaws.com/images/u1","1:3":null}}'
      		local rendered = figma.renderImages({file_key = KEY, ids = {"1:2", "1:3"}, format = "svg", scale = 2, svg_include_id = true})
      		assert(last().url == API .. "/v1/images/" .. KEY .. "?ids=1%3A2,1%3A3&scale=2&format=svg&svg_include_id=true", last().url)
      		assert(rendered.images["1:3"] == NULL and #requests == 11, "renders are not downloaded without save_to")
      
      		payload = '{"versions":[],"pagination":{}}'
      		assert(json.encode(figma.listFileVersions({file_key = KEY, page_size = 50, before = 123}).versions) == "[]")
      		assert(last().url == API .. "/v1/files/" .. KEY .. "/versions?page_size=50&before=123")
      		payload = '{"meta":{"components":[{"key":"abc123","node_id":"1:2"}],"cursor":{"after":30}}}'
      		local components = figma.listTeamComponents({team_id = "1234567890", page_size = 30, after = 0})
      		assert(last().url == API .. "/v1/teams/1234567890/components?page_size=30&after=0")
      		assert(components.meta.cursor.after == 30 and components.meta.components[1].key == "abc123")
      		payload = '{"comments":[{"id":"7","message":"**Hi**","parent_id":"","reactions":[]}]}'
      		local comments = figma.listComments({file_key = KEY, as_md = true})
      		assert(last().url == API .. "/v1/files/" .. KEY .. "/comments?as_md=true")
      		assert(comments.comments[1].message == "**Hi**" and json.encode(comments.comments[1].reactions) == "[]")
      		payload = '{"comments":[]}'
      		assert(json.encode(figma.listComments({file_key = KEY}).comments) == "[]")
      
      		for _, case in {
      			{function() figma.getImageFills({file_key = KEY}) end, "/v1/files/" .. KEY .. "/images"},
      			{function() figma.listTeamProjects({team_id = "42"}) end, "/v1/teams/42/projects"},
      			{function() figma.listProjectFiles({project_id = "77", branch_data = true}) end, "/v1/projects/77/files?branch_data=true"},
      			{function() figma.listTeamComponentSets({team_id = "42"}) end, "/v1/teams/42/component_sets"},
      			{function() figma.listTeamStyles({team_id = "42", before = 10}) end, "/v1/teams/42/styles?before=10"},
      			{function() figma.listFileComponents({file_key = KEY}) end, "/v1/files/" .. KEY .. "/components"},
      			{function() figma.listFileComponentSets({file_key = KEY}) end, "/v1/files/" .. KEY .. "/component_sets"},
      			{function() figma.listFileStyles({file_key = KEY}) end, "/v1/files/" .. KEY .. "/styles"},
      			{function() figma.getComponent({key = "abc123"}) end, "/v1/components/abc123"},
      			{function() figma.getComponentSet({key = "def456"}) end, "/v1/component_sets/def456"},
      			{function() figma.getStyle({key = "0f0f"}) end, "/v1/styles/0f0f"},
      			{function() figma.listCommentReactions({file_key = KEY, comment_id = "7", cursor = "c2"}) end, "/v1/files/" .. KEY .. "/comments/7/reactions?cursor=c2"},
      			{function() figma.listCommentReactions({file_key = KEY, comment_id = "7", cursor = "https://api.figma.com/v1/files/" .. KEY .. "/comments/7/reactions?cursor=YWJj%3D%3D"}) end, "/v1/files/" .. KEY .. "/comments/7/reactions?cursor=YWJj%3D%3D"},
      		} do
      			case[1]()
      			assert(last().method == "GET" and last().url == API .. case[2], last().url)
      		end
      		assert(#requests == 28)
      
      		rejected(function() figma.getFile() end, "file_key must be a Figma file key or URL")
      		rejected(function() figma.getFile({file_key = "../v1/me"}) end, "file_key must be a Figma file key or URL")
      		rejected(function() figma.getFile({file_key = "https://evil.example/design/" .. KEY}) end, "file_key must be a Figma file key or URL")
      		rejected(function() figma.getFile({file_key = "https://www.figma.com.evil.example/design/" .. KEY}) end, "file_key must be a Figma file key or URL")
      		rejected(function() figma.getFile({file_key = "https://www.figma.com/"}) end, "file_key must be a Figma file key or URL")
      		rejected(function() figma.getFile({file_key = "https://www.figma.com/files/123/team/456/Design"}) end, "file_key must be a Figma file key or URL")
      		rejected(function() figma.getFile({file_key = "https://www.figma.com/community/file/123/Kit"}) end, "file_key must be a Figma file key or URL")
      		rejected(function() figma.getFile({file_key = KEY, save_to = "out"}) end, "getFile has no option save_to")
      		rejected(function() figma.listCommentReactions({file_key = KEY, comment_id = "7", cursor = "https://api.figma.com/v1/files/x/comments/7/reactions?page=2"}) end, "cursor must be a cursor or pagination.next_page")
      		rejected(function() figma.listTeamProjects({team_id = 42}) end, "team_id must be a numeric id string")
      		rejected(function() figma.listTeamProjects({team_id = "42/../1"}) end, "team_id must be a numeric id string")
      		rejected(function() figma.getComponent({key = "node 1:2"}) end, "key must be a Figma key")
      		rejected(function() figma.getFileNodes({file_key = KEY}) end, "ids is required")
      		rejected(function() figma.getFileNodes({file_key = KEY, ids = json.decode("[]")}) end, "ids must name at least one node")
      		rejected(function() figma.getFileNodes({file_key = KEY, ids = {"1:2&x=y"}}) end, "ids must be node ids such as 1:2")
      		rejected(function() figma.getFileNodes({file_key = KEY, ids = {a = "1:2"}}) end, "ids must be a list")
      		rejected(function() figma.renderImages({file_key = KEY, ids = {"1:2"}, save_to = "out", format = "gif"}) end, "format must be png, jpg, svg or pdf")
      		rejected(function() figma.getFile({file_key = KEY, deep = 1}) end, "getFile has no option deep")
      		rejected(function() figma.getFile("key") end, "opts must be an object")
      		rejected(function() figma.listCommentReactions({file_key = KEY, comment_id = "7", cursor = {"a", "b"}}) end, "cursor must be one value")
      	end,
      }
      
    • renders.luau
      return {
      	scenario = {publisher = {}, config = {}, auth_method = "token", auth_config = {token = "figd_fixture"}},
      	configure = function()
      		requests = {}
      		responses = {}
      		fs = fixture.files()
      		http = {request = function(req)
      			table.insert(requests, req)
      			local next = table.remove(responses, 1)
      			return fixture.operation({statusCode = next.statusCode, headers = {}, body = fixture.reader(next.body)})
      		end}
      	end,
      	run = function(figma)
      		local KEY = "aBcDeFgHiJkLmNoPqRsTuV12"
      		local BUCKET = "https://figma-alpha-api.s3.us-west-2.amazonaws.com/images/"
      		local NULL = json.decode("null")
      		local function respond(statusCode, body) table.insert(responses, {statusCode = statusCode, body = body}) end
      		local function contents(path)
      			local file = fs.open(path, "r")
      			local chunk = await(file:read(1024 * 1024))
      			await(file:close())
      			return if chunk.done then "" else chunk.data
      		end
      
      		respond(200, '{"err":null,"images":{"1:2":"' .. BUCKET .. 'u1","I3:4;5:6":"' .. BUCKET .. 'u2","7:8":null}}')
      		respond(200, "png-one")
      		respond(200, "png-two")
      		local saved = figma.renderImages({file_key = KEY, ids = {"1:2", "I3:4;5:6", "7:8"}, scale = 2, save_to = "renders/"})
      		assert(#requests == 3 and requests[1].url == "https://api.figma.com/v1/images/" .. KEY .. "?ids=1%3A2,I3%3A4%3B5%3A6,7%3A8&scale=2", requests[1].url)
      		-- Downloads go to the render bucket in sorted id order, without credentials.
      		assert(requests[2].method == "GET" and requests[2].url == BUCKET .. "u1" and requests[2].headers == nil)
      		assert(requests[3].url == BUCKET .. "u2")
      		local one, two = saved.images["1:2"], saved.images["I3:4;5:6"]
      		assert(one.path == "renders/1-2.png" and one.size == 7 and type(one.url) == "string" and contents("renders/1-2.png") == "png-one")
      		assert(two.path == "renders/I3-4_5-6.png" and contents(two.path) == "png-two")
      		assert(saved.images["7:8"] == NULL and saved.err == NULL)
      
      		respond(200, '{"err":null,"images":{"1:2":"https://evil.example/images/u1"}}')
      		local ok, err = pcall(function() figma.renderImages({file_key = KEY, ids = "1:2", format = "jpg", save_to = "renders"}) end)
      		assert(not ok and string.find(tostring(err), "unexpected host", 1, true) and #requests == 4, tostring(err))
      
      		respond(200, '{"err":null,"images":{"1:2":"' .. BUCKET .. 'gone"}}')
      		respond(403, "<Error>AccessDenied</Error>")
      		ok, err = pcall(function() figma.renderImages({file_key = KEY, ids = "1:2", format = "jpg", save_to = "renders"}) end)
      		assert(not ok and string.find(tostring(err), "Downloading the render of 1:2 failed with HTTP 403", 1, true)
      			and string.find(tostring(err), '"retryable":true', 1, true), tostring(err))
      
      		respond(400, '{"status":400,"err":"Invalid parameter: scale"}')
      		ok, err = pcall(function() figma.renderImages({file_key = KEY, ids = "1:2", scale = 9, save_to = "renders"}) end)
      		assert(not ok and string.find(tostring(err), "Figma HTTP 400: Invalid parameter: scale", 1, true), tostring(err))
      		respond(200, '{"err":"Render timeout","images":null}')
      		ok, err = pcall(function() figma.renderImages({file_key = KEY, ids = "1:2", save_to = "renders"}) end)
      		assert(not ok and string.find(tostring(err), "Figma rendered no images: Render timeout", 1, true), tostring(err))
      		assert(#requests == 8)
      
      		respond(200, '{"err":null,"images":{"2:1":"' .. BUCKET .. 'a","2:2":"' .. BUCKET .. 'b"}}')
      		respond(200, "first")
      		respond(403, "<Error>AccessDenied</Error>")
      		ok, err = pcall(function() figma.renderImages({file_key = KEY, ids = {"2:1", "2:2"}, save_to = "batch"}) end)
      		assert(not ok and string.find(tostring(err), "render of 2:2 failed with HTTP 403", 1, true), tostring(err))
      		assert(not await(fs.exists("batch/2-1.png")) and not await(fs.exists("batch/2-2.png")), "a failed batch saves nothing")
      		respond(200, '{"err":null,"images":{"3:1":null}}')
      		local none = figma.renderImages({file_key = KEY, ids = "3:1", save_to = "batch"})
      		assert(none.images["3:1"] == NULL, "nothing to download")
      		assert(#requests == 12)
      		local many = {}
      		for index = 1, 11 do many[index] = "1:" .. index end
      		ok, err = pcall(function() figma.renderImages({file_key = KEY, ids = many, save_to = "renders"}) end)
      		assert(not ok and string.find(tostring(err), "save_to saves at most 10 ids", 1, true) and #requests == 12, tostring(err))
      		ok, err = pcall(function() figma.renderImages({file_key = KEY, ids = "1:2", save_to = ""}) end)
      		assert(not ok and string.find(tostring(err), "save_to must be a session folder path", 1, true) and #requests == 12, tostring(err))
      		ok, err = pcall(function() figma.renderImages({file_key = KEY, ids = "1:2", save_to = "//"}) end)
      		assert(not ok and string.find(tostring(err), "save_to must be a session folder path", 1, true) and #requests == 12, tostring(err))
      	end,
      }
      
    • writes.luau
      return {
      	scenario = {publisher = {}, access = {data = "write"}, config = {client_id = "fixture-client", client_secret = "fixture-secret"},
      		auth_method = "oauth", auth_config = {}},
      	configure = function()
      		requests = {}
      		payload = "{}"
      		http = {request = function(req)
      			table.insert(requests, req)
      			return fixture.operation({statusCode = 200, headers = {}, body = fixture.reader(payload)})
      		end}
      	end,
      	run = function(figma)
      		local API = "https://api.figma.com"
      		local KEY = "aBcDeFgHiJkLmNoPqRsTuV12"
      		local function last() return requests[#requests] end
      		local function rejected(fn, expected)
      			local before = #requests
      			local ok, err = pcall(fn)
      			assert(not ok and string.find(tostring(err), expected, 1, true), "wrong validation error: " .. tostring(err))
      			assert(#requests == before, "invalid input reached Figma")
      		end
      
      		local count = 0
      		for _ in figma do count += 1 end
      		assert(count == 24, "wrong read-write surface: " .. count)
      		for _, name in {"postComment", "deleteComment", "addCommentReaction", "removeCommentReaction"} do
      			assert(type(figma[name]) == "function", "missing " .. name)
      		end
      
      		payload = '{"id":"8","message":"Looks good","parent_id":"7","client_meta":null}'
      		local link = "https://www.figma.com/design/" .. KEY .. "/App"
      		local opts = {file_key = link, message = "Looks good", comment_id = "7"}
      		local reply = figma.postComment(opts)
      		assert(last().method == "POST" and last().url == API .. "/v1/files/" .. KEY .. "/comments")
      		assert(last().headers["Content-Type"][1] == "application/json" and last().headers.Authorization == nil and last().headers["X-Figma-Token"] == nil)
      		local body = json.decode(last().body)
      		assert(body.message == "Looks good" and body.comment_id == "7" and body.file_key == nil)
      		assert(reply.parent_id == "7" and opts.file_key == link, "caller options were modified")
      
      		figma.postComment({file_key = KEY, message = "Pinned", client_meta = {node_id = "1-2", node_offset = {x = 10, y = 20}}})
      		body = json.decode(last().body)
      		assert(body.client_meta.node_id == "1:2" and body.client_meta.node_offset.y == 20)
      
      		payload = ""
      		assert(figma.deleteComment({file_key = KEY, comment_id = "8"}).success == true)
      		assert(last().method == "DELETE" and last().url == API .. "/v1/files/" .. KEY .. "/comments/8" and last().body == nil)
      		payload = '{"status":200,"error":false}'
      		figma.addCommentReaction({file_key = KEY, comment_id = "7", emoji = ":+1:"})
      		assert(last().method == "POST" and last().url == API .. "/v1/files/" .. KEY .. "/comments/7/reactions" and last().body == '{"emoji":":+1:"}')
      		figma.removeCommentReaction({file_key = KEY, comment_id = "7", emoji = ":+1:"})
      		assert(last().method == "DELETE" and last().url == API .. "/v1/files/" .. KEY .. "/comments/7/reactions?emoji=%3A%2B1%3A" and last().body == nil, last().url)
      		figma.getMe()
      		assert(last().method == "GET" and last().url == API .. "/v1/me")
      		assert(#requests == 6)
      
      		rejected(function() figma.postComment({file_key = KEY}) end, "message is required")
      		rejected(function() figma.addCommentReaction({file_key = KEY, comment_id = "7"}) end, "emoji is required")
      		rejected(function() figma.removeCommentReaction({file_key = KEY, comment_id = "7"}) end, "emoji is required")
      		rejected(function() figma.deleteComment({file_key = KEY, comment_id = "abc"}) end, "comment_id must be a numeric id string")
      	end,
      }