twenty-sdk 0.6.0 → 0.6.2

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 (70) hide show
  1. package/README.md +6 -2
  2. package/dist/{HtmlTagToRemoteComponent-DzQ2I9Lz.js → HtmlTagToRemoteComponent-CgtwxDeH.js} +11 -11
  3. package/dist/{HtmlTagToRemoteComponent-DBOkvIRB.mjs → HtmlTagToRemoteComponent-D_EW5OLu.mjs} +1743 -1640
  4. package/dist/cli/utilities/api/api-service.d.ts +4 -0
  5. package/dist/cli/utilities/build/common/esbuild-watcher.d.ts +5 -2
  6. package/dist/cli/utilities/build/common/typecheck-plugin.d.ts +1 -1
  7. package/dist/cli/utilities/build/manifest/manifest-extract-config.d.ts +2 -0
  8. package/dist/cli/utilities/client/client-service.d.ts +5 -1
  9. package/dist/cli/utilities/client/twenty-client-template.d.ts +42 -0
  10. package/dist/cli/utilities/dev/orchestrator/dev-mode-orchestrator.d.ts +2 -0
  11. package/dist/cli/utilities/dev/orchestrator/steps/start-watchers-orchestrator-step.d.ts +2 -0
  12. package/dist/cli.cjs +430 -75
  13. package/dist/cli.mjs +3175 -2725
  14. package/dist/front-component-renderer/index.cjs +11 -11
  15. package/dist/front-component-renderer/index.d.ts +3 -3
  16. package/dist/front-component-renderer/index.mjs +2186 -1906
  17. package/dist/front-component-renderer/remote/generated/remote-components.d.ts +44 -0
  18. package/dist/front-component-renderer/remote/generated/remote-elements.d.ts +93 -0
  19. package/dist/front-component-renderer/types/FrontComponentHostCommunicationApi.d.ts +2 -1
  20. package/dist/{get-function-input-schema-BZ7_XyUh-GxSybvDe.js → get-function-input-schema-BZ7_XyUh-CCSi0u_q.js} +1 -1
  21. package/dist/{get-function-input-schema-BZ7_XyUh-By3UDh4s.mjs → get-function-input-schema-BZ7_XyUh-DAPandzB.mjs} +1 -1
  22. package/dist/index.cjs +2 -2
  23. package/dist/index.mjs +122 -89
  24. package/dist/sdk/application/application-config.d.ts +1 -1
  25. package/dist/sdk/front-component-api/constants/AllowedHtmlElements.d.ts +1 -0
  26. package/dist/sdk/front-component-api/constants/AllowedHtmlElements.js +104 -1
  27. package/dist/sdk/front-component-api/constants/AllowedHtmlElements.js.map +1 -1
  28. package/dist/sdk/front-component-api/constants/EventToReact.js +22 -3
  29. package/dist/sdk/front-component-api/constants/EventToReact.js.map +1 -1
  30. package/dist/sdk/front-component-api/constants/SerializedEventData.d.ts +7 -0
  31. package/dist/sdk/front-component-api/globals/frontComponentHostCommunicationApi.d.ts +2 -0
  32. package/dist/sdk/front-component-api/globals/frontComponentHostCommunicationApi.js.map +1 -1
  33. package/dist/sdk/index.d.ts +3 -0
  34. package/dist/sdk/index.js +70 -66
  35. package/dist/sdk/index.js.map +1 -1
  36. package/dist/sdk/logic-functions/define-post-install-logic-function.d.ts +6 -0
  37. package/dist/sdk/logic-functions/define-post-install-logic-function.js +12 -0
  38. package/dist/sdk/logic-functions/define-post-install-logic-function.js.map +1 -0
  39. package/dist/sdk/logic-functions/define-pre-install-logic-function.d.ts +6 -0
  40. package/dist/sdk/logic-functions/define-pre-install-logic-function.js +12 -0
  41. package/dist/sdk/logic-functions/define-pre-install-logic-function.js.map +1 -0
  42. package/dist/sdk/logic-functions/install-logic-function-payload-type.d.ts +4 -0
  43. package/generated/core/index.ts +406 -0
  44. package/generated/core/runtime/batcher.ts +265 -0
  45. package/generated/core/runtime/createClient.ts +68 -0
  46. package/generated/core/runtime/error.ts +29 -0
  47. package/generated/core/runtime/fetcher.ts +98 -0
  48. package/generated/core/runtime/generateGraphqlOperation.ts +225 -0
  49. package/generated/core/runtime/index.ts +13 -0
  50. package/generated/core/runtime/linkTypeMap.ts +139 -0
  51. package/generated/core/runtime/typeSelection.ts +98 -0
  52. package/generated/core/runtime/types.ts +69 -0
  53. package/generated/core/schema.graphql +36745 -0
  54. package/generated/core/schema.ts +39341 -0
  55. package/generated/core/types.ts +45860 -0
  56. package/generated/index.ts +2 -0
  57. package/generated/metadata/index.ts +469 -0
  58. package/generated/metadata/runtime/batcher.ts +265 -0
  59. package/generated/metadata/runtime/createClient.ts +68 -0
  60. package/generated/metadata/runtime/error.ts +29 -0
  61. package/generated/metadata/runtime/fetcher.ts +98 -0
  62. package/generated/metadata/runtime/generateGraphqlOperation.ts +225 -0
  63. package/generated/metadata/runtime/index.ts +13 -0
  64. package/generated/metadata/runtime/linkTypeMap.ts +139 -0
  65. package/generated/metadata/runtime/typeSelection.ts +98 -0
  66. package/generated/metadata/runtime/types.ts +69 -0
  67. package/generated/metadata/schema.graphql +3971 -0
  68. package/generated/metadata/schema.ts +8357 -0
  69. package/generated/metadata/types.ts +10044 -0
  70. package/package.json +17 -1
@@ -0,0 +1,2 @@
1
+ export { CoreApiClient } from './core/index';
2
+ export { MetadataApiClient } from './metadata/index';
@@ -0,0 +1,469 @@
1
+ // @ts-nocheck
2
+ import type {
3
+ QueryGenqlSelection,
4
+ Query,
5
+ MutationGenqlSelection,
6
+ Mutation,
7
+ SubscriptionGenqlSelection,
8
+ Subscription,
9
+ } from './schema'
10
+ import {
11
+ linkTypeMap,
12
+ createClient as createClientOriginal,
13
+ generateGraphqlOperation,
14
+ type FieldsSelection,
15
+ type GraphqlOperation,
16
+ type ClientOptions,
17
+ GenqlError,
18
+ } from './runtime'
19
+ export type { FieldsSelection } from './runtime'
20
+ export { GenqlError }
21
+
22
+ import types from './types'
23
+ export * from './schema'
24
+ const typeMap = linkTypeMap(types as any)
25
+
26
+ export interface Client {
27
+ query<R extends QueryGenqlSelection>(
28
+ request: R & { __name?: string },
29
+ ): Promise<FieldsSelection<Query, R>>
30
+
31
+ mutation<R extends MutationGenqlSelection>(
32
+ request: R & { __name?: string },
33
+ ): Promise<FieldsSelection<Mutation, R>>
34
+ }
35
+
36
+ export const createClient = function (options?: ClientOptions): Client {
37
+ return createClientOriginal({
38
+ url: undefined,
39
+
40
+ ...options,
41
+ queryRoot: typeMap.Query!,
42
+ mutationRoot: typeMap.Mutation!,
43
+ subscriptionRoot: typeMap.Subscription!,
44
+ }) as any
45
+ }
46
+
47
+ export const everything = {
48
+ __scalar: true,
49
+ }
50
+
51
+ export type QueryResult<fields extends QueryGenqlSelection> = FieldsSelection<
52
+ Query,
53
+ fields
54
+ >
55
+ export const generateQueryOp: (
56
+ fields: QueryGenqlSelection & { __name?: string },
57
+ ) => GraphqlOperation = function (fields) {
58
+ return generateGraphqlOperation('query', typeMap.Query!, fields as any)
59
+ }
60
+
61
+ export type MutationResult<fields extends MutationGenqlSelection> =
62
+ FieldsSelection<Mutation, fields>
63
+ export const generateMutationOp: (
64
+ fields: MutationGenqlSelection & { __name?: string },
65
+ ) => GraphqlOperation = function (fields) {
66
+ return generateGraphqlOperation('mutation', typeMap.Mutation!, fields as any)
67
+ }
68
+
69
+ export type SubscriptionResult<fields extends SubscriptionGenqlSelection> =
70
+ FieldsSelection<Subscription, fields>
71
+ export const generateSubscriptionOp: (
72
+ fields: SubscriptionGenqlSelection & { __name?: string },
73
+ ) => GraphqlOperation = function (fields) {
74
+ return generateGraphqlOperation(
75
+ 'subscription',
76
+ typeMap.Subscription!,
77
+ fields as any,
78
+ )
79
+ }
80
+
81
+
82
+ // ----------------------------------------------------
83
+ // MetadataApiClient (auto-injected)
84
+ // ----------------------------------------------------
85
+
86
+ const APP_ACCESS_TOKEN_ENV_KEY = 'TWENTY_APP_ACCESS_TOKEN';
87
+ const API_KEY_ENV_KEY = 'TWENTY_API_KEY';
88
+
89
+ type MetadataApiClientOptions = ClientOptions
90
+
91
+ type ProcessEnvironment = Record<string, string | undefined>
92
+
93
+ type GraphqlError = {
94
+ message?: string;
95
+ extensions?: { code?: string };
96
+ }
97
+
98
+ type GraphqlResponsePayload = {
99
+ data?: Record<string, unknown>
100
+ errors?: GraphqlError[];
101
+ }
102
+
103
+ type GraphqlResponse = {
104
+ status: number;
105
+ statusText: string;
106
+ payload: GraphqlResponsePayload | null;
107
+ rawBody: string;
108
+ }
109
+
110
+ const getProcessEnvironment = (): ProcessEnvironment => {
111
+ const processObject = (globalThis as { process?: { env?: ProcessEnvironment } })
112
+ .process;
113
+
114
+ return processObject?.env ?? {};
115
+ }
116
+
117
+ const getTokenFromAuthorizationHeader = (
118
+ authorizationHeader: string | undefined,
119
+ ): string | null => {
120
+ if (typeof authorizationHeader !== 'string') {
121
+ return null;
122
+ }
123
+
124
+ const trimmedAuthorizationHeader = authorizationHeader.trim();
125
+
126
+ if (trimmedAuthorizationHeader.length === 0) {
127
+ return null;
128
+ }
129
+
130
+ if (trimmedAuthorizationHeader === 'Bearer') {
131
+ return null;
132
+ }
133
+
134
+ if (trimmedAuthorizationHeader.startsWith('Bearer ')) {
135
+ return trimmedAuthorizationHeader.slice('Bearer '.length).trim();
136
+ }
137
+
138
+ return trimmedAuthorizationHeader;
139
+ }
140
+
141
+ const getTokenFromHeaders = (headers: HeadersInit | undefined): string | null => {
142
+ if (!headers) {
143
+ return null;
144
+ }
145
+
146
+ if (headers instanceof Headers) {
147
+ return getTokenFromAuthorizationHeader(headers.get('Authorization') ?? undefined);
148
+ }
149
+
150
+ if (Array.isArray(headers)) {
151
+ const matchedAuthorizationHeader = headers.find(
152
+ ([headerName]) => headerName.toLowerCase() === 'authorization',
153
+ );
154
+
155
+ return getTokenFromAuthorizationHeader(matchedAuthorizationHeader?.[1]);
156
+ }
157
+
158
+ const headersRecord = headers as Record<string, string | undefined>;
159
+
160
+ return getTokenFromAuthorizationHeader(
161
+ headersRecord.Authorization ?? headersRecord.authorization,
162
+ );
163
+ }
164
+
165
+ const hasAuthenticationErrorInGraphqlPayload = (
166
+ payload: GraphqlResponsePayload | null,
167
+ ): boolean => {
168
+ if (!payload?.errors) {
169
+ return false;
170
+ }
171
+
172
+ return payload.errors.some((error) => {
173
+ return (
174
+ error.extensions?.code === 'UNAUTHENTICATED' ||
175
+ error.message?.toLowerCase() === 'unauthorized'
176
+ );
177
+ });
178
+ }
179
+
180
+ const defaultOptions: MetadataApiClientOptions = {
181
+ url: `${process.env.TWENTY_API_URL}/metadata`,
182
+ headers: {
183
+ 'Content-Type': 'application/json',
184
+ },
185
+ }
186
+
187
+ export class MetadataApiClient {
188
+ private client: Client;
189
+ private url: string;
190
+ private requestOptions: RequestInit;
191
+ private headers: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
192
+ private fetchImplementation: typeof globalThis.fetch | null;
193
+ private authorizationToken: string | null;
194
+ private refreshAccessTokenPromise: Promise<string | null> | null = null;
195
+
196
+ constructor(options?: MetadataApiClientOptions) {
197
+ const merged: MetadataApiClientOptions = {
198
+ ...defaultOptions,
199
+ ...options,
200
+ }
201
+
202
+ const {
203
+ url,
204
+ headers,
205
+ fetch: customFetchImplementation,
206
+ fetcher: _fetcher,
207
+ batch: _batch,
208
+ ...requestOptions
209
+ } = merged;
210
+
211
+ this.url = url ?? '';
212
+ this.requestOptions = requestOptions;
213
+ this.headers = headers ?? {};
214
+ this.fetchImplementation = customFetchImplementation ?? globalThis.fetch ?? null;
215
+
216
+ const processEnvironment = getProcessEnvironment();
217
+ const tokenFromHeaders = getTokenFromHeaders(
218
+ typeof headers === 'function' ? undefined : headers,
219
+ );
220
+
221
+ // Priority: explicit header > TWENTY_APP_ACCESS_TOKEN > TWENTY_API_KEY (legacy fallback).
222
+ this.authorizationToken =
223
+ tokenFromHeaders ??
224
+ processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] ??
225
+ processEnvironment[API_KEY_ENV_KEY] ??
226
+ null;
227
+
228
+ this.client = createClient({
229
+ ...merged,
230
+ headers: undefined,
231
+ fetcher: async (operation) =>
232
+ this.executeGraphqlRequestWithOptionalRefresh({
233
+ operation,
234
+ }),
235
+ });
236
+ }
237
+
238
+ query<R extends QueryGenqlSelection>(request: R & { __name?: string }) {
239
+ return this.client.query(request);
240
+ }
241
+
242
+ mutation<R extends MutationGenqlSelection>(request: R & { __name?: string }) {
243
+ return this.client.mutation(request);
244
+ }
245
+
246
+ async uploadFile(
247
+ fileBuffer: Buffer,
248
+ filename: string,
249
+ contentType: string = 'application/octet-stream',
250
+ fieldMetadataUniversalIdentifier: string,
251
+ ): Promise<{
252
+ id: string;
253
+ path: string;
254
+ size: number;
255
+ createdAt: string;
256
+ url: string;
257
+ }> {
258
+ const form = new FormData();
259
+
260
+ form.append(
261
+ 'operations',
262
+ JSON.stringify({
263
+ query: `mutation UploadFilesFieldFileByUniversalIdentifier($file: Upload!, $fieldMetadataUniversalIdentifier: String!) {
264
+ uploadFilesFieldFileByUniversalIdentifier(file: $file, fieldMetadataUniversalIdentifier: $fieldMetadataUniversalIdentifier) { id path size createdAt url }
265
+ }`,
266
+ variables: { file: null, fieldMetadataUniversalIdentifier },
267
+ }),
268
+ );
269
+ form.append('map', JSON.stringify({ '0': ['variables.file'] }));
270
+ form.append('0', new Blob([fileBuffer], { type: contentType }), filename);
271
+
272
+ const result = await this.executeGraphqlRequestWithOptionalRefresh({
273
+ operation: form,
274
+ headers: {},
275
+ requestInit: {
276
+ method: 'POST',
277
+ },
278
+ });
279
+
280
+ if (result.errors) {
281
+ throw new GenqlError(result.errors, result.data);
282
+ }
283
+
284
+ const data = result.data as Record<string, unknown>;
285
+
286
+ return data.uploadFilesFieldFileByUniversalIdentifier as {
287
+ id: string;
288
+ path: string;
289
+ size: number;
290
+ createdAt: string;
291
+ url: string;
292
+ }
293
+ }
294
+
295
+ private async executeGraphqlRequestWithOptionalRefresh({
296
+ operation,
297
+ headers,
298
+ requestInit,
299
+ }: {
300
+ operation: GraphqlOperation | GraphqlOperation[] | FormData;
301
+ headers?: HeadersInit;
302
+ requestInit?: RequestInit;
303
+ }) {
304
+ const firstResponse = await this.executeGraphqlRequest({
305
+ operation,
306
+ headers,
307
+ requestInit,
308
+ token: this.authorizationToken,
309
+ });
310
+
311
+ if (this.shouldRefreshToken(firstResponse)) {
312
+ const refreshedAccessToken = await this.requestRefreshedAccessToken();
313
+
314
+ if (refreshedAccessToken) {
315
+ const retryResponse = await this.executeGraphqlRequest({
316
+ operation,
317
+ headers,
318
+ requestInit,
319
+ token: refreshedAccessToken,
320
+ });
321
+
322
+ return this.assertResponseIsSuccessful(retryResponse);
323
+ }
324
+ }
325
+
326
+ return this.assertResponseIsSuccessful(firstResponse);
327
+ }
328
+
329
+ private async executeGraphqlRequest({
330
+ operation,
331
+ headers,
332
+ requestInit,
333
+ token,
334
+ }: {
335
+ operation: GraphqlOperation | GraphqlOperation[] | FormData;
336
+ headers?: HeadersInit;
337
+ requestInit?: RequestInit;
338
+ token: string | null;
339
+ }): Promise<GraphqlResponse> {
340
+ if (!this.fetchImplementation) {
341
+ throw new Error(
342
+ 'Global `fetch` function is not available, pass a fetch implementation to the Twenty client',
343
+ );
344
+ }
345
+
346
+ const resolvedHeaders = await this.resolveHeaders();
347
+ const requestHeaders = new Headers(resolvedHeaders);
348
+
349
+ if (headers) {
350
+ new Headers(headers).forEach((value, key) => requestHeaders.set(key, value));
351
+ }
352
+
353
+ if (operation instanceof FormData) {
354
+ requestHeaders.delete('Content-Type');
355
+ } else {
356
+ requestHeaders.set('Content-Type', 'application/json');
357
+ }
358
+
359
+ if (token) {
360
+ requestHeaders.set('Authorization', `Bearer ${token}`);
361
+ } else {
362
+ requestHeaders.delete('Authorization');
363
+ }
364
+
365
+ const response = await this.fetchImplementation.call(globalThis, this.url, {
366
+ ...this.requestOptions,
367
+ ...requestInit,
368
+ method: requestInit?.method ?? 'POST',
369
+ headers: requestHeaders,
370
+ body: operation instanceof FormData ? operation : JSON.stringify(operation),
371
+ });
372
+
373
+ const rawBody = await response.text();
374
+ let payload: GraphqlResponsePayload | null = null;
375
+
376
+ if (rawBody.trim().length > 0) {
377
+ try {
378
+ payload = JSON.parse(rawBody) as GraphqlResponsePayload;
379
+ } catch {
380
+ payload = null;
381
+ }
382
+ }
383
+
384
+ return {
385
+ status: response.status,
386
+ statusText: response.statusText,
387
+ payload,
388
+ rawBody,
389
+ }
390
+ }
391
+
392
+ private async resolveHeaders(): Promise<HeadersInit> {
393
+ if (typeof this.headers === 'function') {
394
+ return (await this.headers()) ?? {};
395
+ }
396
+
397
+ return this.headers ?? {};
398
+ }
399
+
400
+ private shouldRefreshToken(response: GraphqlResponse): boolean {
401
+ if (response.status === 401) {
402
+ return true;
403
+ }
404
+
405
+ return hasAuthenticationErrorInGraphqlPayload(response.payload);
406
+ }
407
+
408
+ private assertResponseIsSuccessful(response: GraphqlResponse) {
409
+ if (response.status < 200 || response.status >= 300) {
410
+ throw new Error(`${response.statusText}: ${response.rawBody}`);
411
+ }
412
+
413
+ if (response.payload === null) {
414
+ throw new Error('Invalid JSON response');
415
+ }
416
+
417
+ return response.payload;
418
+ }
419
+
420
+ private async requestRefreshedAccessToken(): Promise<string | null> {
421
+ const refreshAccessTokenFunction = (
422
+ globalThis as {
423
+ frontComponentHostCommunicationApi?: {
424
+ requestAccessTokenRefresh?: () => Promise<string>
425
+ }
426
+ }
427
+ ).frontComponentHostCommunicationApi?.requestAccessTokenRefresh;
428
+
429
+ if (typeof refreshAccessTokenFunction !== 'function') {
430
+ return null;
431
+ }
432
+
433
+ if (!this.refreshAccessTokenPromise) {
434
+ this.refreshAccessTokenPromise = refreshAccessTokenFunction()
435
+ .then((refreshedAccessToken) => {
436
+ if (
437
+ typeof refreshedAccessToken !== 'string' ||
438
+ refreshedAccessToken.length === 0
439
+ ) {
440
+ return null;
441
+ }
442
+
443
+ this.setAuthorizationToken(refreshedAccessToken);
444
+
445
+ return refreshedAccessToken;
446
+ })
447
+ .catch((error) => {
448
+ console.error('Twenty client: token refresh failed', error);
449
+
450
+ return null;
451
+ })
452
+ .finally(() => {
453
+ this.refreshAccessTokenPromise = null;
454
+ });
455
+ }
456
+
457
+ return this.refreshAccessTokenPromise;
458
+ }
459
+
460
+ private setAuthorizationToken(token: string) {
461
+ this.authorizationToken = token;
462
+
463
+ const processEnvironment = getProcessEnvironment();
464
+
465
+ processEnvironment[APP_ACCESS_TOKEN_ENV_KEY] = token;
466
+ processEnvironment[API_KEY_ENV_KEY] = token;
467
+ }
468
+ }
469
+