@payloadcms/figma 0.1.0-internal.fbdc0d3 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/dist/content-api/auth.d.ts +34 -0
  2. package/dist/content-api/auth.js +70 -0
  3. package/dist/content-api/awaitWithSignal.d.ts +2 -0
  4. package/dist/content-api/awaitWithSignal.js +27 -0
  5. package/dist/content-api/createContentApiClient.d.ts +18 -0
  6. package/dist/content-api/createContentApiClient.js +90 -0
  7. package/dist/content-api/withRateLimitRetries.d.ts +7 -0
  8. package/dist/content-api/withRateLimitRetries.js +45 -0
  9. package/dist/db-content-api/index.d.ts +5 -5
  10. package/dist/db-content-api/index.js +6 -13
  11. package/dist/oauth/components/FigmaAvatar/index.js +3 -2
  12. package/dist/oauth/components/FigmaAvatarCell/index.js +3 -1
  13. package/dist/oauth/components/LoginButton/index.js +8 -4
  14. package/dist/oauth/components/LogoutButton/index.js +3 -2
  15. package/dist/oauth/endpoints/getLoginEndpoint.js +2 -5
  16. package/dist/oauth/index.js +2 -2
  17. package/dist/oauth/utilities/resolvePayloadRedirect.d.ts +13 -0
  18. package/dist/oauth/utilities/resolvePayloadRedirect.js +30 -0
  19. package/dist/plugin/build-config.js +6 -6
  20. package/dist/plugin/cloud-limits/CloudLimitModal/index.js +1 -1
  21. package/dist/plugin/cloud-limits/shared.d.ts +5 -1
  22. package/dist/plugin/cloud-limits/utilities/toasts.d.ts +2 -1
  23. package/dist/translations/ar.d.ts +9 -0
  24. package/dist/translations/ar.js +10 -1
  25. package/dist/translations/az.d.ts +9 -0
  26. package/dist/translations/az.js +10 -1
  27. package/dist/translations/bg.d.ts +9 -0
  28. package/dist/translations/bg.js +10 -1
  29. package/dist/translations/bnBd.d.ts +9 -0
  30. package/dist/translations/bnBd.js +10 -1
  31. package/dist/translations/bnIn.d.ts +9 -0
  32. package/dist/translations/bnIn.js +10 -1
  33. package/dist/translations/ca.d.ts +9 -0
  34. package/dist/translations/ca.js +10 -1
  35. package/dist/translations/cs.d.ts +9 -0
  36. package/dist/translations/cs.js +10 -1
  37. package/dist/translations/da.d.ts +9 -0
  38. package/dist/translations/da.js +10 -1
  39. package/dist/translations/de.d.ts +9 -0
  40. package/dist/translations/de.js +10 -1
  41. package/dist/translations/en.d.ts +9 -0
  42. package/dist/translations/en.js +10 -1
  43. package/dist/translations/es.d.ts +9 -0
  44. package/dist/translations/es.js +15 -6
  45. package/dist/translations/et.d.ts +9 -0
  46. package/dist/translations/et.js +10 -1
  47. package/dist/translations/fa.d.ts +9 -0
  48. package/dist/translations/fa.js +10 -1
  49. package/dist/translations/fr.d.ts +9 -0
  50. package/dist/translations/fr.js +10 -1
  51. package/dist/translations/he.d.ts +9 -0
  52. package/dist/translations/he.js +10 -1
  53. package/dist/translations/hr.d.ts +9 -0
  54. package/dist/translations/hr.js +10 -1
  55. package/dist/translations/hu.d.ts +9 -0
  56. package/dist/translations/hu.js +10 -1
  57. package/dist/translations/hy.d.ts +9 -0
  58. package/dist/translations/hy.js +10 -1
  59. package/dist/translations/id.d.ts +9 -0
  60. package/dist/translations/id.js +10 -1
  61. package/dist/translations/index.d.ts +400 -3
  62. package/dist/translations/is.d.ts +9 -0
  63. package/dist/translations/is.js +10 -1
  64. package/dist/translations/it.d.ts +9 -0
  65. package/dist/translations/it.js +10 -1
  66. package/dist/translations/ja.d.ts +9 -0
  67. package/dist/translations/ja.js +14 -5
  68. package/dist/translations/ko.d.ts +9 -0
  69. package/dist/translations/ko.js +16 -7
  70. package/dist/translations/lt.d.ts +9 -0
  71. package/dist/translations/lt.js +10 -1
  72. package/dist/translations/lv.d.ts +9 -0
  73. package/dist/translations/lv.js +10 -1
  74. package/dist/translations/my.d.ts +9 -0
  75. package/dist/translations/my.js +10 -1
  76. package/dist/translations/nb.d.ts +9 -0
  77. package/dist/translations/nb.js +10 -1
  78. package/dist/translations/nl.d.ts +9 -0
  79. package/dist/translations/nl.js +10 -1
  80. package/dist/translations/pl.d.ts +9 -0
  81. package/dist/translations/pl.js +10 -1
  82. package/dist/translations/pt.d.ts +9 -0
  83. package/dist/translations/pt.js +15 -6
  84. package/dist/translations/ro.d.ts +9 -0
  85. package/dist/translations/ro.js +10 -1
  86. package/dist/translations/rs.d.ts +9 -0
  87. package/dist/translations/rs.js +10 -1
  88. package/dist/translations/rsLatin.d.ts +9 -0
  89. package/dist/translations/rsLatin.js +10 -1
  90. package/dist/translations/ru.d.ts +9 -0
  91. package/dist/translations/ru.js +10 -1
  92. package/dist/translations/sk.d.ts +9 -0
  93. package/dist/translations/sk.js +10 -1
  94. package/dist/translations/sl.d.ts +9 -0
  95. package/dist/translations/sl.js +10 -1
  96. package/dist/translations/sv.d.ts +9 -0
  97. package/dist/translations/sv.js +10 -1
  98. package/dist/translations/ta.d.ts +9 -0
  99. package/dist/translations/ta.js +10 -1
  100. package/dist/translations/th.d.ts +9 -0
  101. package/dist/translations/th.js +10 -1
  102. package/dist/translations/tr.d.ts +9 -0
  103. package/dist/translations/tr.js +10 -1
  104. package/dist/translations/uk.d.ts +9 -0
  105. package/dist/translations/uk.js +10 -1
  106. package/dist/translations/vi.d.ts +9 -0
  107. package/dist/translations/vi.js +10 -1
  108. package/dist/translations/zh.d.ts +9 -0
  109. package/dist/translations/zh.js +10 -1
  110. package/dist/translations/zhTw.d.ts +9 -0
  111. package/dist/translations/zhTw.js +10 -1
  112. package/package.json +13 -13
@@ -0,0 +1,34 @@
1
+ import type { TokenStore } from '../auth/token-store.js';
2
+ import type { ProjectStoreScope } from '../auth/types.js';
3
+ export type ContentApiAuth = {
4
+ apiKey: string;
5
+ mode: 'apiKey';
6
+ } | {
7
+ mode: 'devJwt';
8
+ } | {
9
+ mode: 'tokenStore';
10
+ projectInfo?: ProjectStoreScope;
11
+ tokenStore: TokenStore;
12
+ };
13
+ export type ContentApiLogger = {
14
+ error?: (details: {
15
+ msg: string;
16
+ status: number;
17
+ statusText: string;
18
+ }) => void;
19
+ info?: (message: string) => void;
20
+ warn: (message: string) => void;
21
+ };
22
+ export declare function invalidateDevJwt(baseUrl: string, contentSystemId: string): void;
23
+ export declare function getDevJwt({ baseUrl, contentSystemId, logger, signal, }: {
24
+ baseUrl: string;
25
+ contentSystemId: string;
26
+ logger: ContentApiLogger;
27
+ signal: AbortSignal;
28
+ }): Promise<string>;
29
+ export declare function applyContentApiAuth(request: Request, options: {
30
+ auth: ContentApiAuth;
31
+ baseUrl: string;
32
+ contentSystemId: string;
33
+ logger: ContentApiLogger;
34
+ }): Promise<void>;
@@ -0,0 +1,70 @@
1
+ import { getValidProjectToken } from '../auth/project-token.js';
2
+ import { awaitWithSignal } from './awaitWithSignal.js';
3
+ import { withRateLimitRetries } from './withRateLimitRetries.js';
4
+ const devJwtCache = new Map();
5
+ function devJwtCacheKey(baseUrl, contentSystemId) {
6
+ return `${baseUrl}::${contentSystemId}`;
7
+ }
8
+ export function invalidateDevJwt(baseUrl, contentSystemId) {
9
+ devJwtCache.delete(devJwtCacheKey(baseUrl, contentSystemId));
10
+ }
11
+ export async function getDevJwt({ baseUrl, contentSystemId, logger, signal }) {
12
+ signal.throwIfAborted();
13
+ const cacheKey = devJwtCacheKey(baseUrl, contentSystemId);
14
+ const cached = devJwtCache.get(cacheKey);
15
+ if (cached) {
16
+ return cached;
17
+ }
18
+ const usesSuperUser = !contentSystemId || contentSystemId === 'test-system' || contentSystemId === '*';
19
+ const fetchWithRetries = withRateLimitRetries({
20
+ fetchImplementation: fetch,
21
+ warn: (message)=>logger.warn(message)
22
+ });
23
+ const response = await fetchWithRetries(new URL('/dev/jwt', baseUrl), {
24
+ body: JSON.stringify({
25
+ content_system_id: usesSuperUser ? '*' : contentSystemId
26
+ }),
27
+ headers: {
28
+ 'Content-Type': 'application/json'
29
+ },
30
+ method: 'POST',
31
+ signal
32
+ });
33
+ if (!response.ok) {
34
+ throw new Error(`Failed to get dev JWT: ${response.status} ${response.statusText}`);
35
+ }
36
+ const { token } = await awaitWithSignal(response.json(), signal);
37
+ signal.throwIfAborted();
38
+ devJwtCache.set(cacheKey, token);
39
+ logger.info?.(`Dev JWT acquired for content system: ${contentSystemId}`);
40
+ return token;
41
+ }
42
+ export async function applyContentApiAuth(request, options) {
43
+ const { auth, baseUrl, contentSystemId, logger } = options;
44
+ request.signal.throwIfAborted();
45
+ if (auth.mode === 'apiKey') {
46
+ request.headers.set('X-Api-Key', auth.apiKey);
47
+ return;
48
+ }
49
+ if (auth.mode === 'tokenStore') {
50
+ const token = await awaitWithSignal(getValidProjectToken({
51
+ ...auth.projectInfo ? {
52
+ projectInfo: auth.projectInfo
53
+ } : {},
54
+ tenantId: contentSystemId,
55
+ tokenStore: auth.tokenStore
56
+ }), request.signal);
57
+ request.signal.throwIfAborted();
58
+ if (!token) {
59
+ throw new Error('Authentication required. Run `npx @payloadcms/figma login` to authenticate.');
60
+ }
61
+ request.headers.set('Authorization', `Bearer ${token}`);
62
+ return;
63
+ }
64
+ request.headers.set('Authorization', `Bearer ${await getDevJwt({
65
+ baseUrl,
66
+ contentSystemId,
67
+ logger,
68
+ signal: request.signal
69
+ })}`);
70
+ }
@@ -0,0 +1,2 @@
1
+ /** Stop this caller's wait without cancelling a promise shared with other callers. */
2
+ export declare function awaitWithSignal<T>(promise: Promise<T>, signal: AbortSignal): Promise<T>;
@@ -0,0 +1,27 @@
1
+ /** Stop this caller's wait without cancelling a promise shared with other callers. */ export async function awaitWithSignal(promise, signal) {
2
+ let onAbort;
3
+ const cancellation = new Promise((_resolve, reject)=>{
4
+ onAbort = ()=>{
5
+ const reason = signal.reason;
6
+ reject(reason instanceof Error ? reason : new DOMException('The operation was aborted', 'AbortError'));
7
+ };
8
+ if (signal.aborted) {
9
+ onAbort();
10
+ } else {
11
+ signal.addEventListener('abort', onAbort, {
12
+ once: true
13
+ });
14
+ }
15
+ });
16
+ try {
17
+ // Observe the shared promise even if cancellation has already occurred.
18
+ return await Promise.race([
19
+ cancellation,
20
+ promise
21
+ ]);
22
+ } finally{
23
+ if (onAbort) {
24
+ signal.removeEventListener('abort', onAbort);
25
+ }
26
+ }
27
+ }
@@ -0,0 +1,18 @@
1
+ import type { ContentApiAuth, ContentApiLogger } from './auth.js';
2
+ export type ContentApiClientOptions = {
3
+ auth: ContentApiAuth;
4
+ baseUrl: string;
5
+ contentSystemId: string;
6
+ logger: ContentApiLogger;
7
+ /** Optional deadline across authentication and retries, ending when response headers arrive. */
8
+ requestTimeoutMs?: number;
9
+ };
10
+ type RawRequestOptions = {
11
+ unauthenticatedDevEndpoint?: boolean;
12
+ };
13
+ /** The sole request entry point for Content API endpoints in the Payload plugin. */
14
+ export declare function createContentApiClient<Paths extends Record<string, Record<string, unknown>>>(options: ContentApiClientOptions): {
15
+ api: import("openapi-fetch").Client<Paths, `${string}/${string}`>;
16
+ request(path: string, init?: RequestInit, rawOptions?: RawRequestOptions): Promise<Response>;
17
+ };
18
+ export {};
@@ -0,0 +1,90 @@
1
+ import createClient from 'openapi-fetch';
2
+ import { getClientVersionHeaders } from '../db-content-api/utilities/clientVersionHeaders.js';
3
+ import { applyContentApiAuth, getDevJwt, invalidateDevJwt } from './auth.js';
4
+ import { withRateLimitRetries } from './withRateLimitRetries.js';
5
+ /** The sole request entry point for Content API endpoints in the Payload plugin. */ export function createContentApiClient(options) {
6
+ const baseUrl = new URL(options.baseUrl);
7
+ if (options.requestTimeoutMs !== undefined && (!Number.isFinite(options.requestTimeoutMs) || options.requestTimeoutMs <= 0 || options.requestTimeoutMs > 2_147_483_647)) {
8
+ throw new RangeError('requestTimeoutMs must be between 0 (exclusive) and 2147483647 milliseconds');
9
+ }
10
+ const versionHeaders = getClientVersionHeaders();
11
+ const fetchWithRetries = withRateLimitRetries({
12
+ fetchImplementation: fetch,
13
+ warn: (message)=>options.logger.warn(message)
14
+ });
15
+ async function send(input, init, rawOptions) {
16
+ const original = new Request(input, init);
17
+ if (new URL(original.url).origin !== baseUrl.origin) {
18
+ throw new Error('Content API client cannot request a different origin');
19
+ }
20
+ if (rawOptions?.unauthenticatedDevEndpoint && !new URL(original.url).pathname.startsWith('/dev/')) {
21
+ throw new Error('Unauthenticated Content API requests are only allowed for dev endpoints');
22
+ }
23
+ original.signal.throwIfAborted();
24
+ const deadlineController = new AbortController();
25
+ const signal = AbortSignal.any([
26
+ original.signal,
27
+ deadlineController.signal
28
+ ]);
29
+ const timeout = options.requestTimeoutMs === undefined ? undefined : globalThis.setTimeout(()=>deadlineController.abort(new DOMException('Content API request timed out', 'TimeoutError')), options.requestTimeoutMs);
30
+ try {
31
+ const request = new Request(original.clone(), {
32
+ signal
33
+ });
34
+ for (const [name, value] of Object.entries(versionHeaders)){
35
+ request.headers.set(name, value);
36
+ }
37
+ if (!rawOptions?.unauthenticatedDevEndpoint) {
38
+ await applyContentApiAuth(request, options);
39
+ }
40
+ signal.throwIfAborted();
41
+ let response = await fetchWithRetries(request);
42
+ signal.throwIfAborted();
43
+ if (response.status === 401 && options.auth.mode === 'devJwt' && !rawOptions?.unauthenticatedDevEndpoint) {
44
+ options.logger.info?.('Dev JWT expired, refreshing...');
45
+ invalidateDevJwt(options.baseUrl, options.contentSystemId);
46
+ const refreshedToken = await getDevJwt({
47
+ baseUrl: options.baseUrl,
48
+ contentSystemId: options.contentSystemId,
49
+ logger: options.logger,
50
+ signal
51
+ });
52
+ signal.throwIfAborted();
53
+ const retryRequest = new Request(original.clone(), {
54
+ signal
55
+ });
56
+ for (const [name, value] of Object.entries(versionHeaders)){
57
+ retryRequest.headers.set(name, value);
58
+ }
59
+ retryRequest.headers.set('Authorization', `Bearer ${refreshedToken}`);
60
+ response = await fetchWithRetries(retryRequest);
61
+ }
62
+ signal.throwIfAborted();
63
+ if (!response.ok && response.status !== 429) {
64
+ options.logger.error?.({
65
+ msg: `HTTP ${response.status} from ${request.url}`,
66
+ status: response.status,
67
+ statusText: response.statusText
68
+ });
69
+ }
70
+ return response;
71
+ } catch (error) {
72
+ // Node's abortable waits may wrap the original timeout/cancellation reason in AbortError.
73
+ signal.throwIfAborted();
74
+ throw error;
75
+ } finally{
76
+ globalThis.clearTimeout(timeout);
77
+ }
78
+ }
79
+ const api = createClient({
80
+ baseUrl: options.baseUrl,
81
+ fetch: send
82
+ });
83
+ return {
84
+ api,
85
+ request (path, init, rawOptions) {
86
+ const url = new URL(path, baseUrl);
87
+ return send(url, init, rawOptions);
88
+ }
89
+ };
90
+ }
@@ -0,0 +1,7 @@
1
+ interface WithRateLimitRetriesArgs {
2
+ fetchImplementation: typeof fetch;
3
+ warn: (message: string) => void;
4
+ }
5
+ /** The retry budget starts after the first 429; caller aborts and other errors propagate. */
6
+ export declare function withRateLimitRetries({ fetchImplementation, warn, }: WithRateLimitRetriesArgs): typeof fetch;
7
+ export {};
@@ -0,0 +1,45 @@
1
+ import { setTimeout as wait } from 'node:timers/promises';
2
+ const INITIAL_BACKOFF_MS = 200;
3
+ const MAX_RETRY_DURATION_MS = 30_000;
4
+ /** The retry budget starts after the first 429; caller aborts and other errors propagate. */ export function withRateLimitRetries({ fetchImplementation, warn }) {
5
+ return async (input, init)=>{
6
+ const request = input instanceof Request && init == null ? input.clone() : new Request(input, init);
7
+ request.signal.throwIfAborted();
8
+ let response = await fetchImplementation(request.clone());
9
+ if (response.status !== 429) {
10
+ return response;
11
+ }
12
+ const timeoutReason = new DOMException('Rate-limit retry budget exhausted', 'TimeoutError');
13
+ const retryController = new AbortController();
14
+ const signal = AbortSignal.any([
15
+ request.signal,
16
+ retryController.signal
17
+ ]);
18
+ const timeout = globalThis.setTimeout(()=>retryController.abort(timeoutReason), MAX_RETRY_DURATION_MS);
19
+ let attempt = 0;
20
+ try {
21
+ while(response.status === 429){
22
+ signal.throwIfAborted();
23
+ const backoffMs = INITIAL_BACKOFF_MS * 2 ** attempt;
24
+ const delayMs = backoffMs + Math.random() * backoffMs;
25
+ warn(`HTTP 429 from ${request.url}; retrying in ${Math.round(delayMs)}ms`);
26
+ await wait(delayMs, undefined, {
27
+ signal
28
+ });
29
+ signal.throwIfAborted();
30
+ // Only the caller can abort an in-flight request: a retry may have already written data.
31
+ response = await fetchImplementation(request.clone());
32
+ attempt += 1;
33
+ }
34
+ return response;
35
+ } catch (error) {
36
+ const isRetryTimeout = error === timeoutReason || error instanceof Error && error.name === 'AbortError' && error.cause === timeoutReason;
37
+ if (isRetryTimeout && !request.signal.aborted) {
38
+ return response;
39
+ }
40
+ throw error;
41
+ } finally{
42
+ globalThis.clearTimeout(timeout);
43
+ }
44
+ };
45
+ }
@@ -1,11 +1,11 @@
1
1
  import type { BaseDatabaseAdapter, CreateArgs, DatabaseAdapterObj } from 'payload';
2
- import createClient from 'openapi-fetch';
2
+ import type { ContentApiAuth } from '../content-api/auth.js';
3
3
  import type { paths } from './generated/content-api-types.js';
4
- import { type AuthMode } from './utilities/auth.js';
4
+ import { createContentApiClient } from '../content-api/createContentApiClient.js';
5
5
  import { type DocumentSchemaWire } from './utilities/schema/buildDocumentSchema.js';
6
6
  type ContentAPIOptions = {
7
7
  allowIDOnCreate?: boolean;
8
- auth: AuthMode;
8
+ auth: ContentApiAuth;
9
9
  contentSystemId: string;
10
10
  environmentName?: string;
11
11
  notifyLocalJobQueue: boolean;
@@ -24,9 +24,9 @@ export declare const LOCAL_JOB_QUEUE_NOTICE: string;
24
24
  */
25
25
  export declare function maybeNotifyLocalJobQueue(adapter: ContentAPIAdapter, args: CreateArgs): void;
26
26
  export type ContentAPIAdapter = {
27
- auth: AuthMode;
27
+ auth: ContentApiAuth;
28
28
  clearDatabase: () => Promise<void>;
29
- client: ReturnType<typeof createClient<paths>>;
29
+ client: ReturnType<typeof createContentApiClient<paths>>['api'];
30
30
  clientVersionHeaders: Record<string, string>;
31
31
  contentSystemId: string;
32
32
  documentSchema: () => DocumentSchemaWire;
@@ -1,13 +1,12 @@
1
- import createClient from 'openapi-fetch';
2
1
  import { APIError, createDatabaseAdapter, ValidationError } from 'payload';
3
2
  import { v4 as uuid } from 'uuid';
4
3
  import { FigmaApiError } from '../api/figma-api.js';
5
4
  import { CONTENT_SYSTEM_NOT_FOUND_MESSAGE } from '../constants.js';
5
+ import { createContentApiClient } from '../content-api/createContentApiClient.js';
6
6
  import { redirectInitialAutosaveCreate } from '../plugin/cloud-limits/server/redirectInitialAutosaveCreate.js';
7
7
  import { getGlobalSlug } from './temp-utilities/slug.js';
8
8
  import { addFallbackSort } from './temp-utilities/sorting.js';
9
9
  import { unwrapDocument, unwrapFindResponse } from './temp-utilities/unwrapDocument.js';
10
- import { createAuthMiddleware, createErrorMiddleware } from './utilities/auth.js';
11
10
  import { getClientVersionHeaders } from './utilities/clientVersionHeaders.js';
12
11
  import { dataToContentAPI, resolveVersionContent } from './utilities/data/index.js';
13
12
  import { injectGlobalType } from './utilities/data/injectGlobalType.js';
@@ -870,25 +869,19 @@ export const contentAPIAdapter = (opts)=>({
870
869
  defaultIDType: 'text',
871
870
  init: ({ payload })=>{
872
871
  const clientVersionHeaders = getClientVersionHeaders();
873
- const client = createClient({
874
- baseUrl: opts.url,
875
- headers: clientVersionHeaders
876
- });
877
- const middlewareOpts = {
872
+ const contentApi = createContentApiClient({
878
873
  auth: opts.auth,
874
+ baseUrl: opts.url,
879
875
  contentSystemId: opts.contentSystemId,
880
- logger: payload.logger,
881
- url: opts.url
882
- };
883
- client.use(createAuthMiddleware(middlewareOpts));
884
- client.use(createErrorMiddleware(middlewareOpts));
876
+ logger: payload.logger
877
+ });
885
878
  return createDatabaseAdapter({
886
879
  name: 'content-api',
887
880
  allowIDOnCreate: opts.allowIDOnCreate ?? false,
888
881
  auth: opts.auth,
889
882
  beginTransaction: ()=>Promise.resolve(null),
890
883
  clearDatabase: clearDatabase,
891
- client,
884
+ client: contentApi.api,
892
885
  clientVersionHeaders,
893
886
  commitTransaction: async ()=>{},
894
887
  connect: connect,
@@ -1,12 +1,13 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
- import { useAuth } from '@payloadcms/ui';
3
+ import { useAuth, useTranslation } from '@payloadcms/ui';
4
4
  import { useState } from 'react';
5
5
  import { FigmaAvatarPlaceholder, isValidImageUrl } from '../FigmaAvatarPlaceholder/index.js';
6
6
  import './index.scss';
7
7
  const baseClass = 'figma-avatar';
8
8
  export const FigmaAvatar = ()=>{
9
9
  const { user } = useAuth();
10
+ const { t } = useTranslation();
10
11
  const [hasError, setHasError] = useState(false);
11
12
  const figmaImageUrl = user?.figmaImageUrl;
12
13
  if (!figmaImageUrl || hasError || !isValidImageUrl(figmaImageUrl)) {
@@ -15,7 +16,7 @@ export const FigmaAvatar = ()=>{
15
16
  });
16
17
  }
17
18
  return /*#__PURE__*/ _jsx("img", {
18
- alt: "Profile",
19
+ alt: t('figma:profile'),
19
20
  className: `${baseClass}__image`,
20
21
  height: 25,
21
22
  onError: ()=>setHasError(true),
@@ -1,10 +1,12 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
+ import { useTranslation } from '@payloadcms/ui';
3
4
  import { useState } from 'react';
4
5
  import { FigmaAvatarPlaceholder, isValidImageUrl } from '../FigmaAvatarPlaceholder/index.js';
5
6
  import './index.scss';
6
7
  const baseClass = 'figma-avatar-cell';
7
8
  export const FigmaAvatarCell = ({ cellData })=>{
9
+ const { t } = useTranslation();
8
10
  const [hasError, setHasError] = useState(false);
9
11
  const figmaImageUrl = cellData;
10
12
  if (!figmaImageUrl || hasError || !isValidImageUrl(figmaImageUrl)) {
@@ -13,7 +15,7 @@ export const FigmaAvatarCell = ({ cellData })=>{
13
15
  });
14
16
  }
15
17
  return /*#__PURE__*/ _jsx("img", {
16
- alt: "Avatar",
18
+ alt: t('figma:avatar'),
17
19
  className: `${baseClass}__image`,
18
20
  height: 20,
19
21
  onError: ()=>setHasError(true),
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useConfig, useSearchParams } from '@payloadcms/ui';
3
+ import { useConfig, useSearchParams, useTranslation } from '@payloadcms/ui';
4
4
  import React, { useEffect, useState } from 'react';
5
5
  import { getSearchParam } from '../../utils/getSearchParam.js';
6
6
  import { resolveParentTargetOrigin, setupIframeAutoLogin } from './iframeAutoLogin.js';
@@ -60,8 +60,10 @@ const FigmaIcon = ()=>/*#__PURE__*/ _jsx("svg", {
60
60
  fillRule: "evenodd"
61
61
  })
62
62
  });
63
- const PayloadAdminLoadingShimmer = ()=>/*#__PURE__*/ _jsx("div", {
64
- "aria-label": "Signing in",
63
+ const PayloadAdminLoadingShimmer = ()=>{
64
+ const { t } = useTranslation();
65
+ return /*#__PURE__*/ _jsx("div", {
66
+ "aria-label": t('figma:signingIn'),
65
67
  "aria-live": "polite",
66
68
  className: `${baseClass}__admin-shimmer`,
67
69
  role: "status",
@@ -111,8 +113,10 @@ const PayloadAdminLoadingShimmer = ()=>/*#__PURE__*/ _jsx("div", {
111
113
  ]
112
114
  })
113
115
  });
116
+ };
114
117
  export const DefaultLoginButton = ({ disabled, endpointSlug })=>{
115
118
  const { config: { admin: { user: userSlug }, routes: { api }, serverURL } } = useConfig();
119
+ const { t } = useTranslation();
116
120
  const [authorizeURL, setAuthorizeURL] = useState('');
117
121
  const [isInIframe, setIsInIframe] = useState(null);
118
122
  const [autoLoginFailed, setAutoLoginFailed] = useState(false);
@@ -229,7 +233,7 @@ export const DefaultLoginButton = ({ disabled, endpointSlug })=>{
229
233
  /*#__PURE__*/ _jsx(FigmaIcon, {}),
230
234
  /*#__PURE__*/ _jsx("span", {
231
235
  className: `${baseClass}__text`,
232
- children: "Log in with Figma"
236
+ children: t('figma:logInWithFigma')
233
237
  })
234
238
  ]
235
239
  })
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { Logout, useConfig } from '@payloadcms/ui';
3
+ import { Logout, useConfig, useTranslation } from '@payloadcms/ui';
4
4
  import { formatAdminURL } from 'payload/shared';
5
5
  import React from 'react';
6
6
  import './index.scss';
@@ -12,6 +12,7 @@ export const LogoutButton = ({ disabled, endpointSlug })=>{
12
12
  // logout. Redirect to the site root instead so the user actually stays
13
13
  // logged out. Outside an iframe, keep the original behavior of redirecting
14
14
  // back to /admin.
15
+ const { t } = useTranslation();
15
16
  const [redirect, setRedirect] = React.useState('');
16
17
  React.useEffect(()=>{
17
18
  const protocol = window.location.protocol;
@@ -44,7 +45,7 @@ export const LogoutButton = ({ disabled, endpointSlug })=>{
44
45
  return /*#__PURE__*/ _jsx("div", {
45
46
  className: baseClass,
46
47
  children: /*#__PURE__*/ _jsx("a", {
47
- "aria-label": "Logout",
48
+ "aria-label": t('authentication:logout'),
48
49
  href: `${serverURL}${api}/${userSlug}/${endpointSlug}/logout?redirect=${encodeURIComponent(redirect)}`,
49
50
  children: /*#__PURE__*/ _jsxs("svg", {
50
51
  className: "icon icon--logout",
@@ -8,6 +8,7 @@ import { exchangeCodeForAccessToken } from '../utilities/exchangeCodeForAccessTo
8
8
  import { extractOrigin } from '../utilities/extractOrigin.js';
9
9
  import { buildCsrfCookieClearHeader, getOAuthCallbackPath, OAUTH_STATE_CSRF_COOKIE_NAME } from '../utilities/getAuthorizeURL.js';
10
10
  import { isAbsoluteURL } from '../utilities/isAbsoluteURL.js';
11
+ import { resolvePayloadRedirect } from '../utilities/resolvePayloadRedirect.js';
11
12
  export const getLoginEndpoint = ({ collection, collectionOptions, endpointSlug, pluginOptions, strategy })=>({
12
13
  handler: async (req)=>{
13
14
  const { config } = req.payload;
@@ -196,11 +197,7 @@ export const getLoginEndpoint = ({ collection, collectionOptions, endpointSlug,
196
197
  // is single-use; leaving it around lets a replay try again.
197
198
  req.responseHeaders.append('Set-Cookie', buildCsrfCookieClearHeader());
198
199
  if (payloadRedirect) {
199
- if (isAbsoluteURL(payloadRedirect)) {
200
- redirectToUse = payloadRedirect;
201
- } else {
202
- redirectToUse += payloadRedirect;
203
- }
200
+ redirectToUse = resolvePayloadRedirect(payloadRedirect, redirectToUse);
204
201
  req.responseHeaders.append('Set-Cookie', // Match the attributes the cookie was set with so the clear removes it
205
202
  // in the cross-site Make iframe.
206
203
  `payloadRedirect=${redirectToUse}; Max-Age=0; Path=/; Secure; SameSite=None; Partitioned`);
@@ -97,7 +97,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
97
97
  name: 'email',
98
98
  type: 'email',
99
99
  admin: {
100
- description: 'Managed by Figma',
100
+ description: ({ t })=>t('figma:managedByFigma'),
101
101
  readOnly: true
102
102
  },
103
103
  unique: true
@@ -114,7 +114,7 @@ export const oAuth2Plugin = (pluginOptions)=>(config)=>{
114
114
  admin: {
115
115
  ...usernameField.admin || {},
116
116
  ...usernameField.name === 'email' ? {
117
- description: 'Managed by Figma'
117
+ description: ({ t })=>t('figma:managedByFigma')
118
118
  } : {},
119
119
  readOnly: true
120
120
  }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Applies the `payloadRedirect` cookie (Payload's `?redirect=` login param, saved by
3
+ * `LoginButton`) to the post-login redirect URL.
4
+ *
5
+ * Payload sets `?redirect=` to the full admin path, e.g. `/admin/collections/posts`, or to just a
6
+ * query string when login started at the admin root. Appending a path to the admin URL would
7
+ * double the admin route (`/admin/admin/collections/posts`), so paths are resolved from the
8
+ * origin instead. Unsafe values, including absolute URLs, are ignored.
9
+ *
10
+ * @example resolvePayloadRedirect('/admin/collections/posts', 'https://site/admin') // 'https://site/admin/collections/posts'
11
+ * @example resolvePayloadRedirect('?embed=true', 'https://site/admin') // 'https://site/admin?embed=true'
12
+ */
13
+ export declare function resolvePayloadRedirect(payloadRedirect: string, redirectURL: string): string;
@@ -0,0 +1,30 @@
1
+ import { formatAdminURL, getSafeRedirect } from 'payload/shared';
2
+ /**
3
+ * Applies the `payloadRedirect` cookie (Payload's `?redirect=` login param, saved by
4
+ * `LoginButton`) to the post-login redirect URL.
5
+ *
6
+ * Payload sets `?redirect=` to the full admin path, e.g. `/admin/collections/posts`, or to just a
7
+ * query string when login started at the admin root. Appending a path to the admin URL would
8
+ * double the admin route (`/admin/admin/collections/posts`), so paths are resolved from the
9
+ * origin instead. Unsafe values, including absolute URLs, are ignored.
10
+ *
11
+ * @example resolvePayloadRedirect('/admin/collections/posts', 'https://site/admin') // 'https://site/admin/collections/posts'
12
+ * @example resolvePayloadRedirect('?embed=true', 'https://site/admin') // 'https://site/admin?embed=true'
13
+ */ export function resolvePayloadRedirect(payloadRedirect, redirectURL) {
14
+ if (payloadRedirect.startsWith('?')) {
15
+ return redirectURL + payloadRedirect;
16
+ }
17
+ const path = getSafeRedirect({
18
+ fallbackTo: '',
19
+ redirectTo: payloadRedirect
20
+ });
21
+ if (!path) {
22
+ return redirectURL;
23
+ }
24
+ // `adminRoute: '/'` adds no route segment, leaving the origin, any Next.js basePath, and `path`.
25
+ return formatAdminURL({
26
+ adminRoute: '/',
27
+ path: path,
28
+ serverURL: redirectURL
29
+ });
30
+ }
@@ -42,7 +42,7 @@ import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
42
42
  admin: {
43
43
  readOnly: true
44
44
  },
45
- label: 'Name'
45
+ label: ({ t })=>t('general:name')
46
46
  },
47
47
  {
48
48
  name: 'figmaImageUrl',
@@ -57,7 +57,7 @@ import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
57
57
  hidden: true,
58
58
  readOnly: true
59
59
  },
60
- label: 'Profile Picture'
60
+ label: ({ t })=>t('figma:profilePicture')
61
61
  },
62
62
  // Virtual (never persisted): populated per-request from the session JWT. The
63
63
  // afterRead hook surfaces the claim on the requester's OWN user record only —
@@ -79,7 +79,7 @@ import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
79
79
  ({ data, req })=>data?.id !== undefined && req.user?.id === data.id ? req.user.userGroups : undefined
80
80
  ]
81
81
  },
82
- label: 'User Groups',
82
+ label: ({ t })=>t('figma:userGroups'),
83
83
  virtual: true
84
84
  },
85
85
  // KEEP_IN_SYNC(sinatra/controllers/api/api_payload_control_plane.rb) — resolve_make_permission
@@ -97,14 +97,14 @@ import { createSandboxUploadFetchPlugin } from './sandbox-upload-fetch.js';
97
97
  ({ data, req })=>data?.id !== undefined && req.user?.id === data.id ? req.user.makePermission : undefined
98
98
  ]
99
99
  },
100
- label: 'Make Permission',
100
+ label: ({ t })=>t('figma:makePermission'),
101
101
  options: [
102
102
  {
103
- label: 'View',
103
+ label: ({ t })=>t('figma:view'),
104
104
  value: 'view'
105
105
  },
106
106
  {
107
- label: 'Edit',
107
+ label: ({ t })=>t('general:edit'),
108
108
  value: 'edit'
109
109
  }
110
110
  ],
@@ -54,7 +54,7 @@ export function FigmaCloudLimitDocumentCountModal({ collectionLabel, collectionL
54
54
  onRetry();
55
55
  },
56
56
  size: "medium",
57
- children: t('figma:cloudLimitModalRetry')
57
+ children: t('general:retry')
58
58
  })
59
59
  ]
60
60
  })
@@ -7,4 +7,8 @@ export type CloudLimitErrorCode = (typeof cloudLimitErrorCodes)[keyof typeof clo
7
7
  export declare function isCloudLimitErrorCode(code: unknown): code is CloudLimitErrorCode;
8
8
  export declare function getCloudLimitErrorCode(json: unknown): CloudLimitErrorCode | undefined;
9
9
  export declare const cloudLimitDocumentCountModalSlug = "figma-cloud-limit-document-count";
10
- export declare const cloudLimitToastKeyByCode: Record<CloudLimitErrorCode, string>;
10
+ export declare const cloudLimitToastKeyByCode: {
11
+ "cloud_limit.cms_assets_bytes_exceeded": "figma:cloudLimitAssetStorageError";
12
+ "cloud_limit.document_count_exceeded": "figma:cloudLimitDocumentCountError";
13
+ "cloud_limit.per_document_data_bytes_exceeded": "figma:cloudLimitDocumentDataSizeError";
14
+ };
@@ -1,4 +1,5 @@
1
+ import type { FigmaTranslationKeys } from '../../../translations/index.js';
1
2
  import type { CloudLimitErrorCode } from '../shared.js';
2
- export type Translate = (key: string) => string;
3
+ export type Translate = (key: FigmaTranslationKeys) => string;
3
4
  export declare function dismissSubmittingToast(label: string): void;
4
5
  export declare function showCloudLimitToast(code: CloudLimitErrorCode, translate: Translate): void;