twenty-sdk 2.9.0 → 2.10.0

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 (42) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/billing/index.cjs.map +1 -1
  3. package/dist/billing/index.mjs.map +1 -1
  4. package/dist/catalog-sync-BHD2q_KA.mjs +18 -0
  5. package/dist/catalog-sync-Dp2RKu2c.js +1 -0
  6. package/dist/cli/utilities/build/manifest/manifest-extract-config.d.ts +2 -0
  7. package/dist/cli/utilities/build/manifest/utils/validate-conditional-availability-usage.d.ts +1 -0
  8. package/dist/cli/utilities/build/manifest/utils/validate-package-json-dependencies.d.ts +1 -0
  9. package/dist/cli/utilities/entity/entity-view-field-template.d.ts +3 -0
  10. package/dist/cli.cjs +93 -77
  11. package/dist/cli.mjs +1868 -1830
  12. package/dist/define/index.cjs +38 -16
  13. package/dist/define/index.cjs.map +1 -1
  14. package/dist/define/index.d.ts +871 -52
  15. package/dist/define/index.mjs +13655 -3526
  16. package/dist/define/index.mjs.map +1 -1
  17. package/dist/front-component/index.cjs +37 -15
  18. package/dist/front-component/index.cjs.map +1 -1
  19. package/dist/front-component/index.d.ts +1 -135
  20. package/dist/front-component/index.mjs +12833 -3490
  21. package/dist/front-component/index.mjs.map +1 -1
  22. package/dist/get-function-input-schema-DTlcRJz3-BweFaTLz.mjs +73 -0
  23. package/dist/get-function-input-schema-DTlcRJz3-DWdkAlue.js +1 -0
  24. package/dist/logic-function/index.cjs +37 -1
  25. package/dist/logic-function/index.cjs.map +1 -1
  26. package/dist/logic-function/index.d.ts +33 -2
  27. package/dist/logic-function/index.mjs +97 -28
  28. package/dist/logic-function/index.mjs.map +1 -1
  29. package/dist/{login-oauth-DSC3zo9c.mjs → login-oauth-BPSmh2dn.mjs} +15214 -4936
  30. package/dist/login-oauth-DnF6U1Ak.js +340 -0
  31. package/dist/operations.cjs +1 -1
  32. package/dist/operations.mjs +2 -2
  33. package/dist/ui/index.cjs +48 -26
  34. package/dist/ui/index.mjs +20941 -11460
  35. package/dist/utils/index.cjs.map +1 -1
  36. package/dist/utils/index.mjs.map +1 -1
  37. package/package.json +11 -9
  38. package/dist/catalog-sync-CanLpG9v.js +0 -1
  39. package/dist/catalog-sync-DyCidT5d.mjs +0 -16
  40. package/dist/get-function-input-schema-BZ7_XyUh-COeGJwHh.js +0 -1
  41. package/dist/get-function-input-schema-BZ7_XyUh-Dql7-b-j.mjs +0 -62
  42. package/dist/login-oauth-BESuSxoP.js +0 -298
@@ -0,0 +1,73 @@
1
+ import { createSourceFile as y, ScriptTarget as p, SyntaxKind as r } from "typescript";
2
+ import { o } from "./login-oauth-BPSmh2dn.mjs";
3
+ const c = (i) => {
4
+ switch (i.kind) {
5
+ case r.NumberKeyword:
6
+ return { type: "number" };
7
+ case r.StringKeyword:
8
+ return { type: "string" };
9
+ case r.BooleanKeyword:
10
+ return { type: "boolean" };
11
+ case r.ArrayType:
12
+ return {
13
+ type: "array",
14
+ items: c(i.elementType)
15
+ };
16
+ case r.TypeReference: {
17
+ const e = i, t = e.typeName.kind === r.Identifier ? e.typeName.text : void 0;
18
+ if (t === "Array" || t === "ReadonlyArray") {
19
+ const a = e.typeArguments?.[0];
20
+ return {
21
+ type: "array",
22
+ items: o(a) ? c(a) : {}
23
+ };
24
+ }
25
+ return {};
26
+ }
27
+ case r.ObjectKeyword:
28
+ return { type: "object" };
29
+ case r.TypeLiteral: {
30
+ const e = {};
31
+ return i.members.forEach((t) => {
32
+ if (o(t.name) && o(t.type)) {
33
+ const a = t.name.text;
34
+ e[a] = c(t.type);
35
+ }
36
+ }), { type: "object", properties: e };
37
+ }
38
+ case r.UnionType: {
39
+ const e = i, t = [];
40
+ let a = !0;
41
+ return e.types.forEach((n) => {
42
+ if (n.kind === r.LiteralType) {
43
+ const s = n.literal;
44
+ s.kind === r.StringLiteral ? t.push(s.text) : a = !1;
45
+ } else
46
+ a = !1;
47
+ }), a ? { type: "string", enum: t } : {};
48
+ }
49
+ default:
50
+ return {};
51
+ }
52
+ }, l = (i, e) => i.parameters.reduce((t, a) => {
53
+ const n = a.type;
54
+ return o(n) ? [...t, c(n)] : [...t, {}];
55
+ }, e), u = (i) => i.kind === r.FunctionDeclaration ? [i] : i.kind === r.VariableStatement ? i.declarationList.declarations.filter(
56
+ (e) => o(e.initializer) && e.initializer.kind === r.ArrowFunction
57
+ ).map((e) => e.initializer) : [], f = (i) => {
58
+ const e = y(
59
+ "temp.ts",
60
+ i,
61
+ p.ESNext,
62
+ !0
63
+ );
64
+ let t = [];
65
+ return e.forEachChild((a) => {
66
+ (a.kind === r.FunctionDeclaration || a.kind === r.VariableStatement) && u(a).forEach((n) => {
67
+ t = l(n, t);
68
+ });
69
+ }), t;
70
+ };
71
+ export {
72
+ f as getFunctionInputSchema
73
+ };
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("typescript"),o=require("./login-oauth-DnF6U1Ak.js"),y=r=>{switch(r.kind){case e.SyntaxKind.NumberKeyword:return{type:"number"};case e.SyntaxKind.StringKeyword:return{type:"string"};case e.SyntaxKind.BooleanKeyword:return{type:"boolean"};case e.SyntaxKind.ArrayType:return{type:"array",items:y(r.elementType)};case e.SyntaxKind.TypeReference:{const t=r,n=t.typeName.kind===e.SyntaxKind.Identifier?t.typeName.text:void 0;if(n==="Array"||n==="ReadonlyArray"){const i=t.typeArguments?.[0];return{type:"array",items:o.o(i)?y(i):{}}}return{}}case e.SyntaxKind.ObjectKeyword:return{type:"object"};case e.SyntaxKind.TypeLiteral:{const t={};return r.members.forEach(n=>{if(o.o(n.name)&&o.o(n.type)){const i=n.name.text;t[i]=y(n.type)}}),{type:"object",properties:t}}case e.SyntaxKind.UnionType:{const t=r,n=[];let i=!0;return t.types.forEach(a=>{if(a.kind===e.SyntaxKind.LiteralType){const c=a.literal;c.kind===e.SyntaxKind.StringLiteral?n.push(c.text):i=!1}else i=!1}),i?{type:"string",enum:n}:{}}default:return{}}},d=(r,t)=>r.parameters.reduce((n,i)=>{const a=i.type;return o.o(a)?[...n,y(a)]:[...n,{}]},t),s=r=>r.kind===e.SyntaxKind.FunctionDeclaration?[r]:r.kind===e.SyntaxKind.VariableStatement?r.declarationList.declarations.filter(t=>o.o(t.initializer)&&t.initializer.kind===e.SyntaxKind.ArrowFunction).map(t=>t.initializer):[],u=r=>{const t=e.createSourceFile("temp.ts",r,e.ScriptTarget.ESNext,!0);let n=[];return t.forEachChild(i=>{(i.kind===e.SyntaxKind.FunctionDeclaration||i.kind===e.SyntaxKind.VariableStatement)&&s(i).forEach(a=>{n=d(a,n)})}),n};exports.getFunctionInputSchema=u;
@@ -1,2 +1,38 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class c extends Error{constructor(e){super(`App connection ${e} requires the user to reconnect (authFailedAt is set). Surface a "Reconnect" prompt in your UI.`),this.name="AppConnectionAuthFailedError",this.connectionId=e}}const r="TWENTY_API_URL",i="TWENTY_APP_ACCESS_TOKEN",a=async(n,e)=>{const s=process.env[r],t=process.env[i];if(!s||!t)throw new Error(`${n==="list"?"listConnections":"getConnection"}() requires the app runtime env vars ${r} and ${i}.`);const o=await fetch(`${s}/apps/connections/${n}`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(e)});if(!o.ok)throw new Error(`${n==="list"?"listConnections":"getConnection"}() failed: HTTP ${o.status} ${o.statusText}`);return await o.json()},u=async n=>{const e=await a("get",{id:n});if(e.authFailedAt!==null)throw new c(e.id);return e},p=async(n={})=>a("list",n),l=(n,e)=>{if(e.userWorkspaceId!==null){const t=n.find(o=>o.visibility==="user"&&o.userWorkspaceId===e.userWorkspaceId);if(t)return t}return n.find(t=>t.visibility==="workspace")??null};exports.AppConnectionAuthFailedError=c;exports.findConnectionForRequest=l;exports.getConnection=u;exports.listConnections=p;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class p extends Error{constructor(e){super(`App connection ${e} requires the user to reconnect (authFailedAt is set). Surface a "Reconnect" prompt in your UI.`),this.name="AppConnectionAuthFailedError",this.connectionId=e}}const c="TWENTY_API_URL",u="TWENTY_APP_ACCESS_TOKEN",a=async({query:n,variables:e,caller:t})=>{const r=process.env[c],s=process.env[u];if(!r||!s)throw new Error(`${t}() requires the app runtime env vars ${c} and ${u}.`);const i=await fetch(`${r}/metadata`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({query:n,variables:e})});if(!i.ok)throw new Error(`${t}() failed: HTTP ${i.status} ${i.statusText}`);const o=await i.json();if(o.errors&&o.errors.length>0)throw new Error(`${t}() failed: ${o.errors.map(d=>d.message).join(", ")}`);if(!o.data)throw new Error(`${t}() failed: response contained no data.`);return o.data},l=`
2
+ query GetAppConnection($id: ID!) {
3
+ appConnection(id: $id) {
4
+ id
5
+ providerName
6
+ name
7
+ handle
8
+ visibility
9
+ userWorkspaceId
10
+ accessToken
11
+ scopes
12
+ authFailedAt
13
+ }
14
+ }
15
+ `,h=async n=>{const{appConnection:e}=await a({query:l,variables:{id:n},caller:"getConnection"});if(e.authFailedAt!==null)throw new p(e.id);return e},A=`
16
+ query ListAppConnections($filter: ListAppConnectionsInput) {
17
+ appConnections(filter: $filter) {
18
+ id
19
+ providerName
20
+ name
21
+ handle
22
+ visibility
23
+ userWorkspaceId
24
+ accessToken
25
+ scopes
26
+ authFailedAt
27
+ }
28
+ }
29
+ `,C=async(n={})=>{const{appConnections:e}=await a({query:A,variables:{filter:n},caller:"listConnections"});return e},y=(n,e)=>{if(e.userWorkspaceId!==null){const r=n.find(s=>s.visibility==="user"&&s.userWorkspaceId===e.userWorkspaceId);if(r)return r}return n.find(r=>r.visibility==="workspace")??null},T=`
30
+ mutation RunAgent($input: RunAgentInput!) {
31
+ runAgent(input: $input) {
32
+ result
33
+ error
34
+ success
35
+ }
36
+ }
37
+ `,f=async n=>{const{runAgent:e}=await a({query:T,variables:{input:n},caller:"runAgent"});return e};class w{constructor(e,t){this.__twentyHttpResponse=!0,this.body=e,this.status=t?.status,this.headers=t?.headers}}exports.AppConnectionAuthFailedError=p;exports.Response=w;exports.findConnectionForRequest=y;exports.getConnection=h;exports.listConnections=C;exports.runAgent=f;
2
38
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../src/sdk/logic-function/connections/errors/app-connection-auth-failed.error.ts","../../../twenty-shared/dist/application.mjs","../../src/sdk/logic-function/connections/utils/post-connections-endpoint.util.ts","../../src/sdk/logic-function/connections/get-connection.ts","../../src/sdk/logic-function/connections/list-connections.ts","../../src/sdk/logic-function/connections/find-connection-for-request.ts"],"sourcesContent":["// Thrown when the platform asks the SDK to operate on a connection whose\n// OAuth refresh failed permanently (`authFailedAt` is set). The end user\n// must reconnect from the app's settings tab — the app cannot recover on\n// its own.\n//\n// `listConnections` filters these out by default (the user can't act on\n// them anyway). `getConnection` throws this when the looked-up connection\n// is in this state, so a stored connection id can be safely retried until\n// it works again.\nexport class AppConnectionAuthFailedError extends Error {\n readonly connectionId: string;\n\n constructor(connectionId: string) {\n super(\n `App connection ${connectionId} requires the user to reconnect ` +\n `(authFailedAt is set). Surface a \"Reconnect\" prompt in your UI.`,\n );\n this.name = 'AppConnectionAuthFailedError';\n this.connectionId = connectionId;\n }\n}\n","const _ = \"public\", A = \"TWENTY_API_KEY\", T = \"TWENTY_API_URL\", r = \"TWENTY_APP_ACCESS_TOKEN\", t = \"generated\", N = {\n js: `import { createRequire as __createRequire } from 'module';\nconst require = __createRequire(import.meta.url);`\n}, u = \".twenty/output\", I = \"Standard\", n = \"20202020-64aa-4b6f-b003-9c74b97cee20\";\nvar e = /* @__PURE__ */ ((o) => (o.Object = \"object\", o.Field = \"field\", o.LogicFunction = \"logicFunction\", o.FrontComponent = \"frontComponent\", o.Role = \"role\", o.Skill = \"skill\", o.Agent = \"agent\", o.ConnectionProvider = \"connectionProvider\", o.View = \"view\", o.NavigationMenuItem = \"navigationMenuItem\", o.PageLayout = \"pageLayout\", o.PageLayoutTab = \"pageLayoutTab\", o.CommandMenuItem = \"commandMenuItem\", o))(e || {});\nexport {\n _ as ASSETS_DIR,\n A as DEFAULT_API_KEY_NAME,\n T as DEFAULT_API_URL_NAME,\n r as DEFAULT_APP_ACCESS_TOKEN_NAME,\n t as GENERATED_DIR,\n N as NODE_ESM_CJS_BANNER,\n u as OUTPUT_DIR,\n e as SyncableEntity,\n I as TWENTY_STANDARD_APPLICATION_NAME,\n n as TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER\n};\n","import {\n DEFAULT_API_URL_NAME,\n DEFAULT_APP_ACCESS_TOKEN_NAME,\n} from 'twenty-shared/application';\n\n// Shared transport for `/apps/connections/*` endpoints. Centralises the\n// env-var check, auth header, and HTTP error translation so each helper\n// stays focused on its own input/output shape.\nexport const postConnectionsEndpoint = async <TBody, TResponse>(\n path: 'list' | 'get',\n body: TBody,\n): Promise<TResponse> => {\n const apiUrl = process.env[DEFAULT_API_URL_NAME];\n const accessToken = process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];\n\n if (!apiUrl || !accessToken) {\n throw new Error(\n `${path === 'list' ? 'listConnections' : 'getConnection'}() requires the app runtime env vars ` +\n `${DEFAULT_API_URL_NAME} and ${DEFAULT_APP_ACCESS_TOKEN_NAME}.`,\n );\n }\n\n const response = await fetch(`${apiUrl}/apps/connections/${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n throw new Error(\n `${path === 'list' ? 'listConnections' : 'getConnection'}() failed: ` +\n `HTTP ${response.status} ${response.statusText}`,\n );\n }\n\n return (await response.json()) as TResponse;\n};\n","import { AppConnectionAuthFailedError } from '@/sdk/logic-function/connections/errors/app-connection-auth-failed.error';\nimport { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\nimport { postConnectionsEndpoint } from '@/sdk/logic-function/connections/utils/post-connections-endpoint.util';\n\n// Look up a single connection by id. The id is stable across reconnects\n// (the row keeps its id when the user clicks \"Reconnect\"), so apps can\n// safely persist it in their own data and call this helper on each\n// invocation to retrieve a fresh access token.\n//\n// Throws `AppConnectionAuthFailedError` if the credential is in a\n// permanent-failure state (the user must reconnect from the app's\n// settings tab). Throws a regular `Error` for any other failure\n// (network, not-found, transient refresh failure).\nexport const getConnection = async (id: string): Promise<AppConnection> => {\n const connection = await postConnectionsEndpoint<\n { id: string },\n AppConnection\n >('get', { id });\n\n if (connection.authFailedAt !== null) {\n throw new AppConnectionAuthFailedError(connection.id);\n }\n\n return connection;\n};\n","import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\nimport { postConnectionsEndpoint } from '@/sdk/logic-function/connections/utils/post-connections-endpoint.util';\n\nexport type ListConnectionsFilter = {\n // Provider name as declared on `defineConnectionProvider({ name })`.\n providerName?: string;\n // Restrict to credentials owned by a specific user. Useful in cron\n // triggers when picking a service-account user via app config.\n userWorkspaceId?: string;\n // Restrict by row visibility — 'user' (private) or 'workspace' (shared).\n visibility?: 'user' | 'workspace';\n};\n\n// Returns every connection owned by the running app, optionally filtered.\n// The server refreshes each access token on read, so the returned values\n// are usable immediately. When the running execution carries a user\n// context (HTTP-route trigger with `isAuthRequired`, tool calls, etc.),\n// `scope: 'user'` connections belonging to other users are filtered out\n// server-side. Cron and database-event triggers see all connections.\nexport const listConnections = async (\n filter: ListConnectionsFilter = {},\n): Promise<AppConnection[]> =>\n postConnectionsEndpoint<ListConnectionsFilter, AppConnection[]>(\n 'list',\n filter,\n );\n","import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\n\n// Resolution rule for an HTTP-route handler that wants \"the request user's\n// connection, or fall back to a workspace-shared one.\" Pure function — no\n// network. Pass it the result of `listConnections` and the trigger event.\n//\n// The plan-of-record for picking a connection is documented in the v3 plan\n// notes; this utility encodes the most common case so handlers don't have\n// to repeat the same `find(...) ?? find(...)` chain.\n//\n// Returns `null` when no candidate exists — caller decides whether that's\n// a 4xx for the end user or a hard error.\nexport const findConnectionForRequest = (\n connections: AppConnection[],\n event: { userWorkspaceId: string | null },\n): AppConnection | null => {\n // 1. Personal credential of the request user (highest specificity).\n if (event.userWorkspaceId !== null) {\n const personal = connections.find(\n (connection) =>\n connection.visibility === 'user' &&\n connection.userWorkspaceId === event.userWorkspaceId,\n );\n\n if (personal) {\n return personal;\n }\n }\n\n // 2. Any workspace-shared credential (team-managed service account).\n const workspaceShared = connections.find(\n (connection) => connection.visibility === 'workspace',\n );\n\n return workspaceShared ?? null;\n};\n"],"names":["AppConnectionAuthFailedError","connectionId","T","r","postConnectionsEndpoint","path","body","apiUrl","DEFAULT_API_URL_NAME","accessToken","DEFAULT_APP_ACCESS_TOKEN_NAME","response","getConnection","id","connection","listConnections","filter","findConnectionForRequest","connections","event","personal"],"mappings":"gFASO,MAAMA,UAAqC,KAAM,CAGtD,YAAYC,EAAsB,CAChC,MACE,kBAAkBA,CAAY,iGAAA,EAGhC,KAAK,KAAO,+BACZ,KAAK,aAAeA,CACtB,CACF,CCpBK,MAAqCC,EAAI,iBAAkBC,EAAI,0BCQvDC,EAA0B,MACrCC,EACAC,IACuB,CACvB,MAAMC,EAAS,QAAQ,IAAIC,CAAoB,EACzCC,EAAc,QAAQ,IAAIC,CAA6B,EAE7D,GAAI,CAACH,GAAU,CAACE,EACd,MAAM,IAAI,MACR,GAAGJ,IAAS,OAAS,kBAAoB,eAAe,wCACnDG,CAAoB,QAAQE,CAA6B,GAAA,EAIlE,MAAMC,EAAW,MAAM,MAAM,GAAGJ,CAAM,qBAAqBF,CAAI,GAAI,CACjE,OAAQ,OACR,QAAS,CACP,eAAgB,mBAChB,cAAe,UAAUI,CAAW,EAAA,EAEtC,KAAM,KAAK,UAAUH,CAAI,CAAA,CAC1B,EAED,GAAI,CAACK,EAAS,GACZ,MAAM,IAAI,MACR,GAAGN,IAAS,OAAS,kBAAoB,eAAe,mBAC9CM,EAAS,MAAM,IAAIA,EAAS,UAAU,EAAA,EAIpD,OAAQ,MAAMA,EAAS,KAAA,CACzB,EC1BaC,EAAgB,MAAOC,GAAuC,CACzE,MAAMC,EAAa,MAAMV,EAGvB,MAAO,CAAE,GAAAS,EAAI,EAEf,GAAIC,EAAW,eAAiB,KAC9B,MAAM,IAAId,EAA6Bc,EAAW,EAAE,EAGtD,OAAOA,CACT,ECLaC,EAAkB,MAC7BC,EAAgC,CAAA,IAEhCZ,EACE,OACAY,CACF,ECbWC,EAA2B,CACtCC,EACAC,IACyB,CAEzB,GAAIA,EAAM,kBAAoB,KAAM,CAClC,MAAMC,EAAWF,EAAY,KAC1BJ,GACCA,EAAW,aAAe,QAC1BA,EAAW,kBAAoBK,EAAM,eAAA,EAGzC,GAAIC,EACF,OAAOA,CAEX,CAOA,OAJwBF,EAAY,KACjCJ,GAAeA,EAAW,aAAe,WAAA,GAGlB,IAC5B"}
1
+ {"version":3,"file":"index.cjs","sources":["../../src/sdk/logic-function/connections/errors/app-connection-auth-failed.error.ts","../../../twenty-shared/dist/application.mjs","../../src/sdk/logic-function/utils/post-graphql-request.util.ts","../../src/sdk/logic-function/connections/get-connection.ts","../../src/sdk/logic-function/connections/list-connections.ts","../../src/sdk/logic-function/connections/find-connection-for-request.ts","../../src/sdk/logic-function/agents/run-agent.ts","../../src/sdk/logic-function/response.ts"],"sourcesContent":["// Thrown when the platform asks the SDK to operate on a connection whose\n// OAuth refresh failed permanently (`authFailedAt` is set). The end user\n// must reconnect from the app's settings tab — the app cannot recover on\n// its own.\n//\n// `listConnections` filters these out by default (the user can't act on\n// them anyway). `getConnection` throws this when the looked-up connection\n// is in this state, so a stored connection id can be safely retried until\n// it works again.\nexport class AppConnectionAuthFailedError extends Error {\n readonly connectionId: string;\n\n constructor(connectionId: string) {\n super(\n `App connection ${connectionId} requires the user to reconnect ` +\n `(authFailedAt is set). Surface a \"Reconnect\" prompt in your UI.`,\n );\n this.name = 'AppConnectionAuthFailedError';\n this.connectionId = connectionId;\n }\n}\n","const _ = \"public\", A = \"TWENTY_API_KEY\", T = \"TWENTY_API_URL\", r = \"TWENTY_APP_ACCESS_TOKEN\", N = \"generated\", t = {\n js: `import { createRequire as __createRequire } from 'module';\nconst require = __createRequire(import.meta.url);`\n}, u = \".twenty/output\", I = \"Standard\", P = \"20202020-64aa-4b6f-b003-9c74b97cee20\";\nvar o = /* @__PURE__ */ ((e) => (e.Object = \"object\", e.Field = \"field\", e.LogicFunction = \"logicFunction\", e.FrontComponent = \"frontComponent\", e.Role = \"role\", e.Skill = \"skill\", e.Agent = \"agent\", e.ConnectionProvider = \"connectionProvider\", e.View = \"view\", e.ViewField = \"viewField\", e.NavigationMenuItem = \"navigationMenuItem\", e.PageLayout = \"pageLayout\", e.PageLayoutTab = \"pageLayoutTab\", e.CommandMenuItem = \"commandMenuItem\", e))(o || {});\nexport {\n _ as ASSETS_DIR,\n A as DEFAULT_API_KEY_NAME,\n T as DEFAULT_API_URL_NAME,\n r as DEFAULT_APP_ACCESS_TOKEN_NAME,\n N as GENERATED_DIR,\n t as NODE_ESM_CJS_BANNER,\n u as OUTPUT_DIR,\n o as SyncableEntity,\n I as TWENTY_STANDARD_APPLICATION_NAME,\n P as TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER\n};\n","import {\n DEFAULT_API_URL_NAME,\n DEFAULT_APP_ACCESS_TOKEN_NAME,\n} from 'twenty-shared/application';\n\nexport const postGraphqlRequest = async <TVariables, TData>({\n query,\n variables,\n caller,\n}: {\n query: string;\n variables: TVariables;\n caller: string;\n}): Promise<TData> => {\n const apiUrl = process.env[DEFAULT_API_URL_NAME];\n const accessToken = process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];\n\n if (!apiUrl || !accessToken) {\n throw new Error(\n `${caller}() requires the app runtime env vars ` +\n `${DEFAULT_API_URL_NAME} and ${DEFAULT_APP_ACCESS_TOKEN_NAME}.`,\n );\n }\n\n const response = await fetch(`${apiUrl}/metadata`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({ query, variables }),\n });\n\n if (!response.ok) {\n throw new Error(\n `${caller}() failed: HTTP ${response.status} ${response.statusText}`,\n );\n }\n\n const body = (await response.json()) as {\n data?: TData;\n errors?: { message: string }[];\n };\n\n if (body.errors && body.errors.length > 0) {\n throw new Error(\n `${caller}() failed: ${body.errors.map((error) => error.message).join(', ')}`,\n );\n }\n\n if (!body.data) {\n throw new Error(`${caller}() failed: response contained no data.`);\n }\n\n return body.data;\n};\n","import { AppConnectionAuthFailedError } from '@/sdk/logic-function/connections/errors/app-connection-auth-failed.error';\nimport { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\nimport { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';\n\nconst GET_APP_CONNECTION_QUERY = `\n query GetAppConnection($id: ID!) {\n appConnection(id: $id) {\n id\n providerName\n name\n handle\n visibility\n userWorkspaceId\n accessToken\n scopes\n authFailedAt\n }\n }\n`;\n\nexport const getConnection = async (id: string): Promise<AppConnection> => {\n const { appConnection } = await postGraphqlRequest<\n { id: string },\n { appConnection: AppConnection }\n >({\n query: GET_APP_CONNECTION_QUERY,\n variables: { id },\n caller: 'getConnection',\n });\n\n if (appConnection.authFailedAt !== null) {\n throw new AppConnectionAuthFailedError(appConnection.id);\n }\n\n return appConnection;\n};\n","import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\nimport { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';\n\nconst LIST_APP_CONNECTIONS_QUERY = `\n query ListAppConnections($filter: ListAppConnectionsInput) {\n appConnections(filter: $filter) {\n id\n providerName\n name\n handle\n visibility\n userWorkspaceId\n accessToken\n scopes\n authFailedAt\n }\n }\n`;\n\nexport type ListConnectionsFilter = {\n providerName?: string;\n userWorkspaceId?: string;\n visibility?: 'user' | 'workspace';\n};\n\nexport const listConnections = async (\n filter: ListConnectionsFilter = {},\n): Promise<AppConnection[]> => {\n const { appConnections } = await postGraphqlRequest<\n { filter: ListConnectionsFilter },\n { appConnections: AppConnection[] }\n >({\n query: LIST_APP_CONNECTIONS_QUERY,\n variables: { filter },\n caller: 'listConnections',\n });\n\n return appConnections;\n};\n","import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\n\nexport const findConnectionForRequest = (\n connections: AppConnection[],\n event: { userWorkspaceId: string | null },\n): AppConnection | null => {\n if (event.userWorkspaceId !== null) {\n const personal = connections.find(\n (connection) =>\n connection.visibility === 'user' &&\n connection.userWorkspaceId === event.userWorkspaceId,\n );\n\n if (personal) {\n return personal;\n }\n }\n\n const workspaceShared = connections.find(\n (connection) => connection.visibility === 'workspace',\n );\n\n return workspaceShared ?? null;\n};\n","import {\n type RunAgentInput,\n type RunAgentResult,\n} from 'twenty-shared/application';\n\nimport { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';\n\nconst RUN_AGENT_MUTATION = `\n mutation RunAgent($input: RunAgentInput!) {\n runAgent(input: $input) {\n result\n error\n success\n }\n }\n`;\n\nexport const runAgent = async (\n input: RunAgentInput,\n): Promise<RunAgentResult> => {\n const { runAgent: result } = await postGraphqlRequest<\n { input: RunAgentInput },\n { runAgent: RunAgentResult }\n >({\n query: RUN_AGENT_MUTATION,\n variables: { input },\n caller: 'runAgent',\n });\n\n return result;\n};\n","import { type LogicFunctionHttpResponse } from 'twenty-shared/types';\n\nexport type ResponseInit = {\n status?: number;\n headers?: Record<string, string>;\n};\n\nexport class Response implements LogicFunctionHttpResponse {\n readonly __twentyHttpResponse = true as const;\n readonly body: unknown;\n readonly status?: number;\n readonly headers?: Record<string, string>;\n\n constructor(body: unknown, init?: ResponseInit) {\n this.body = body;\n this.status = init?.status;\n this.headers = init?.headers;\n }\n}\n"],"names":["AppConnectionAuthFailedError","connectionId","T","r","postGraphqlRequest","query","variables","caller","apiUrl","DEFAULT_API_URL_NAME","accessToken","DEFAULT_APP_ACCESS_TOKEN_NAME","response","body","error","GET_APP_CONNECTION_QUERY","getConnection","id","appConnection","LIST_APP_CONNECTIONS_QUERY","listConnections","filter","appConnections","findConnectionForRequest","connections","event","personal","connection","RUN_AGENT_MUTATION","runAgent","input","result","Response","init"],"mappings":"gFASO,MAAMA,UAAqC,KAAM,CAGtD,YAAYC,EAAsB,CAChC,MACE,kBAAkBA,CAAY,iGAAA,EAGhC,KAAK,KAAO,+BACZ,KAAK,aAAeA,CACtB,CACF,CCpBK,MAAqCC,EAAI,iBAAkBC,EAAI,0BCKvDC,EAAqB,MAA0B,CAC1D,MAAAC,EACA,UAAAC,EACA,OAAAC,CACF,IAIsB,CACpB,MAAMC,EAAS,QAAQ,IAAIC,CAAoB,EACzCC,EAAc,QAAQ,IAAIC,CAA6B,EAE7D,GAAI,CAACH,GAAU,CAACE,EACd,MAAM,IAAI,MACR,GAAGH,CAAM,wCACJE,CAAoB,QAAQE,CAA6B,GAAA,EAIlE,MAAMC,EAAW,MAAM,MAAM,GAAGJ,CAAM,YAAa,CACjD,OAAQ,OACR,QAAS,CACP,eAAgB,mBAChB,cAAe,UAAUE,CAAW,EAAA,EAEtC,KAAM,KAAK,UAAU,CAAE,MAAAL,EAAO,UAAAC,EAAW,CAAA,CAC1C,EAED,GAAI,CAACM,EAAS,GACZ,MAAM,IAAI,MACR,GAAGL,CAAM,mBAAmBK,EAAS,MAAM,IAAIA,EAAS,UAAU,EAAA,EAItE,MAAMC,EAAQ,MAAMD,EAAS,KAAA,EAK7B,GAAIC,EAAK,QAAUA,EAAK,OAAO,OAAS,EACtC,MAAM,IAAI,MACR,GAAGN,CAAM,cAAcM,EAAK,OAAO,IAAKC,GAAUA,EAAM,OAAO,EAAE,KAAK,IAAI,CAAC,EAAA,EAI/E,GAAI,CAACD,EAAK,KACR,MAAM,IAAI,MAAM,GAAGN,CAAM,wCAAwC,EAGnE,OAAOM,EAAK,IACd,ECnDME,EAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBpBC,EAAgB,MAAOC,GAAuC,CACzE,KAAM,CAAE,cAAAC,GAAkB,MAAMd,EAG9B,CACA,MAAOW,EACP,UAAW,CAAE,GAAAE,CAAA,EACb,OAAQ,eAAA,CACT,EAED,GAAIC,EAAc,eAAiB,KACjC,MAAM,IAAIlB,EAA6BkB,EAAc,EAAE,EAGzD,OAAOA,CACT,EChCMC,EAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAsBtBC,EAAkB,MAC7BC,EAAgC,KACH,CAC7B,KAAM,CAAE,eAAAC,GAAmB,MAAMlB,EAG/B,CACA,MAAOe,EACP,UAAW,CAAE,OAAAE,CAAA,EACb,OAAQ,iBAAA,CACT,EAED,OAAOC,CACT,ECpCaC,EAA2B,CACtCC,EACAC,IACyB,CACzB,GAAIA,EAAM,kBAAoB,KAAM,CAClC,MAAMC,EAAWF,EAAY,KAC1BG,GACCA,EAAW,aAAe,QAC1BA,EAAW,kBAAoBF,EAAM,eAAA,EAGzC,GAAIC,EACF,OAAOA,CAEX,CAMA,OAJwBF,EAAY,KACjCG,GAAeA,EAAW,aAAe,WAAA,GAGlB,IAC5B,EChBMC,EAAqB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUdC,EAAW,MACtBC,GAC4B,CAC5B,KAAM,CAAE,SAAUC,CAAA,EAAW,MAAM3B,EAGjC,CACA,MAAOwB,EACP,UAAW,CAAE,MAAAE,CAAA,EACb,OAAQ,UAAA,CACT,EAED,OAAOC,CACT,ECvBO,MAAMC,CAA8C,CAMzD,YAAYnB,EAAeoB,EAAqB,CALhD,KAAS,qBAAuB,GAM9B,KAAK,KAAOpB,EACZ,KAAK,OAASoB,GAAM,OACpB,KAAK,QAAUA,GAAM,OACvB,CACF"}
@@ -66,6 +66,13 @@ type LogicFunctionEvent<TBody = object> = {
66
66
  userWorkspaceId: string | null;
67
67
  };
68
68
 
69
+ type LogicFunctionHttpResponse = {
70
+ __twentyHttpResponse: true;
71
+ body: unknown;
72
+ status?: number;
73
+ headers?: Record<string, string>;
74
+ };
75
+
69
76
  type InputJsonSchema = {
70
77
  type?: 'string' | 'number' | 'boolean' | 'object' | 'array' | 'integer' | 'null';
71
78
  description?: string;
@@ -136,6 +143,16 @@ type HttpRouteTriggerSettings = {
136
143
  forwardedRequestHeaders?: string[];
137
144
  };
138
145
 
146
+ type RunAgentInput = {
147
+ agentUniversalIdentifier: string;
148
+ prompt: string;
149
+ };
150
+ type RunAgentResult = {
151
+ result: object | null;
152
+ error: string | null;
153
+ success: boolean;
154
+ };
155
+
139
156
  type LogicFunctionHandler = (...args: any[]) => any | Promise<any>;
140
157
  type LogicFunctionConfig = Omit<LogicFunctionManifest, 'sourceHandlerPath' | 'builtHandlerPath' | 'builtHandlerChecksum' | 'handlerName'> & {
141
158
  handler: LogicFunctionHandler;
@@ -281,5 +298,19 @@ declare class AppConnectionAuthFailedError extends Error {
281
298
  constructor(connectionId: string);
282
299
  }
283
300
 
284
- export { AppConnectionAuthFailedError, ObjectRecordBaseEvent, ObjectRecordCreateEvent, ObjectRecordDeleteEvent, ObjectRecordDestroyEvent, ObjectRecordRestoreEvent, ObjectRecordUpdateEvent, ObjectRecordUpsertEvent, findConnectionForRequest, getConnection, listConnections };
285
- export type { AppConnection, CronPayload, DatabaseEventPayload, InputJsonSchema, InstallHandler, InstallPayload, ListConnectionsFilter, LogicFunctionConfig, LogicFunctionHandler, ObjectRecordEvent, LogicFunctionEvent as RoutePayload };
301
+ declare const runAgent: (input: RunAgentInput) => Promise<RunAgentResult>;
302
+
303
+ type ResponseInit = {
304
+ status?: number;
305
+ headers?: Record<string, string>;
306
+ };
307
+ declare class Response implements LogicFunctionHttpResponse {
308
+ readonly __twentyHttpResponse: true;
309
+ readonly body: unknown;
310
+ readonly status?: number;
311
+ readonly headers?: Record<string, string>;
312
+ constructor(body: unknown, init?: ResponseInit);
313
+ }
314
+
315
+ export { AppConnectionAuthFailedError, ObjectRecordBaseEvent, ObjectRecordCreateEvent, ObjectRecordDeleteEvent, ObjectRecordDestroyEvent, ObjectRecordRestoreEvent, ObjectRecordUpdateEvent, ObjectRecordUpsertEvent, Response, findConnectionForRequest, getConnection, listConnections, runAgent };
316
+ export type { AppConnection, CronPayload, DatabaseEventPayload, InputJsonSchema, InstallHandler, InstallPayload, ListConnectionsFilter, LogicFunctionConfig, LogicFunctionHandler, ObjectRecordEvent, ResponseInit, LogicFunctionEvent as RoutePayload, RunAgentInput, RunAgentResult };
@@ -1,53 +1,122 @@
1
- class a extends Error {
1
+ class d extends Error {
2
2
  constructor(e) {
3
3
  super(
4
4
  `App connection ${e} requires the user to reconnect (authFailedAt is set). Surface a "Reconnect" prompt in your UI.`
5
5
  ), this.name = "AppConnectionAuthFailedError", this.connectionId = e;
6
6
  }
7
7
  }
8
- const r = "TWENTY_API_URL", i = "TWENTY_APP_ACCESS_TOKEN", c = async (n, e) => {
9
- const s = process.env[r], t = process.env[i];
10
- if (!s || !t)
8
+ const c = "TWENTY_API_URL", p = "TWENTY_APP_ACCESS_TOKEN", a = async ({
9
+ query: t,
10
+ variables: e,
11
+ caller: n
12
+ }) => {
13
+ const s = process.env[c], r = process.env[p];
14
+ if (!s || !r)
11
15
  throw new Error(
12
- `${n === "list" ? "listConnections" : "getConnection"}() requires the app runtime env vars ${r} and ${i}.`
16
+ `${n}() requires the app runtime env vars ${c} and ${p}.`
13
17
  );
14
- const o = await fetch(`${s}/apps/connections/${n}`, {
18
+ const i = await fetch(`${s}/metadata`, {
15
19
  method: "POST",
16
20
  headers: {
17
21
  "Content-Type": "application/json",
18
- Authorization: `Bearer ${t}`
22
+ Authorization: `Bearer ${r}`
19
23
  },
20
- body: JSON.stringify(e)
24
+ body: JSON.stringify({ query: t, variables: e })
21
25
  });
22
- if (!o.ok)
26
+ if (!i.ok)
23
27
  throw new Error(
24
- `${n === "list" ? "listConnections" : "getConnection"}() failed: HTTP ${o.status} ${o.statusText}`
28
+ `${n}() failed: HTTP ${i.status} ${i.statusText}`
25
29
  );
26
- return await o.json();
27
- }, p = async (n) => {
28
- const e = await c("get", { id: n });
30
+ const o = await i.json();
31
+ if (o.errors && o.errors.length > 0)
32
+ throw new Error(
33
+ `${n}() failed: ${o.errors.map((u) => u.message).join(", ")}`
34
+ );
35
+ if (!o.data)
36
+ throw new Error(`${n}() failed: response contained no data.`);
37
+ return o.data;
38
+ }, l = `
39
+ query GetAppConnection($id: ID!) {
40
+ appConnection(id: $id) {
41
+ id
42
+ providerName
43
+ name
44
+ handle
45
+ visibility
46
+ userWorkspaceId
47
+ accessToken
48
+ scopes
49
+ authFailedAt
50
+ }
51
+ }
52
+ `, C = async (t) => {
53
+ const { appConnection: e } = await a({
54
+ query: l,
55
+ variables: { id: t },
56
+ caller: "getConnection"
57
+ });
29
58
  if (e.authFailedAt !== null)
30
- throw new a(e.id);
59
+ throw new d(e.id);
60
+ return e;
61
+ }, h = `
62
+ query ListAppConnections($filter: ListAppConnectionsInput) {
63
+ appConnections(filter: $filter) {
64
+ id
65
+ providerName
66
+ name
67
+ handle
68
+ visibility
69
+ userWorkspaceId
70
+ accessToken
71
+ scopes
72
+ authFailedAt
73
+ }
74
+ }
75
+ `, T = async (t = {}) => {
76
+ const { appConnections: e } = await a({
77
+ query: h,
78
+ variables: { filter: t },
79
+ caller: "listConnections"
80
+ });
31
81
  return e;
32
- }, u = async (n = {}) => c(
33
- "list",
34
- n
35
- ), l = (n, e) => {
82
+ }, y = (t, e) => {
36
83
  if (e.userWorkspaceId !== null) {
37
- const t = n.find(
38
- (o) => o.visibility === "user" && o.userWorkspaceId === e.userWorkspaceId
84
+ const s = t.find(
85
+ (r) => r.visibility === "user" && r.userWorkspaceId === e.userWorkspaceId
39
86
  );
40
- if (t)
41
- return t;
87
+ if (s)
88
+ return s;
42
89
  }
43
- return n.find(
44
- (t) => t.visibility === "workspace"
90
+ return t.find(
91
+ (s) => s.visibility === "workspace"
45
92
  ) ?? null;
93
+ }, A = `
94
+ mutation RunAgent($input: RunAgentInput!) {
95
+ runAgent(input: $input) {
96
+ result
97
+ error
98
+ success
99
+ }
100
+ }
101
+ `, f = async (t) => {
102
+ const { runAgent: e } = await a({
103
+ query: A,
104
+ variables: { input: t },
105
+ caller: "runAgent"
106
+ });
107
+ return e;
46
108
  };
109
+ class w {
110
+ constructor(e, n) {
111
+ this.__twentyHttpResponse = !0, this.body = e, this.status = n?.status, this.headers = n?.headers;
112
+ }
113
+ }
47
114
  export {
48
- a as AppConnectionAuthFailedError,
49
- l as findConnectionForRequest,
50
- p as getConnection,
51
- u as listConnections
115
+ d as AppConnectionAuthFailedError,
116
+ w as Response,
117
+ y as findConnectionForRequest,
118
+ C as getConnection,
119
+ T as listConnections,
120
+ f as runAgent
52
121
  };
53
122
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../../src/sdk/logic-function/connections/errors/app-connection-auth-failed.error.ts","../../../twenty-shared/dist/application.mjs","../../src/sdk/logic-function/connections/utils/post-connections-endpoint.util.ts","../../src/sdk/logic-function/connections/get-connection.ts","../../src/sdk/logic-function/connections/list-connections.ts","../../src/sdk/logic-function/connections/find-connection-for-request.ts"],"sourcesContent":["// Thrown when the platform asks the SDK to operate on a connection whose\n// OAuth refresh failed permanently (`authFailedAt` is set). The end user\n// must reconnect from the app's settings tab — the app cannot recover on\n// its own.\n//\n// `listConnections` filters these out by default (the user can't act on\n// them anyway). `getConnection` throws this when the looked-up connection\n// is in this state, so a stored connection id can be safely retried until\n// it works again.\nexport class AppConnectionAuthFailedError extends Error {\n readonly connectionId: string;\n\n constructor(connectionId: string) {\n super(\n `App connection ${connectionId} requires the user to reconnect ` +\n `(authFailedAt is set). Surface a \"Reconnect\" prompt in your UI.`,\n );\n this.name = 'AppConnectionAuthFailedError';\n this.connectionId = connectionId;\n }\n}\n","const _ = \"public\", A = \"TWENTY_API_KEY\", T = \"TWENTY_API_URL\", r = \"TWENTY_APP_ACCESS_TOKEN\", t = \"generated\", N = {\n js: `import { createRequire as __createRequire } from 'module';\nconst require = __createRequire(import.meta.url);`\n}, u = \".twenty/output\", I = \"Standard\", n = \"20202020-64aa-4b6f-b003-9c74b97cee20\";\nvar e = /* @__PURE__ */ ((o) => (o.Object = \"object\", o.Field = \"field\", o.LogicFunction = \"logicFunction\", o.FrontComponent = \"frontComponent\", o.Role = \"role\", o.Skill = \"skill\", o.Agent = \"agent\", o.ConnectionProvider = \"connectionProvider\", o.View = \"view\", o.NavigationMenuItem = \"navigationMenuItem\", o.PageLayout = \"pageLayout\", o.PageLayoutTab = \"pageLayoutTab\", o.CommandMenuItem = \"commandMenuItem\", o))(e || {});\nexport {\n _ as ASSETS_DIR,\n A as DEFAULT_API_KEY_NAME,\n T as DEFAULT_API_URL_NAME,\n r as DEFAULT_APP_ACCESS_TOKEN_NAME,\n t as GENERATED_DIR,\n N as NODE_ESM_CJS_BANNER,\n u as OUTPUT_DIR,\n e as SyncableEntity,\n I as TWENTY_STANDARD_APPLICATION_NAME,\n n as TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER\n};\n","import {\n DEFAULT_API_URL_NAME,\n DEFAULT_APP_ACCESS_TOKEN_NAME,\n} from 'twenty-shared/application';\n\n// Shared transport for `/apps/connections/*` endpoints. Centralises the\n// env-var check, auth header, and HTTP error translation so each helper\n// stays focused on its own input/output shape.\nexport const postConnectionsEndpoint = async <TBody, TResponse>(\n path: 'list' | 'get',\n body: TBody,\n): Promise<TResponse> => {\n const apiUrl = process.env[DEFAULT_API_URL_NAME];\n const accessToken = process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];\n\n if (!apiUrl || !accessToken) {\n throw new Error(\n `${path === 'list' ? 'listConnections' : 'getConnection'}() requires the app runtime env vars ` +\n `${DEFAULT_API_URL_NAME} and ${DEFAULT_APP_ACCESS_TOKEN_NAME}.`,\n );\n }\n\n const response = await fetch(`${apiUrl}/apps/connections/${path}`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n throw new Error(\n `${path === 'list' ? 'listConnections' : 'getConnection'}() failed: ` +\n `HTTP ${response.status} ${response.statusText}`,\n );\n }\n\n return (await response.json()) as TResponse;\n};\n","import { AppConnectionAuthFailedError } from '@/sdk/logic-function/connections/errors/app-connection-auth-failed.error';\nimport { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\nimport { postConnectionsEndpoint } from '@/sdk/logic-function/connections/utils/post-connections-endpoint.util';\n\n// Look up a single connection by id. The id is stable across reconnects\n// (the row keeps its id when the user clicks \"Reconnect\"), so apps can\n// safely persist it in their own data and call this helper on each\n// invocation to retrieve a fresh access token.\n//\n// Throws `AppConnectionAuthFailedError` if the credential is in a\n// permanent-failure state (the user must reconnect from the app's\n// settings tab). Throws a regular `Error` for any other failure\n// (network, not-found, transient refresh failure).\nexport const getConnection = async (id: string): Promise<AppConnection> => {\n const connection = await postConnectionsEndpoint<\n { id: string },\n AppConnection\n >('get', { id });\n\n if (connection.authFailedAt !== null) {\n throw new AppConnectionAuthFailedError(connection.id);\n }\n\n return connection;\n};\n","import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\nimport { postConnectionsEndpoint } from '@/sdk/logic-function/connections/utils/post-connections-endpoint.util';\n\nexport type ListConnectionsFilter = {\n // Provider name as declared on `defineConnectionProvider({ name })`.\n providerName?: string;\n // Restrict to credentials owned by a specific user. Useful in cron\n // triggers when picking a service-account user via app config.\n userWorkspaceId?: string;\n // Restrict by row visibility — 'user' (private) or 'workspace' (shared).\n visibility?: 'user' | 'workspace';\n};\n\n// Returns every connection owned by the running app, optionally filtered.\n// The server refreshes each access token on read, so the returned values\n// are usable immediately. When the running execution carries a user\n// context (HTTP-route trigger with `isAuthRequired`, tool calls, etc.),\n// `scope: 'user'` connections belonging to other users are filtered out\n// server-side. Cron and database-event triggers see all connections.\nexport const listConnections = async (\n filter: ListConnectionsFilter = {},\n): Promise<AppConnection[]> =>\n postConnectionsEndpoint<ListConnectionsFilter, AppConnection[]>(\n 'list',\n filter,\n );\n","import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\n\n// Resolution rule for an HTTP-route handler that wants \"the request user's\n// connection, or fall back to a workspace-shared one.\" Pure function — no\n// network. Pass it the result of `listConnections` and the trigger event.\n//\n// The plan-of-record for picking a connection is documented in the v3 plan\n// notes; this utility encodes the most common case so handlers don't have\n// to repeat the same `find(...) ?? find(...)` chain.\n//\n// Returns `null` when no candidate exists — caller decides whether that's\n// a 4xx for the end user or a hard error.\nexport const findConnectionForRequest = (\n connections: AppConnection[],\n event: { userWorkspaceId: string | null },\n): AppConnection | null => {\n // 1. Personal credential of the request user (highest specificity).\n if (event.userWorkspaceId !== null) {\n const personal = connections.find(\n (connection) =>\n connection.visibility === 'user' &&\n connection.userWorkspaceId === event.userWorkspaceId,\n );\n\n if (personal) {\n return personal;\n }\n }\n\n // 2. Any workspace-shared credential (team-managed service account).\n const workspaceShared = connections.find(\n (connection) => connection.visibility === 'workspace',\n );\n\n return workspaceShared ?? null;\n};\n"],"names":["AppConnectionAuthFailedError","connectionId","T","r","postConnectionsEndpoint","path","body","apiUrl","DEFAULT_API_URL_NAME","accessToken","DEFAULT_APP_ACCESS_TOKEN_NAME","response","getConnection","id","connection","listConnections","filter","findConnectionForRequest","connections","event","personal"],"mappings":"AASO,MAAMA,UAAqC,MAAM;AAAA,EAGtD,YAAYC,GAAsB;AAChC;AAAA,MACE,kBAAkBA,CAAY;AAAA,IAAA,GAGhC,KAAK,OAAO,gCACZ,KAAK,eAAeA;AAAA,EACtB;AACF;ACpBK,MAAqCC,IAAI,kBAAkBC,IAAI,2BCQvDC,IAA0B,OACrCC,GACAC,MACuB;AACvB,QAAMC,IAAS,QAAQ,IAAIC,CAAoB,GACzCC,IAAc,QAAQ,IAAIC,CAA6B;AAE7D,MAAI,CAACH,KAAU,CAACE;AACd,UAAM,IAAI;AAAA,MACR,GAAGJ,MAAS,SAAS,oBAAoB,eAAe,wCACnDG,CAAoB,QAAQE,CAA6B;AAAA,IAAA;AAIlE,QAAMC,IAAW,MAAM,MAAM,GAAGJ,CAAM,qBAAqBF,CAAI,IAAI;AAAA,IACjE,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAUI,CAAW;AAAA,IAAA;AAAA,IAEtC,MAAM,KAAK,UAAUH,CAAI;AAAA,EAAA,CAC1B;AAED,MAAI,CAACK,EAAS;AACZ,UAAM,IAAI;AAAA,MACR,GAAGN,MAAS,SAAS,oBAAoB,eAAe,mBAC9CM,EAAS,MAAM,IAAIA,EAAS,UAAU;AAAA,IAAA;AAIpD,SAAQ,MAAMA,EAAS,KAAA;AACzB,GC1BaC,IAAgB,OAAOC,MAAuC;AACzE,QAAMC,IAAa,MAAMV,EAGvB,OAAO,EAAE,IAAAS,GAAI;AAEf,MAAIC,EAAW,iBAAiB;AAC9B,UAAM,IAAId,EAA6Bc,EAAW,EAAE;AAGtD,SAAOA;AACT,GCLaC,IAAkB,OAC7BC,IAAgC,CAAA,MAEhCZ;AAAA,EACE;AAAA,EACAY;AACF,GCbWC,IAA2B,CACtCC,GACAC,MACyB;AAEzB,MAAIA,EAAM,oBAAoB,MAAM;AAClC,UAAMC,IAAWF,EAAY;AAAA,MAC3B,CAACJ,MACCA,EAAW,eAAe,UAC1BA,EAAW,oBAAoBK,EAAM;AAAA,IAAA;AAGzC,QAAIC;AACF,aAAOA;AAAA,EAEX;AAOA,SAJwBF,EAAY;AAAA,IAClC,CAACJ,MAAeA,EAAW,eAAe;AAAA,EAAA,KAGlB;AAC5B;"}
1
+ {"version":3,"file":"index.mjs","sources":["../../src/sdk/logic-function/connections/errors/app-connection-auth-failed.error.ts","../../../twenty-shared/dist/application.mjs","../../src/sdk/logic-function/utils/post-graphql-request.util.ts","../../src/sdk/logic-function/connections/get-connection.ts","../../src/sdk/logic-function/connections/list-connections.ts","../../src/sdk/logic-function/connections/find-connection-for-request.ts","../../src/sdk/logic-function/agents/run-agent.ts","../../src/sdk/logic-function/response.ts"],"sourcesContent":["// Thrown when the platform asks the SDK to operate on a connection whose\n// OAuth refresh failed permanently (`authFailedAt` is set). The end user\n// must reconnect from the app's settings tab — the app cannot recover on\n// its own.\n//\n// `listConnections` filters these out by default (the user can't act on\n// them anyway). `getConnection` throws this when the looked-up connection\n// is in this state, so a stored connection id can be safely retried until\n// it works again.\nexport class AppConnectionAuthFailedError extends Error {\n readonly connectionId: string;\n\n constructor(connectionId: string) {\n super(\n `App connection ${connectionId} requires the user to reconnect ` +\n `(authFailedAt is set). Surface a \"Reconnect\" prompt in your UI.`,\n );\n this.name = 'AppConnectionAuthFailedError';\n this.connectionId = connectionId;\n }\n}\n","const _ = \"public\", A = \"TWENTY_API_KEY\", T = \"TWENTY_API_URL\", r = \"TWENTY_APP_ACCESS_TOKEN\", N = \"generated\", t = {\n js: `import { createRequire as __createRequire } from 'module';\nconst require = __createRequire(import.meta.url);`\n}, u = \".twenty/output\", I = \"Standard\", P = \"20202020-64aa-4b6f-b003-9c74b97cee20\";\nvar o = /* @__PURE__ */ ((e) => (e.Object = \"object\", e.Field = \"field\", e.LogicFunction = \"logicFunction\", e.FrontComponent = \"frontComponent\", e.Role = \"role\", e.Skill = \"skill\", e.Agent = \"agent\", e.ConnectionProvider = \"connectionProvider\", e.View = \"view\", e.ViewField = \"viewField\", e.NavigationMenuItem = \"navigationMenuItem\", e.PageLayout = \"pageLayout\", e.PageLayoutTab = \"pageLayoutTab\", e.CommandMenuItem = \"commandMenuItem\", e))(o || {});\nexport {\n _ as ASSETS_DIR,\n A as DEFAULT_API_KEY_NAME,\n T as DEFAULT_API_URL_NAME,\n r as DEFAULT_APP_ACCESS_TOKEN_NAME,\n N as GENERATED_DIR,\n t as NODE_ESM_CJS_BANNER,\n u as OUTPUT_DIR,\n o as SyncableEntity,\n I as TWENTY_STANDARD_APPLICATION_NAME,\n P as TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER\n};\n","import {\n DEFAULT_API_URL_NAME,\n DEFAULT_APP_ACCESS_TOKEN_NAME,\n} from 'twenty-shared/application';\n\nexport const postGraphqlRequest = async <TVariables, TData>({\n query,\n variables,\n caller,\n}: {\n query: string;\n variables: TVariables;\n caller: string;\n}): Promise<TData> => {\n const apiUrl = process.env[DEFAULT_API_URL_NAME];\n const accessToken = process.env[DEFAULT_APP_ACCESS_TOKEN_NAME];\n\n if (!apiUrl || !accessToken) {\n throw new Error(\n `${caller}() requires the app runtime env vars ` +\n `${DEFAULT_API_URL_NAME} and ${DEFAULT_APP_ACCESS_TOKEN_NAME}.`,\n );\n }\n\n const response = await fetch(`${apiUrl}/metadata`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n },\n body: JSON.stringify({ query, variables }),\n });\n\n if (!response.ok) {\n throw new Error(\n `${caller}() failed: HTTP ${response.status} ${response.statusText}`,\n );\n }\n\n const body = (await response.json()) as {\n data?: TData;\n errors?: { message: string }[];\n };\n\n if (body.errors && body.errors.length > 0) {\n throw new Error(\n `${caller}() failed: ${body.errors.map((error) => error.message).join(', ')}`,\n );\n }\n\n if (!body.data) {\n throw new Error(`${caller}() failed: response contained no data.`);\n }\n\n return body.data;\n};\n","import { AppConnectionAuthFailedError } from '@/sdk/logic-function/connections/errors/app-connection-auth-failed.error';\nimport { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\nimport { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';\n\nconst GET_APP_CONNECTION_QUERY = `\n query GetAppConnection($id: ID!) {\n appConnection(id: $id) {\n id\n providerName\n name\n handle\n visibility\n userWorkspaceId\n accessToken\n scopes\n authFailedAt\n }\n }\n`;\n\nexport const getConnection = async (id: string): Promise<AppConnection> => {\n const { appConnection } = await postGraphqlRequest<\n { id: string },\n { appConnection: AppConnection }\n >({\n query: GET_APP_CONNECTION_QUERY,\n variables: { id },\n caller: 'getConnection',\n });\n\n if (appConnection.authFailedAt !== null) {\n throw new AppConnectionAuthFailedError(appConnection.id);\n }\n\n return appConnection;\n};\n","import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\nimport { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';\n\nconst LIST_APP_CONNECTIONS_QUERY = `\n query ListAppConnections($filter: ListAppConnectionsInput) {\n appConnections(filter: $filter) {\n id\n providerName\n name\n handle\n visibility\n userWorkspaceId\n accessToken\n scopes\n authFailedAt\n }\n }\n`;\n\nexport type ListConnectionsFilter = {\n providerName?: string;\n userWorkspaceId?: string;\n visibility?: 'user' | 'workspace';\n};\n\nexport const listConnections = async (\n filter: ListConnectionsFilter = {},\n): Promise<AppConnection[]> => {\n const { appConnections } = await postGraphqlRequest<\n { filter: ListConnectionsFilter },\n { appConnections: AppConnection[] }\n >({\n query: LIST_APP_CONNECTIONS_QUERY,\n variables: { filter },\n caller: 'listConnections',\n });\n\n return appConnections;\n};\n","import { type AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';\n\nexport const findConnectionForRequest = (\n connections: AppConnection[],\n event: { userWorkspaceId: string | null },\n): AppConnection | null => {\n if (event.userWorkspaceId !== null) {\n const personal = connections.find(\n (connection) =>\n connection.visibility === 'user' &&\n connection.userWorkspaceId === event.userWorkspaceId,\n );\n\n if (personal) {\n return personal;\n }\n }\n\n const workspaceShared = connections.find(\n (connection) => connection.visibility === 'workspace',\n );\n\n return workspaceShared ?? null;\n};\n","import {\n type RunAgentInput,\n type RunAgentResult,\n} from 'twenty-shared/application';\n\nimport { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';\n\nconst RUN_AGENT_MUTATION = `\n mutation RunAgent($input: RunAgentInput!) {\n runAgent(input: $input) {\n result\n error\n success\n }\n }\n`;\n\nexport const runAgent = async (\n input: RunAgentInput,\n): Promise<RunAgentResult> => {\n const { runAgent: result } = await postGraphqlRequest<\n { input: RunAgentInput },\n { runAgent: RunAgentResult }\n >({\n query: RUN_AGENT_MUTATION,\n variables: { input },\n caller: 'runAgent',\n });\n\n return result;\n};\n","import { type LogicFunctionHttpResponse } from 'twenty-shared/types';\n\nexport type ResponseInit = {\n status?: number;\n headers?: Record<string, string>;\n};\n\nexport class Response implements LogicFunctionHttpResponse {\n readonly __twentyHttpResponse = true as const;\n readonly body: unknown;\n readonly status?: number;\n readonly headers?: Record<string, string>;\n\n constructor(body: unknown, init?: ResponseInit) {\n this.body = body;\n this.status = init?.status;\n this.headers = init?.headers;\n }\n}\n"],"names":["AppConnectionAuthFailedError","connectionId","T","r","postGraphqlRequest","query","variables","caller","apiUrl","DEFAULT_API_URL_NAME","accessToken","DEFAULT_APP_ACCESS_TOKEN_NAME","response","body","error","GET_APP_CONNECTION_QUERY","getConnection","id","appConnection","LIST_APP_CONNECTIONS_QUERY","listConnections","filter","appConnections","findConnectionForRequest","connections","event","personal","connection","RUN_AGENT_MUTATION","runAgent","input","result","Response","init"],"mappings":"AASO,MAAMA,UAAqC,MAAM;AAAA,EAGtD,YAAYC,GAAsB;AAChC;AAAA,MACE,kBAAkBA,CAAY;AAAA,IAAA,GAGhC,KAAK,OAAO,gCACZ,KAAK,eAAeA;AAAA,EACtB;AACF;ACpBK,MAAqCC,IAAI,kBAAkBC,IAAI,2BCKvDC,IAAqB,OAA0B;AAAA,EAC1D,OAAAC;AAAA,EACA,WAAAC;AAAA,EACA,QAAAC;AACF,MAIsB;AACpB,QAAMC,IAAS,QAAQ,IAAIC,CAAoB,GACzCC,IAAc,QAAQ,IAAIC,CAA6B;AAE7D,MAAI,CAACH,KAAU,CAACE;AACd,UAAM,IAAI;AAAA,MACR,GAAGH,CAAM,wCACJE,CAAoB,QAAQE,CAA6B;AAAA,IAAA;AAIlE,QAAMC,IAAW,MAAM,MAAM,GAAGJ,CAAM,aAAa;AAAA,IACjD,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,gBAAgB;AAAA,MAChB,eAAe,UAAUE,CAAW;AAAA,IAAA;AAAA,IAEtC,MAAM,KAAK,UAAU,EAAE,OAAAL,GAAO,WAAAC,GAAW;AAAA,EAAA,CAC1C;AAED,MAAI,CAACM,EAAS;AACZ,UAAM,IAAI;AAAA,MACR,GAAGL,CAAM,mBAAmBK,EAAS,MAAM,IAAIA,EAAS,UAAU;AAAA,IAAA;AAItE,QAAMC,IAAQ,MAAMD,EAAS,KAAA;AAK7B,MAAIC,EAAK,UAAUA,EAAK,OAAO,SAAS;AACtC,UAAM,IAAI;AAAA,MACR,GAAGN,CAAM,cAAcM,EAAK,OAAO,IAAI,CAACC,MAAUA,EAAM,OAAO,EAAE,KAAK,IAAI,CAAC;AAAA,IAAA;AAI/E,MAAI,CAACD,EAAK;AACR,UAAM,IAAI,MAAM,GAAGN,CAAM,wCAAwC;AAGnE,SAAOM,EAAK;AACd,GCnDME,IAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAgBpBC,IAAgB,OAAOC,MAAuC;AACzE,QAAM,EAAE,eAAAC,MAAkB,MAAMd,EAG9B;AAAA,IACA,OAAOW;AAAA,IACP,WAAW,EAAE,IAAAE,EAAA;AAAA,IACb,QAAQ;AAAA,EAAA,CACT;AAED,MAAIC,EAAc,iBAAiB;AACjC,UAAM,IAAIlB,EAA6BkB,EAAc,EAAE;AAGzD,SAAOA;AACT,GChCMC,IAA6B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAsBtBC,IAAkB,OAC7BC,IAAgC,OACH;AAC7B,QAAM,EAAE,gBAAAC,MAAmB,MAAMlB,EAG/B;AAAA,IACA,OAAOe;AAAA,IACP,WAAW,EAAE,QAAAE,EAAA;AAAA,IACb,QAAQ;AAAA,EAAA,CACT;AAED,SAAOC;AACT,GCpCaC,IAA2B,CACtCC,GACAC,MACyB;AACzB,MAAIA,EAAM,oBAAoB,MAAM;AAClC,UAAMC,IAAWF,EAAY;AAAA,MAC3B,CAACG,MACCA,EAAW,eAAe,UAC1BA,EAAW,oBAAoBF,EAAM;AAAA,IAAA;AAGzC,QAAIC;AACF,aAAOA;AAAA,EAEX;AAMA,SAJwBF,EAAY;AAAA,IAClC,CAACG,MAAeA,EAAW,eAAe;AAAA,EAAA,KAGlB;AAC5B,GChBMC,IAAqB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,GAUdC,IAAW,OACtBC,MAC4B;AAC5B,QAAM,EAAE,UAAUC,EAAA,IAAW,MAAM3B,EAGjC;AAAA,IACA,OAAOwB;AAAA,IACP,WAAW,EAAE,OAAAE,EAAA;AAAA,IACb,QAAQ;AAAA,EAAA,CACT;AAED,SAAOC;AACT;ACvBO,MAAMC,EAA8C;AAAA,EAMzD,YAAYnB,GAAeoB,GAAqB;AALhD,SAAS,uBAAuB,IAM9B,KAAK,OAAOpB,GACZ,KAAK,SAASoB,GAAM,QACpB,KAAK,UAAUA,GAAM;AAAA,EACvB;AACF;"}