mirror of
https://github.com/langgenius/dify.git
synced 2026-07-21 10:38:32 +08:00
refactor(web): migrate trigger console contracts (#38255)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
This commit is contained in:
parent
f98c6cb2a6
commit
6eb9928df7
@ -1,5 +1,5 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
from typing import Any, Literal
|
||||
|
||||
from flask import make_response, redirect, request
|
||||
from flask_restx import Resource
|
||||
@ -11,8 +11,10 @@ from configs import dify_config
|
||||
from controllers.common.errors import NotFoundError
|
||||
from controllers.common.fields import BinaryFileResponse, RedirectResponse, SimpleResultResponse
|
||||
from controllers.common.schema import register_response_schema_models, register_schema_models
|
||||
from core.entities.parameter_entities import AppSelectorScope, ModelSelectorScope, ToolSelectorScope
|
||||
from core.plugin.entities.plugin_daemon import CredentialType
|
||||
from core.plugin.impl.oauth import OAuthHandler
|
||||
from core.tools.entities.common_entities import I18nObject
|
||||
from core.trigger.entities.api_entities import (
|
||||
SubscriptionBuilderApiEntity,
|
||||
TriggerProviderApiEntity,
|
||||
@ -79,11 +81,38 @@ class TriggerOAuthAuthorizeResponse(BaseModel):
|
||||
subscription_builder: SubscriptionBuilderApiEntity
|
||||
|
||||
|
||||
class TriggerProviderConfigOptionResponse(BaseModel):
|
||||
value: str = Field(..., description="The value of the option")
|
||||
label: I18nObject = Field(..., description="The label of the option")
|
||||
|
||||
|
||||
class TriggerProviderConfigResponse(BaseModel):
|
||||
type: Literal[
|
||||
"secret-input",
|
||||
"text-input",
|
||||
"select",
|
||||
"boolean",
|
||||
"app-selector",
|
||||
"model-selector",
|
||||
"array[tools]",
|
||||
] = Field(..., description="The type of the credentials")
|
||||
name: str = Field(..., description="The name of the credentials")
|
||||
scope: AppSelectorScope | ModelSelectorScope | ToolSelectorScope | None = None
|
||||
required: bool = False
|
||||
default: int | str | float | bool | None = None
|
||||
options: list[TriggerProviderConfigOptionResponse] | None = None
|
||||
multiple: bool = False
|
||||
label: I18nObject | None = None
|
||||
help: I18nObject | None = None
|
||||
url: str | None = None
|
||||
placeholder: I18nObject | None = None
|
||||
|
||||
|
||||
class TriggerOAuthClientResponse(BaseModel):
|
||||
configured: bool
|
||||
system_configured: bool
|
||||
custom_configured: bool
|
||||
oauth_client_schema: Any
|
||||
oauth_client_schema: list[TriggerProviderConfigResponse]
|
||||
custom_enabled: bool
|
||||
redirect_uri: str
|
||||
params: dict[str, Any]
|
||||
@ -724,7 +753,7 @@ class TriggerOAuthClientManageApi(Resource):
|
||||
)
|
||||
class TriggerSubscriptionVerifyApi(Resource):
|
||||
@console_ns.expect(console_ns.models[TriggerSubscriptionBuilderVerifyPayload.__name__])
|
||||
@console_ns.response(200, "Success", console_ns.models[TriggerProviderOpaqueResponse.__name__])
|
||||
@console_ns.response(200, "Success", console_ns.models[TriggerSubscriptionBuilderVerifyResponse.__name__])
|
||||
@setup_required
|
||||
@login_required
|
||||
@edit_permission_required
|
||||
|
||||
@ -12396,7 +12396,7 @@ Returns permission flags that control workspace features like member invitations
|
||||
|
||||
| Code | Description | Schema |
|
||||
| ---- | ----------- | ------ |
|
||||
| 200 | Success | **application/json**: [TriggerProviderOpaqueResponse](#triggerprovideropaqueresponse)<br> |
|
||||
| 200 | Success | **application/json**: [TriggerSubscriptionBuilderVerifyResponse](#triggersubscriptionbuilderverifyresponse)<br> |
|
||||
|
||||
### [POST] /workspaces/current/trigger-provider/{subscription_id}/subscriptions/delete
|
||||
**Delete a subscription instance**
|
||||
@ -21513,7 +21513,7 @@ Enum class for tool provider
|
||||
| configured | boolean | | Yes |
|
||||
| custom_configured | boolean | | Yes |
|
||||
| custom_enabled | boolean | | Yes |
|
||||
| oauth_client_schema | | | Yes |
|
||||
| oauth_client_schema | [ [TriggerProviderConfigResponse](#triggerproviderconfigresponse) ] | | Yes |
|
||||
| params | object | | Yes |
|
||||
| redirect_uri | string | | Yes |
|
||||
| system_configured | boolean | | Yes |
|
||||
@ -21536,6 +21536,29 @@ Enum class for tool provider
|
||||
| supported_creation_methods | [ [TriggerCreationMethod](#triggercreationmethod) ] | Supported creation methods for the trigger provider. like 'OAUTH', 'APIKEY', 'MANUAL'. | No |
|
||||
| tags | [ string ] | The tags of the trigger provider | No |
|
||||
|
||||
#### TriggerProviderConfigOptionResponse
|
||||
|
||||
| Name | Type | Description | Required |
|
||||
| ---- | ---- | ----------- | -------- |
|
||||
| label | [I18nObject](#i18nobject) | The label of the option | Yes |
|
||||
| value | string | The value of the option | Yes |
|
||||
|
||||
#### TriggerProviderConfigResponse
|
||||
|
||||
| Name | Type | Description | Required |
|
||||
| ---- | ---- | ----------- | -------- |
|
||||
| default | integer<br>string<br>number<br>boolean | | No |
|
||||
| help | [I18nObject](#i18nobject) | | No |
|
||||
| label | [I18nObject](#i18nobject) | | No |
|
||||
| multiple | boolean | | No |
|
||||
| name | string | The name of the credentials | Yes |
|
||||
| options | [ [TriggerProviderConfigOptionResponse](#triggerproviderconfigoptionresponse) ] | | No |
|
||||
| placeholder | [I18nObject](#i18nobject) | | No |
|
||||
| required | boolean | | No |
|
||||
| scope | [AppSelectorScope](#appselectorscope)<br>[ModelSelectorScope](#modelselectorscope)<br>[ToolSelectorScope](#toolselectorscope) | | No |
|
||||
| type | string, <br>**Available values:** "app-selector", "array[tools]", "boolean", "model-selector", "secret-input", "select", "text-input" | The type of the credentials<br>*Enum:* `"app-selector"`, `"array[tools]"`, `"boolean"`, `"model-selector"`, `"secret-input"`, `"select"`, `"text-input"` | Yes |
|
||||
| url | string | | No |
|
||||
|
||||
#### TriggerProviderListResponse
|
||||
|
||||
| Name | Type | Description | Required |
|
||||
|
||||
@ -7367,11 +7367,6 @@
|
||||
"count": 1
|
||||
}
|
||||
},
|
||||
"web/service/use-triggers.ts": {
|
||||
"no-restricted-imports": {
|
||||
"count": 1
|
||||
}
|
||||
},
|
||||
"web/service/use-workflow.ts": {
|
||||
"@tanstack/query/exhaustive-deps": {
|
||||
"count": 1
|
||||
|
||||
@ -824,7 +824,7 @@ export type TriggerOAuthClientResponse = {
|
||||
configured: boolean
|
||||
custom_configured: boolean
|
||||
custom_enabled: boolean
|
||||
oauth_client_schema: unknown
|
||||
oauth_client_schema: Array<TriggerProviderConfigResponse>
|
||||
params: {
|
||||
[key: string]: unknown
|
||||
}
|
||||
@ -1342,6 +1342,27 @@ export type ProviderConfig = {
|
||||
|
||||
export type TriggerCreationMethod = 'APIKEY' | 'MANUAL' | 'OAUTH'
|
||||
|
||||
export type TriggerProviderConfigResponse = {
|
||||
default?: number | string | number | boolean | null
|
||||
help?: I18nObject | null
|
||||
label?: I18nObject | null
|
||||
multiple?: boolean
|
||||
name: string
|
||||
options?: Array<TriggerProviderConfigOptionResponse> | null
|
||||
placeholder?: I18nObject | null
|
||||
required?: boolean
|
||||
scope?: AppSelectorScope | ModelSelectorScope | ToolSelectorScope | null
|
||||
type:
|
||||
| 'app-selector'
|
||||
| 'array[tools]'
|
||||
| 'boolean'
|
||||
| 'model-selector'
|
||||
| 'secret-input'
|
||||
| 'select'
|
||||
| 'text-input'
|
||||
url?: string | null
|
||||
}
|
||||
|
||||
export type RequestLog = {
|
||||
created_at: string
|
||||
endpoint: string
|
||||
@ -1628,6 +1649,11 @@ export type CoreEntitiesProviderEntitiesBasicProviderConfigType
|
||||
| 'select'
|
||||
| 'text-input'
|
||||
|
||||
export type TriggerProviderConfigOptionResponse = {
|
||||
label: I18nObject
|
||||
value: string
|
||||
}
|
||||
|
||||
export type AiModelEntityResponse = {
|
||||
deprecated?: boolean
|
||||
features?: Array<ModelFeature> | null
|
||||
@ -4817,7 +4843,7 @@ export type PostWorkspacesCurrentTriggerProviderByProviderSubscriptionsVerifyByS
|
||||
|
||||
export type PostWorkspacesCurrentTriggerProviderByProviderSubscriptionsVerifyBySubscriptionIdResponses
|
||||
= {
|
||||
200: TriggerProviderOpaqueResponse
|
||||
200: TriggerSubscriptionBuilderVerifyResponse
|
||||
}
|
||||
|
||||
export type PostWorkspacesCurrentTriggerProviderByProviderSubscriptionsVerifyBySubscriptionIdResponse
|
||||
|
||||
@ -614,19 +614,6 @@ export const zWorkflowToolDeletePayload = z.object({
|
||||
workflow_tool_id: z.string(),
|
||||
})
|
||||
|
||||
/**
|
||||
* TriggerOAuthClientResponse
|
||||
*/
|
||||
export const zTriggerOAuthClientResponse = z.object({
|
||||
configured: z.boolean(),
|
||||
custom_configured: z.boolean(),
|
||||
custom_enabled: z.boolean(),
|
||||
oauth_client_schema: z.unknown(),
|
||||
params: z.record(z.string(), z.unknown()),
|
||||
redirect_uri: z.string(),
|
||||
system_configured: z.boolean(),
|
||||
})
|
||||
|
||||
/**
|
||||
* TriggerOAuthClientPayload
|
||||
*/
|
||||
@ -2024,6 +2011,52 @@ export const zOAuthSchema = z.object({
|
||||
credentials_schema: z.array(zProviderConfig).optional(),
|
||||
})
|
||||
|
||||
/**
|
||||
* TriggerProviderConfigOptionResponse
|
||||
*/
|
||||
export const zTriggerProviderConfigOptionResponse = z.object({
|
||||
label: zI18nObject,
|
||||
value: z.string(),
|
||||
})
|
||||
|
||||
/**
|
||||
* TriggerProviderConfigResponse
|
||||
*/
|
||||
export const zTriggerProviderConfigResponse = z.object({
|
||||
default: z.union([z.int(), z.string(), z.number(), z.boolean()]).nullish(),
|
||||
help: zI18nObject.nullish(),
|
||||
label: zI18nObject.nullish(),
|
||||
multiple: z.boolean().optional().default(false),
|
||||
name: z.string(),
|
||||
options: z.array(zTriggerProviderConfigOptionResponse).nullish(),
|
||||
placeholder: zI18nObject.nullish(),
|
||||
required: z.boolean().optional().default(false),
|
||||
scope: z.union([zAppSelectorScope, zModelSelectorScope, zToolSelectorScope]).nullish(),
|
||||
type: z.enum([
|
||||
'app-selector',
|
||||
'array[tools]',
|
||||
'boolean',
|
||||
'model-selector',
|
||||
'secret-input',
|
||||
'select',
|
||||
'text-input',
|
||||
]),
|
||||
url: z.string().nullish(),
|
||||
})
|
||||
|
||||
/**
|
||||
* TriggerOAuthClientResponse
|
||||
*/
|
||||
export const zTriggerOAuthClientResponse = z.object({
|
||||
configured: z.boolean(),
|
||||
custom_configured: z.boolean(),
|
||||
custom_enabled: z.boolean(),
|
||||
oauth_client_schema: z.array(zTriggerProviderConfigResponse),
|
||||
params: z.record(z.string(), z.unknown()),
|
||||
redirect_uri: z.string(),
|
||||
system_configured: z.boolean(),
|
||||
})
|
||||
|
||||
/**
|
||||
* UnaddedModelConfiguration
|
||||
*
|
||||
@ -4327,7 +4360,7 @@ export const zPostWorkspacesCurrentTriggerProviderByProviderSubscriptionsVerifyB
|
||||
* Success
|
||||
*/
|
||||
export const zPostWorkspacesCurrentTriggerProviderByProviderSubscriptionsVerifyBySubscriptionIdResponse
|
||||
= zTriggerProviderOpaqueResponse
|
||||
= zTriggerSubscriptionBuilderVerifyResponse
|
||||
|
||||
export const zPostWorkspacesCurrentTriggerProviderBySubscriptionIdSubscriptionsDeletePath
|
||||
= z.object({
|
||||
|
||||
@ -1,137 +0,0 @@
|
||||
import type {
|
||||
TriggerLogEntity,
|
||||
TriggerOAuthClientParams,
|
||||
TriggerOAuthConfig,
|
||||
TriggerProviderApiEntity,
|
||||
TriggerSubscription,
|
||||
TriggerSubscriptionBuilder,
|
||||
} from '@/app/components/workflow/block-selector/types'
|
||||
import { type } from '@orpc/contract'
|
||||
import { base } from '../base'
|
||||
|
||||
export const triggersContract = base
|
||||
.route({ path: '/workspaces/current/triggers', method: 'GET' })
|
||||
.input(type<{ query?: { type?: string } }>())
|
||||
.output(type<TriggerProviderApiEntity[]>())
|
||||
|
||||
export const triggerProviderInfoContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/info', method: 'GET' })
|
||||
.input(type<{ params: { provider: string } }>())
|
||||
.output(type<TriggerProviderApiEntity>())
|
||||
|
||||
export const triggerSubscriptionsContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/subscriptions/list', method: 'GET' })
|
||||
.input(type<{ params: { provider: string } }>())
|
||||
.output(type<TriggerSubscription[]>())
|
||||
|
||||
export const triggerSubscriptionBuilderCreateContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/subscriptions/builder/create', method: 'POST' })
|
||||
.input(type<{
|
||||
params: { provider: string }
|
||||
body?: { credential_type?: string }
|
||||
}>())
|
||||
.output(type<{ subscription_builder: TriggerSubscriptionBuilder }>())
|
||||
|
||||
export const triggerSubscriptionBuilderUpdateContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/subscriptions/builder/update/{subscriptionBuilderId}', method: 'POST' })
|
||||
.input(type<{
|
||||
params: { provider: string, subscriptionBuilderId: string }
|
||||
body?: {
|
||||
name?: string
|
||||
properties?: Record<string, unknown>
|
||||
parameters?: Record<string, unknown>
|
||||
credentials?: Record<string, unknown>
|
||||
}
|
||||
}>())
|
||||
.output(type<TriggerSubscriptionBuilder>())
|
||||
|
||||
export const triggerSubscriptionBuilderVerifyUpdateContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/subscriptions/builder/verify-and-update/{subscriptionBuilderId}', method: 'POST' })
|
||||
.input(type<{
|
||||
params: { provider: string, subscriptionBuilderId: string }
|
||||
body?: { credentials?: Record<string, unknown> }
|
||||
}>())
|
||||
.output(type<{ verified: boolean }>())
|
||||
|
||||
export const triggerSubscriptionVerifyContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/subscriptions/verify/{subscriptionId}', method: 'POST' })
|
||||
.input(type<{
|
||||
params: { provider: string, subscriptionId: string }
|
||||
body?: { credentials?: Record<string, unknown> }
|
||||
}>())
|
||||
.output(type<{ verified: boolean }>())
|
||||
|
||||
export const triggerSubscriptionBuildContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/subscriptions/builder/build/{subscriptionBuilderId}', method: 'POST' })
|
||||
.input(type<{
|
||||
params: { provider: string, subscriptionBuilderId: string }
|
||||
body?: {
|
||||
name?: string
|
||||
parameters?: Record<string, unknown>
|
||||
}
|
||||
}>())
|
||||
.output(type<unknown>())
|
||||
|
||||
export const triggerSubscriptionDeleteContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{subscriptionId}/subscriptions/delete', method: 'POST' })
|
||||
.input(type<{ params: { subscriptionId: string } }>())
|
||||
.output(type<{ result: string }>())
|
||||
|
||||
export const triggerSubscriptionUpdateContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{subscriptionId}/subscriptions/update', method: 'POST' })
|
||||
.input(type<{
|
||||
params: { subscriptionId: string }
|
||||
body?: {
|
||||
name?: string
|
||||
properties?: Record<string, unknown>
|
||||
parameters?: Record<string, unknown>
|
||||
credentials?: Record<string, unknown>
|
||||
}
|
||||
}>())
|
||||
.output(type<{ result: string, id: string }>())
|
||||
|
||||
export const triggerSubscriptionBuilderLogsContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/subscriptions/builder/logs/{subscriptionBuilderId}', method: 'GET' })
|
||||
.input(type<{ params: { provider: string, subscriptionBuilderId: string } }>())
|
||||
.output(type<{ logs: TriggerLogEntity[] }>())
|
||||
|
||||
export const triggerOAuthConfigContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/oauth/client', method: 'GET' })
|
||||
.input(type<{ params: { provider: string } }>())
|
||||
.output(type<TriggerOAuthConfig>())
|
||||
|
||||
export const triggerOAuthConfigureContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/oauth/client', method: 'POST' })
|
||||
.input(type<{
|
||||
params: { provider: string }
|
||||
body: { client_params?: TriggerOAuthClientParams, enabled: boolean }
|
||||
}>())
|
||||
.output(type<{ result: string }>())
|
||||
|
||||
export const triggerOAuthDeleteContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/oauth/client', method: 'DELETE' })
|
||||
.input(type<{ params: { provider: string } }>())
|
||||
.output(type<{ result: string }>())
|
||||
|
||||
export const triggerOAuthInitiateContract = base
|
||||
.route({ path: '/workspaces/current/trigger-provider/{provider}/subscriptions/oauth/authorize', method: 'GET' })
|
||||
.input(type<{ params: { provider: string } }>())
|
||||
.output(type<{ authorization_url: string, subscription_builder: TriggerSubscriptionBuilder }>())
|
||||
|
||||
export const triggersRouterContract = {
|
||||
list: triggersContract,
|
||||
providerInfo: triggerProviderInfoContract,
|
||||
subscriptions: triggerSubscriptionsContract,
|
||||
subscriptionBuilderCreate: triggerSubscriptionBuilderCreateContract,
|
||||
subscriptionBuilderUpdate: triggerSubscriptionBuilderUpdateContract,
|
||||
subscriptionBuilderVerifyUpdate: triggerSubscriptionBuilderVerifyUpdateContract,
|
||||
subscriptionVerify: triggerSubscriptionVerifyContract,
|
||||
subscriptionBuild: triggerSubscriptionBuildContract,
|
||||
subscriptionDelete: triggerSubscriptionDeleteContract,
|
||||
subscriptionUpdate: triggerSubscriptionUpdateContract,
|
||||
subscriptionBuilderLogs: triggerSubscriptionBuilderLogsContract,
|
||||
oauthConfig: triggerOAuthConfigContract,
|
||||
oauthConfigure: triggerOAuthConfigureContract,
|
||||
oauthDelete: triggerOAuthDeleteContract,
|
||||
oauthInitiate: triggerOAuthInitiateContract,
|
||||
}
|
||||
@ -48,7 +48,6 @@ import { contract as enterpriseContract } from '@dify/contracts/enterprise/orpc.
|
||||
import { exploreRouterContract } from './console/explore'
|
||||
import { pluginsRouterContract } from './console/plugins'
|
||||
import { snippetsRouterContract } from './console/snippets'
|
||||
import { triggersRouterContract } from './console/trigger'
|
||||
import { trialAppsRouterContract } from './console/try-app'
|
||||
|
||||
const communityContract = {
|
||||
@ -106,6 +105,5 @@ export const consoleRouterContract = {
|
||||
explore: exploreRouterContract,
|
||||
plugins: pluginsRouterContract,
|
||||
snippets: snippetsRouterContract,
|
||||
triggers: triggersRouterContract,
|
||||
trialApps: trialAppsRouterContract,
|
||||
}
|
||||
|
||||
44
web/service/__tests__/use-triggers.spec.ts
Normal file
44
web/service/__tests__/use-triggers.spec.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import type { TriggerProviderApiEntity as GeneratedTriggerProvider } from '@dify/contracts/api/console/workspaces/types.gen'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { convertToTriggerWithProvider, normalizeTriggerProvider } from '../use-triggers'
|
||||
|
||||
const createGeneratedTriggerProvider = (): GeneratedTriggerProvider => ({
|
||||
author: 'Dify',
|
||||
name: 'github',
|
||||
label: { en_US: 'GitHub' },
|
||||
description: { en_US: 'GitHub trigger provider' },
|
||||
tags: ['source-control'],
|
||||
events: [
|
||||
{
|
||||
name: 'issue_created',
|
||||
identity: {
|
||||
author: 'Dify',
|
||||
name: 'issue_created',
|
||||
label: { en_US: 'Issue created' },
|
||||
provider: 'github',
|
||||
},
|
||||
description: { en_US: 'Issue created event' },
|
||||
parameters: [
|
||||
{
|
||||
name: 'retry_count',
|
||||
label: { en_US: 'Retry count' },
|
||||
type: 'number',
|
||||
default: 0,
|
||||
required: false,
|
||||
multiple: false,
|
||||
},
|
||||
],
|
||||
output_schema: {},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
describe('trigger provider normalization', () => {
|
||||
it('should preserve falsy event parameter defaults', () => {
|
||||
const normalizedProvider = normalizeTriggerProvider(createGeneratedTriggerProvider())
|
||||
const triggerWithProvider = convertToTriggerWithProvider(normalizedProvider)
|
||||
|
||||
expect(normalizedProvider.events[0]?.parameters[0]?.default).toBe(0)
|
||||
expect(triggerWithProvider.events[0]?.parameters[0]?.default).toBe(0)
|
||||
})
|
||||
})
|
||||
@ -16,7 +16,6 @@ const customConsoleContractLoaders: Record<string, () => Promise<AnyContractRout
|
||||
explore: () => import('@/contract/console/explore').then(({ exploreRouterContract }) => wrapConsoleContract('explore', exploreRouterContract)),
|
||||
plugins: () => import('@/contract/console/plugins').then(({ pluginsRouterContract }) => wrapConsoleContract('plugins', pluginsRouterContract)),
|
||||
snippets: () => import('@/contract/console/snippets').then(({ snippetsRouterContract }) => wrapConsoleContract('snippets', snippetsRouterContract)),
|
||||
triggers: () => import('@/contract/console/trigger').then(({ triggersRouterContract }) => wrapConsoleContract('triggers', triggersRouterContract)),
|
||||
trialApps: () => import('@/contract/console/try-app').then(({ trialAppsRouterContract }) => wrapConsoleContract('trialApps', trialAppsRouterContract)),
|
||||
}
|
||||
|
||||
|
||||
@ -1,22 +1,477 @@
|
||||
import type { FormOption } from '@/app/components/base/form/types'
|
||||
import type { ParametersSchema, PluginTriggerSubscriptionConstructor, TriggerEvent, TriggerEventParameter } from '@/app/components/plugins/types'
|
||||
import type {
|
||||
TriggerLogEntity,
|
||||
TriggerOAuthClientParams,
|
||||
TriggerOAuthConfig,
|
||||
TriggerProviderApiEntity,
|
||||
TriggerSubscription,
|
||||
TriggerSubscriptionBuilder,
|
||||
TriggerWithProvider,
|
||||
} from '@/app/components/workflow/block-selector/types'
|
||||
import { useMutation, useQuery } from '@tanstack/react-query'
|
||||
import { FormTypeEnum } from '@/app/components/base/form/types'
|
||||
import { SupportedCreationMethods } from '@/app/components/plugins/types'
|
||||
import { CollectionType } from '@/app/components/tools/types'
|
||||
import { TriggerCredentialTypeEnum } from '@/app/components/workflow/block-selector/types'
|
||||
import { consoleClient, consoleQuery } from '@/service/client'
|
||||
import { get, post } from './base'
|
||||
import { useInvalid } from './use-base'
|
||||
|
||||
const NAME_SPACE = 'triggers'
|
||||
|
||||
const convertToTriggerWithProvider = (provider: TriggerProviderApiEntity): TriggerWithProvider => {
|
||||
type GeneratedEventParameter = import('@dify/contracts/api/console/workspaces/types.gen').EventParameter
|
||||
type GeneratedI18nObject = import('@dify/contracts/api/console/workspaces/types.gen').I18nObject
|
||||
type GeneratedProviderConfig = import('@dify/contracts/api/console/workspaces/types.gen').ProviderConfig
|
||||
type GeneratedRequestLog = import('@dify/contracts/api/console/workspaces/types.gen').RequestLog
|
||||
type GeneratedSubscriptionBuilder = import('@dify/contracts/api/console/workspaces/types.gen').SubscriptionBuilderApiEntity
|
||||
type GeneratedTriggerCreationMethod = import('@dify/contracts/api/console/workspaces/types.gen').TriggerCreationMethod
|
||||
type GeneratedTriggerOAuthConfig = import('@dify/contracts/api/console/workspaces/types.gen').TriggerOAuthClientResponse
|
||||
type GeneratedTriggerProvider = import('@dify/contracts/api/console/workspaces/types.gen').TriggerProviderApiEntity
|
||||
type GeneratedTriggerSubscription = import('@dify/contracts/api/console/workspaces/types.gen').TriggerProviderSubscriptionApiEntity
|
||||
type TriggerProviderApiEntity = import('@/app/components/workflow/block-selector/types').TriggerProviderApiEntity
|
||||
|
||||
const getString = (value: unknown) => {
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
const getNumber = (value: unknown) => {
|
||||
return typeof value === 'number' ? value : 0
|
||||
}
|
||||
|
||||
const getObjectString = (value: unknown, key: string) => {
|
||||
if (!value || typeof value !== 'object')
|
||||
return ''
|
||||
|
||||
return getString(Object.entries(value).find(([entryKey]) => entryKey === key)?.[1])
|
||||
}
|
||||
|
||||
const normalizeI18nObject = (value: GeneratedI18nObject | null | undefined, fallback = '') => {
|
||||
const en = value?.en_US || fallback
|
||||
const zhHans = value?.zh_Hans || en
|
||||
const ja = value?.ja_JP || en
|
||||
const ptBr = value?.pt_BR || en
|
||||
|
||||
return {
|
||||
'en-US': en,
|
||||
'zh-Hans': zhHans,
|
||||
'zh-Hant': en,
|
||||
'pt-BR': ptBr,
|
||||
'es-ES': en,
|
||||
'fr-FR': en,
|
||||
'de-DE': en,
|
||||
'ja-JP': ja,
|
||||
'ko-KR': en,
|
||||
'ru-RU': en,
|
||||
'it-IT': en,
|
||||
'th-TH': en,
|
||||
'uk-UA': en,
|
||||
'vi-VN': en,
|
||||
'ro-RO': en,
|
||||
'pl-PL': en,
|
||||
'hi-IN': en,
|
||||
'tr-TR': en,
|
||||
'fa-IR': en,
|
||||
'sl-SI': en,
|
||||
'id-ID': en,
|
||||
'nl-NL': en,
|
||||
'ar-TN': en,
|
||||
'en_US': en,
|
||||
'zh_Hans': zhHans,
|
||||
'ja_JP': ja,
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeUnknownI18nObject = (value: unknown, fallback = '') => {
|
||||
const en = getObjectString(value, 'en_US') || getObjectString(value, 'en-US') || fallback
|
||||
const zhHans = getObjectString(value, 'zh_Hans') || getObjectString(value, 'zh-Hans') || en
|
||||
const ja = getObjectString(value, 'ja_JP') || getObjectString(value, 'ja-JP') || en
|
||||
const ptBr = getObjectString(value, 'pt_BR') || getObjectString(value, 'pt-BR') || en
|
||||
|
||||
return {
|
||||
'en-US': en,
|
||||
'zh-Hans': zhHans,
|
||||
'zh-Hant': en,
|
||||
'pt-BR': ptBr,
|
||||
'es-ES': en,
|
||||
'fr-FR': en,
|
||||
'de-DE': en,
|
||||
'ja-JP': ja,
|
||||
'ko-KR': en,
|
||||
'ru-RU': en,
|
||||
'it-IT': en,
|
||||
'th-TH': en,
|
||||
'uk-UA': en,
|
||||
'vi-VN': en,
|
||||
'ro-RO': en,
|
||||
'pl-PL': en,
|
||||
'hi-IN': en,
|
||||
'tr-TR': en,
|
||||
'fa-IR': en,
|
||||
'sl-SI': en,
|
||||
'id-ID': en,
|
||||
'nl-NL': en,
|
||||
'ar-TN': en,
|
||||
'en_US': en,
|
||||
'zh_Hans': zhHans,
|
||||
'ja_JP': ja,
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeParameterDefault = (value: unknown) => {
|
||||
if (Array.isArray(value))
|
||||
return value.filter(item => typeof item === 'string')
|
||||
if (typeof value === 'string')
|
||||
return value
|
||||
if (value === undefined || value === null)
|
||||
return undefined
|
||||
return String(value)
|
||||
}
|
||||
|
||||
const normalizeProviderOptions = (options: GeneratedProviderConfig['options']) => {
|
||||
return options?.map(option => ({
|
||||
label: normalizeI18nObject(option.label),
|
||||
value: option.value,
|
||||
})) ?? []
|
||||
}
|
||||
|
||||
const normalizeEventOptions = (options: GeneratedEventParameter['options']) => {
|
||||
return options?.map(option => ({
|
||||
icon: option.icon ?? undefined,
|
||||
label: normalizeI18nObject(option.label),
|
||||
value: option.value,
|
||||
})) ?? []
|
||||
}
|
||||
|
||||
const normalizeProviderConfigType = (type: GeneratedProviderConfig['type']): FormTypeEnum => {
|
||||
switch (type) {
|
||||
case FormTypeEnum.appSelector:
|
||||
return FormTypeEnum.appSelector
|
||||
case FormTypeEnum.boolean:
|
||||
return FormTypeEnum.boolean
|
||||
case FormTypeEnum.modelSelector:
|
||||
return FormTypeEnum.modelSelector
|
||||
case FormTypeEnum.multiToolSelector:
|
||||
return FormTypeEnum.multiToolSelector
|
||||
case FormTypeEnum.secretInput:
|
||||
return FormTypeEnum.secretInput
|
||||
case FormTypeEnum.select:
|
||||
return FormTypeEnum.select
|
||||
case FormTypeEnum.textInput:
|
||||
return FormTypeEnum.textInput
|
||||
}
|
||||
return FormTypeEnum.textInput
|
||||
}
|
||||
|
||||
const normalizeEventParameterFormType = (type: GeneratedEventParameter['type']): FormTypeEnum => {
|
||||
switch (type) {
|
||||
case FormTypeEnum.appSelector:
|
||||
return FormTypeEnum.appSelector
|
||||
case FormTypeEnum.boolean:
|
||||
return FormTypeEnum.boolean
|
||||
case FormTypeEnum.checkbox:
|
||||
return FormTypeEnum.checkbox
|
||||
case FormTypeEnum.dynamicSelect:
|
||||
return FormTypeEnum.dynamicSelect
|
||||
case FormTypeEnum.file:
|
||||
return FormTypeEnum.file
|
||||
case FormTypeEnum.files:
|
||||
return FormTypeEnum.files
|
||||
case FormTypeEnum.modelSelector:
|
||||
return FormTypeEnum.modelSelector
|
||||
case FormTypeEnum.select:
|
||||
return FormTypeEnum.select
|
||||
case 'number':
|
||||
return FormTypeEnum.textNumber
|
||||
case 'string':
|
||||
return FormTypeEnum.textInput
|
||||
case 'array':
|
||||
case 'object':
|
||||
return FormTypeEnum.textInput
|
||||
}
|
||||
return FormTypeEnum.textInput
|
||||
}
|
||||
|
||||
const normalizeProviderConfig = (schema: GeneratedProviderConfig): ParametersSchema => {
|
||||
return {
|
||||
name: schema.name,
|
||||
label: normalizeI18nObject(schema.label, schema.name),
|
||||
type: normalizeProviderConfigType(schema.type),
|
||||
auto_generate: undefined,
|
||||
template: undefined,
|
||||
scope: schema.scope ?? undefined,
|
||||
required: schema.required ?? false,
|
||||
multiple: schema.multiple ?? false,
|
||||
default: normalizeParameterDefault(schema.default),
|
||||
min: undefined,
|
||||
max: undefined,
|
||||
precision: undefined,
|
||||
options: normalizeProviderOptions(schema.options),
|
||||
description: normalizeI18nObject(undefined),
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeCredentialSchema = (schema: GeneratedProviderConfig) => {
|
||||
return {
|
||||
name: schema.name,
|
||||
label: normalizeI18nObject(schema.label, schema.name),
|
||||
description: normalizeI18nObject(undefined),
|
||||
type: normalizeProviderConfigType(schema.type),
|
||||
scope: schema.scope ?? undefined,
|
||||
required: schema.required ?? false,
|
||||
default: schema.default ?? undefined,
|
||||
options: normalizeProviderOptions(schema.options),
|
||||
help: normalizeI18nObject(schema.help),
|
||||
url: schema.url ?? '',
|
||||
placeholder: normalizeI18nObject(schema.placeholder),
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeEventParameterToSchema = (parameter: GeneratedEventParameter): ParametersSchema => {
|
||||
return {
|
||||
name: parameter.name,
|
||||
label: normalizeI18nObject(parameter.label, parameter.name),
|
||||
type: normalizeEventParameterFormType(parameter.type),
|
||||
auto_generate: parameter.auto_generate ?? undefined,
|
||||
template: parameter.template ?? undefined,
|
||||
scope: parameter.scope ?? undefined,
|
||||
required: parameter.required ?? false,
|
||||
multiple: parameter.multiple ?? false,
|
||||
default: normalizeParameterDefault(parameter.default),
|
||||
min: parameter.min ?? undefined,
|
||||
max: parameter.max ?? undefined,
|
||||
precision: parameter.precision ?? undefined,
|
||||
options: normalizeEventOptions(parameter.options),
|
||||
description: normalizeI18nObject(parameter.description),
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeEventParameter = (parameter: GeneratedEventParameter): TriggerEventParameter => {
|
||||
return {
|
||||
name: parameter.name,
|
||||
label: normalizeI18nObject(parameter.label, parameter.name),
|
||||
type: parameter.type,
|
||||
auto_generate: parameter.auto_generate ?? undefined,
|
||||
template: parameter.template ?? undefined,
|
||||
scope: parameter.scope ?? undefined,
|
||||
required: parameter.required ?? false,
|
||||
multiple: parameter.multiple ?? false,
|
||||
default: parameter.default ?? '',
|
||||
min: parameter.min ?? undefined,
|
||||
max: parameter.max ?? undefined,
|
||||
precision: parameter.precision ?? undefined,
|
||||
options: normalizeEventOptions(parameter.options),
|
||||
description: normalizeI18nObject(parameter.description),
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeTriggerEvent = (event: GeneratedTriggerProvider['events'][number]): TriggerEvent => {
|
||||
return {
|
||||
name: event.name,
|
||||
identity: {
|
||||
author: event.identity.author,
|
||||
name: event.identity.name,
|
||||
label: normalizeI18nObject(event.identity.label, event.name),
|
||||
provider: event.identity.provider ?? undefined,
|
||||
},
|
||||
description: normalizeI18nObject(event.description, event.name),
|
||||
parameters: event.parameters.map(normalizeEventParameter),
|
||||
output_schema: event.output_schema ?? {},
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeSupportedCreationMethod = (method: GeneratedTriggerCreationMethod): SupportedCreationMethods => {
|
||||
switch (method) {
|
||||
case SupportedCreationMethods.APIKEY:
|
||||
return SupportedCreationMethods.APIKEY
|
||||
case SupportedCreationMethods.MANUAL:
|
||||
return SupportedCreationMethods.MANUAL
|
||||
case SupportedCreationMethods.OAUTH:
|
||||
return SupportedCreationMethods.OAUTH
|
||||
}
|
||||
return SupportedCreationMethods.MANUAL
|
||||
}
|
||||
|
||||
const normalizeSubscriptionConstructor = (
|
||||
constructor: GeneratedTriggerProvider['subscription_constructor'],
|
||||
): PluginTriggerSubscriptionConstructor | null => {
|
||||
if (!constructor)
|
||||
return null
|
||||
|
||||
return {
|
||||
credentials_schema: (constructor.credentials_schema ?? []).map(normalizeCredentialSchema),
|
||||
oauth_schema: {
|
||||
client_schema: (constructor.oauth_schema?.client_schema ?? []).map(normalizeCredentialSchema),
|
||||
credentials_schema: (constructor.oauth_schema?.credentials_schema ?? []).map(normalizeCredentialSchema),
|
||||
},
|
||||
parameters: (constructor.parameters ?? []).map(normalizeEventParameterToSchema),
|
||||
}
|
||||
}
|
||||
|
||||
export const normalizeTriggerProvider = (provider: GeneratedTriggerProvider): TriggerProviderApiEntity => {
|
||||
return {
|
||||
author: provider.author,
|
||||
name: provider.name,
|
||||
label: normalizeI18nObject(provider.label, provider.name),
|
||||
description: normalizeI18nObject(provider.description),
|
||||
icon: provider.icon ?? undefined,
|
||||
icon_dark: provider.icon_dark ?? undefined,
|
||||
tags: provider.tags ?? [],
|
||||
plugin_id: provider.plugin_id ?? undefined,
|
||||
plugin_unique_identifier: provider.plugin_unique_identifier ?? '',
|
||||
supported_creation_methods: (provider.supported_creation_methods ?? []).map(normalizeSupportedCreationMethod),
|
||||
subscription_constructor: normalizeSubscriptionConstructor(provider.subscription_constructor),
|
||||
subscription_schema: (provider.subscription_schema ?? []).map(normalizeProviderConfig),
|
||||
events: provider.events.map(normalizeTriggerEvent),
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeCredentialType = (credentialType: GeneratedTriggerSubscription['credential_type']): TriggerCredentialTypeEnum => {
|
||||
switch (credentialType) {
|
||||
case TriggerCredentialTypeEnum.ApiKey:
|
||||
return TriggerCredentialTypeEnum.ApiKey
|
||||
case TriggerCredentialTypeEnum.Oauth2:
|
||||
return TriggerCredentialTypeEnum.Oauth2
|
||||
case TriggerCredentialTypeEnum.Unauthorized:
|
||||
return TriggerCredentialTypeEnum.Unauthorized
|
||||
}
|
||||
return TriggerCredentialTypeEnum.Unauthorized
|
||||
}
|
||||
|
||||
const normalizeTriggerSubscription = (subscription: GeneratedTriggerSubscription): TriggerSubscription => {
|
||||
return {
|
||||
id: subscription.id,
|
||||
name: subscription.name,
|
||||
provider: subscription.provider,
|
||||
credential_type: normalizeCredentialType(subscription.credential_type),
|
||||
credentials: subscription.credentials,
|
||||
endpoint: subscription.endpoint,
|
||||
parameters: subscription.parameters,
|
||||
properties: subscription.properties,
|
||||
workflows_in_use: subscription.workflows_in_use,
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeTriggerSubscriptionBuilder = (builder: GeneratedSubscriptionBuilder): TriggerSubscriptionBuilder => {
|
||||
return {
|
||||
id: builder.id,
|
||||
name: builder.name,
|
||||
provider: builder.provider,
|
||||
credential_type: normalizeCredentialType(builder.credential_type),
|
||||
credentials: builder.credentials,
|
||||
endpoint: builder.endpoint,
|
||||
parameters: builder.parameters,
|
||||
properties: builder.properties,
|
||||
workflows_in_use: 0,
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeStringRecord = (record: Record<string, unknown>) => {
|
||||
return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, getString(value)]))
|
||||
}
|
||||
|
||||
const normalizeTriggerOAuthConfig = (config: GeneratedTriggerOAuthConfig): TriggerOAuthConfig => {
|
||||
const params = normalizeStringRecord(config.params)
|
||||
|
||||
return {
|
||||
configured: config.configured,
|
||||
custom_configured: config.custom_configured,
|
||||
custom_enabled: config.custom_enabled,
|
||||
redirect_uri: config.redirect_uri,
|
||||
oauth_client_schema: config.oauth_client_schema.map(normalizeProviderConfig),
|
||||
params: {
|
||||
...params,
|
||||
client_id: params.client_id ?? '',
|
||||
client_secret: params.client_secret ?? '',
|
||||
},
|
||||
system_configured: config.system_configured,
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeDynamicOptionLabel = (label: unknown, fallback: string) => {
|
||||
if (typeof label === 'string')
|
||||
return label
|
||||
|
||||
return normalizeUnknownI18nObject(label, fallback)
|
||||
}
|
||||
|
||||
const normalizeDynamicOption = (option: unknown): FormOption | null => {
|
||||
if (!option || typeof option !== 'object')
|
||||
return null
|
||||
|
||||
const value = getObjectString(option, 'value')
|
||||
if (!value)
|
||||
return null
|
||||
|
||||
const label = Object.entries(option).find(([key]) => key === 'label')?.[1]
|
||||
const icon = getObjectString(option, 'icon')
|
||||
const normalizedOption: FormOption = {
|
||||
label: normalizeDynamicOptionLabel(label, value),
|
||||
value,
|
||||
}
|
||||
|
||||
if (icon)
|
||||
normalizedOption.icon = icon
|
||||
|
||||
return normalizedOption
|
||||
}
|
||||
|
||||
const isFormOption = (option: FormOption | null): option is FormOption => {
|
||||
return option !== null
|
||||
}
|
||||
|
||||
const normalizeDynamicOptionsResponse = (response: { options: unknown }): { options: FormOption[] } => {
|
||||
return {
|
||||
options: Array.isArray(response.options)
|
||||
? response.options.map(normalizeDynamicOption).filter(isFormOption)
|
||||
: [],
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeLogHeaders = (headers: unknown) => {
|
||||
return {
|
||||
'Host': getObjectString(headers, 'Host'),
|
||||
'User-Agent': getObjectString(headers, 'User-Agent'),
|
||||
'Content-Length': getObjectString(headers, 'Content-Length'),
|
||||
'Accept': getObjectString(headers, 'Accept'),
|
||||
'Content-Type': getObjectString(headers, 'Content-Type'),
|
||||
'X-Forwarded-For': getObjectString(headers, 'X-Forwarded-For'),
|
||||
'X-Forwarded-Host': getObjectString(headers, 'X-Forwarded-Host'),
|
||||
'X-Forwarded-Proto': getObjectString(headers, 'X-Forwarded-Proto'),
|
||||
'X-Github-Delivery': getObjectString(headers, 'X-Github-Delivery'),
|
||||
'X-Github-Event': getObjectString(headers, 'X-Github-Event'),
|
||||
'X-Github-Hook-Id': getObjectString(headers, 'X-Github-Hook-Id'),
|
||||
'X-Github-Hook-Installation-Target-Id': getObjectString(headers, 'X-Github-Hook-Installation-Target-Id'),
|
||||
'X-Github-Hook-Installation-Target-Type': getObjectString(headers, 'X-Github-Hook-Installation-Target-Type'),
|
||||
'Accept-Encoding': getObjectString(headers, 'Accept-Encoding'),
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeResponseHeaders = (headers: unknown) => {
|
||||
return {
|
||||
'Content-Type': getObjectString(headers, 'Content-Type'),
|
||||
'Content-Length': getObjectString(headers, 'Content-Length'),
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeTriggerLog = (log: GeneratedRequestLog): TriggerLogEntity => {
|
||||
return {
|
||||
id: log.id,
|
||||
endpoint: log.endpoint,
|
||||
created_at: log.created_at,
|
||||
request: {
|
||||
method: getString(log.request.method),
|
||||
url: getString(log.request.url),
|
||||
headers: normalizeLogHeaders(log.request.headers),
|
||||
data: getString(log.request.data),
|
||||
},
|
||||
response: {
|
||||
status_code: getNumber(log.response.status_code),
|
||||
headers: normalizeResponseHeaders(log.response.headers),
|
||||
data: getString(log.response.data),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const convertToTriggerWithProvider = (provider: TriggerProviderApiEntity): TriggerWithProvider => {
|
||||
return {
|
||||
id: provider.plugin_id || provider.name,
|
||||
name: provider.name,
|
||||
@ -45,7 +500,7 @@ const convertToTriggerWithProvider = (provider: TriggerProviderApiEntity): Trigg
|
||||
form: param.type,
|
||||
llm_description: JSON.stringify(param.description || {}),
|
||||
required: param.required || false,
|
||||
default: param.default || '',
|
||||
default: param.default ?? '',
|
||||
options: param.options?.map(option => ({
|
||||
label: option.label,
|
||||
value: option.value,
|
||||
@ -66,56 +521,63 @@ const convertToTriggerWithProvider = (provider: TriggerProviderApiEntity): Trigg
|
||||
|
||||
export const useAllTriggerPlugins = (enabled = true) => {
|
||||
return useQuery<TriggerWithProvider[]>({
|
||||
queryKey: consoleQuery.triggers.list.queryKey({ input: {} }),
|
||||
queryKey: consoleQuery.workspaces.current.triggers.get.queryKey({ input: {} }),
|
||||
queryFn: async () => {
|
||||
const response = await consoleClient.triggers.list({})
|
||||
return response.map(convertToTriggerWithProvider)
|
||||
const response = await consoleClient.workspaces.current.triggers.get({})
|
||||
return response.map(normalizeTriggerProvider).map(convertToTriggerWithProvider)
|
||||
},
|
||||
enabled,
|
||||
})
|
||||
}
|
||||
|
||||
export const useInvalidateAllTriggerPlugins = () => {
|
||||
return useInvalid(consoleQuery.triggers.list.queryKey({ input: {} }))
|
||||
return useInvalid(consoleQuery.workspaces.current.triggers.get.queryKey({ input: {} }))
|
||||
}
|
||||
|
||||
// ===== Trigger Subscriptions Management =====
|
||||
|
||||
export const useTriggerProviderInfo = (provider: string, enabled = true) => {
|
||||
return useQuery<TriggerProviderApiEntity>({
|
||||
queryKey: consoleQuery.triggers.providerInfo.queryKey({ input: { params: { provider } } }),
|
||||
queryFn: () => consoleClient.triggers.providerInfo({ params: { provider } }),
|
||||
queryKey: consoleQuery.workspaces.current.triggerProvider.byProvider.info.get.queryKey({ input: { params: { provider } } }),
|
||||
queryFn: async () => normalizeTriggerProvider(
|
||||
await consoleClient.workspaces.current.triggerProvider.byProvider.info.get({ params: { provider } }),
|
||||
),
|
||||
enabled: enabled && !!provider,
|
||||
})
|
||||
}
|
||||
|
||||
export const useTriggerSubscriptions = (provider: string, enabled = true) => {
|
||||
return useQuery<TriggerSubscription[]>({
|
||||
queryKey: consoleQuery.triggers.subscriptions.queryKey({ input: { params: { provider } } }),
|
||||
queryFn: () => consoleClient.triggers.subscriptions({ params: { provider } }),
|
||||
queryKey: consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.list.get.queryKey({ input: { params: { provider } } }),
|
||||
queryFn: async () => {
|
||||
const response = await consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.list.get({ params: { provider } })
|
||||
return response.map(normalizeTriggerSubscription)
|
||||
},
|
||||
enabled: enabled && !!provider,
|
||||
})
|
||||
}
|
||||
|
||||
export const useCreateTriggerSubscriptionBuilder = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.subscriptionBuilderCreate.mutationKey(),
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.builder.create.post.mutationKey(),
|
||||
mutationFn: (payload: {
|
||||
provider: string
|
||||
credential_type?: string
|
||||
}) => {
|
||||
const { provider, ...body } = payload
|
||||
return consoleClient.triggers.subscriptionBuilderCreate({
|
||||
return consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.builder.create.post({
|
||||
params: { provider },
|
||||
body,
|
||||
})
|
||||
}).then(response => ({
|
||||
subscription_builder: normalizeTriggerSubscriptionBuilder(response.subscription_builder),
|
||||
}))
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useUpdateTriggerSubscriptionBuilder = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.subscriptionBuilderUpdate.mutationKey(),
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.builder.update.bySubscriptionBuilderId.post.mutationKey(),
|
||||
mutationFn: (payload: {
|
||||
provider: string
|
||||
subscriptionBuilderId: string
|
||||
@ -125,46 +587,48 @@ export const useUpdateTriggerSubscriptionBuilder = () => {
|
||||
credentials?: Record<string, unknown>
|
||||
}) => {
|
||||
const { provider, subscriptionBuilderId, ...body } = payload
|
||||
return consoleClient.triggers.subscriptionBuilderUpdate({
|
||||
params: { provider, subscriptionBuilderId },
|
||||
return consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.builder.update.bySubscriptionBuilderId.post({
|
||||
params: { provider, subscription_builder_id: subscriptionBuilderId },
|
||||
body,
|
||||
})
|
||||
}).then(normalizeTriggerSubscriptionBuilder)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useVerifyAndUpdateTriggerSubscriptionBuilder = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.subscriptionBuilderVerifyUpdate.mutationKey(),
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.builder.verifyAndUpdate.bySubscriptionBuilderId.post.mutationKey(),
|
||||
mutationFn: (payload: {
|
||||
provider: string
|
||||
subscriptionBuilderId: string
|
||||
credentials?: Record<string, unknown>
|
||||
}) => {
|
||||
const { provider, subscriptionBuilderId, ...body } = payload
|
||||
return post<{ verified: boolean }>(
|
||||
`/workspaces/current/trigger-provider/${provider}/subscriptions/builder/verify-and-update/${subscriptionBuilderId}`,
|
||||
{ body },
|
||||
{ silent: true },
|
||||
)
|
||||
const { provider, subscriptionBuilderId, credentials } = payload
|
||||
return consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.builder.verifyAndUpdate.bySubscriptionBuilderId.post({
|
||||
params: { provider, subscription_builder_id: subscriptionBuilderId },
|
||||
body: { credentials: credentials ?? {} },
|
||||
}, {
|
||||
context: { silent: true },
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export const useVerifyTriggerSubscription = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.subscriptionVerify.mutationKey(),
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.verify.bySubscriptionId.post.mutationKey(),
|
||||
mutationFn: (payload: {
|
||||
provider: string
|
||||
subscriptionId: string
|
||||
credentials?: Record<string, unknown>
|
||||
}) => {
|
||||
const { provider, subscriptionId, ...body } = payload
|
||||
return post<{ verified: boolean }>(
|
||||
`/workspaces/current/trigger-provider/${provider}/subscriptions/verify/${subscriptionId}`,
|
||||
{ body },
|
||||
{ silent: true },
|
||||
)
|
||||
const { provider, subscriptionId, credentials } = payload
|
||||
return consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.verify.bySubscriptionId.post({
|
||||
params: { provider, subscription_id: subscriptionId },
|
||||
body: { credentials: credentials ?? {} },
|
||||
}, {
|
||||
context: { silent: true },
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
@ -178,11 +642,11 @@ export type BuildTriggerSubscriptionPayload = {
|
||||
|
||||
export const useBuildTriggerSubscription = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.subscriptionBuild.mutationKey(),
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.builder.build.bySubscriptionBuilderId.post.mutationKey(),
|
||||
mutationFn: (payload: BuildTriggerSubscriptionPayload) => {
|
||||
const { provider, subscriptionBuilderId, ...body } = payload
|
||||
return consoleClient.triggers.subscriptionBuild({
|
||||
params: { provider, subscriptionBuilderId },
|
||||
return consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.builder.build.bySubscriptionBuilderId.post({
|
||||
params: { provider, subscription_builder_id: subscriptionBuilderId },
|
||||
body,
|
||||
})
|
||||
},
|
||||
@ -191,10 +655,10 @@ export const useBuildTriggerSubscription = () => {
|
||||
|
||||
export const useDeleteTriggerSubscription = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.subscriptionDelete.mutationKey(),
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.bySubscriptionId.subscriptions.delete.post.mutationKey(),
|
||||
mutationFn: (subscriptionId: string) => {
|
||||
return consoleClient.triggers.subscriptionDelete({
|
||||
params: { subscriptionId },
|
||||
return consoleClient.workspaces.current.triggerProvider.bySubscriptionId.subscriptions.delete.post({
|
||||
params: { subscription_id: subscriptionId },
|
||||
})
|
||||
},
|
||||
})
|
||||
@ -210,11 +674,11 @@ type UpdateTriggerSubscriptionPayload = {
|
||||
|
||||
export const useUpdateTriggerSubscription = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.subscriptionUpdate.mutationKey(),
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.bySubscriptionId.subscriptions.update.post.mutationKey(),
|
||||
mutationFn: (payload: UpdateTriggerSubscriptionPayload) => {
|
||||
const { subscriptionId, ...body } = payload
|
||||
return consoleClient.triggers.subscriptionUpdate({
|
||||
params: { subscriptionId },
|
||||
return consoleClient.workspaces.current.triggerProvider.bySubscriptionId.subscriptions.update.post({
|
||||
params: { subscription_id: subscriptionId },
|
||||
body,
|
||||
})
|
||||
},
|
||||
@ -232,8 +696,17 @@ export const useTriggerSubscriptionBuilderLogs = (
|
||||
const { enabled = true, refetchInterval = false } = options
|
||||
|
||||
return useQuery<{ logs: TriggerLogEntity[] }>({
|
||||
queryKey: consoleQuery.triggers.subscriptionBuilderLogs.queryKey({ input: { params: { provider, subscriptionBuilderId } } }),
|
||||
queryFn: () => consoleClient.triggers.subscriptionBuilderLogs({ params: { provider, subscriptionBuilderId } }),
|
||||
queryKey: consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.builder.logs.bySubscriptionBuilderId.get.queryKey({
|
||||
input: { params: { provider, subscription_builder_id: subscriptionBuilderId } },
|
||||
}),
|
||||
queryFn: async () => {
|
||||
const response = await consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.builder.logs.bySubscriptionBuilderId.get({
|
||||
params: { provider, subscription_builder_id: subscriptionBuilderId },
|
||||
})
|
||||
return {
|
||||
logs: response.logs.map(normalizeTriggerLog),
|
||||
}
|
||||
},
|
||||
enabled: enabled && !!provider && !!subscriptionBuilderId,
|
||||
refetchInterval,
|
||||
})
|
||||
@ -242,8 +715,10 @@ export const useTriggerSubscriptionBuilderLogs = (
|
||||
// ===== OAuth Management =====
|
||||
export const useTriggerOAuthConfig = (provider: string, enabled = true) => {
|
||||
return useQuery<TriggerOAuthConfig>({
|
||||
queryKey: consoleQuery.triggers.oauthConfig.queryKey({ input: { params: { provider } } }),
|
||||
queryFn: () => consoleClient.triggers.oauthConfig({ params: { provider } }),
|
||||
queryKey: consoleQuery.workspaces.current.triggerProvider.byProvider.oauth.client.get.queryKey({ input: { params: { provider } } }),
|
||||
queryFn: async () => normalizeTriggerOAuthConfig(
|
||||
await consoleClient.workspaces.current.triggerProvider.byProvider.oauth.client.get({ params: { provider } }),
|
||||
),
|
||||
enabled: enabled && !!provider,
|
||||
})
|
||||
}
|
||||
@ -256,10 +731,10 @@ export type ConfigureTriggerOAuthPayload = {
|
||||
|
||||
export const useConfigureTriggerOAuth = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.oauthConfigure.mutationKey(),
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.byProvider.oauth.client.post.mutationKey(),
|
||||
mutationFn: (payload: ConfigureTriggerOAuthPayload) => {
|
||||
const { provider, ...body } = payload
|
||||
return consoleClient.triggers.oauthConfigure({
|
||||
return consoleClient.workspaces.current.triggerProvider.byProvider.oauth.client.post({
|
||||
params: { provider },
|
||||
body,
|
||||
})
|
||||
@ -269,9 +744,9 @@ export const useConfigureTriggerOAuth = () => {
|
||||
|
||||
export const useDeleteTriggerOAuth = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.oauthDelete.mutationKey(),
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.byProvider.oauth.client.delete.mutationKey(),
|
||||
mutationFn: (provider: string) => {
|
||||
return consoleClient.triggers.oauthDelete({
|
||||
return consoleClient.workspaces.current.triggerProvider.byProvider.oauth.client.delete({
|
||||
params: { provider },
|
||||
})
|
||||
},
|
||||
@ -280,13 +755,17 @@ export const useDeleteTriggerOAuth = () => {
|
||||
|
||||
export const useInitiateTriggerOAuth = () => {
|
||||
return useMutation({
|
||||
mutationKey: consoleQuery.triggers.oauthInitiate.mutationKey(),
|
||||
mutationFn: (provider: string) => {
|
||||
return get<{ authorization_url: string, subscription_builder: TriggerSubscriptionBuilder }>(
|
||||
`/workspaces/current/trigger-provider/${provider}/subscriptions/oauth/authorize`,
|
||||
{},
|
||||
{ silent: true },
|
||||
)
|
||||
mutationKey: consoleQuery.workspaces.current.triggerProvider.byProvider.subscriptions.oauth.authorize.get.mutationKey(),
|
||||
mutationFn: async (provider: string) => {
|
||||
const response = await consoleClient.workspaces.current.triggerProvider.byProvider.subscriptions.oauth.authorize.get({
|
||||
params: { provider },
|
||||
}, {
|
||||
context: { silent: true },
|
||||
})
|
||||
return {
|
||||
authorization_url: response.authorization_url,
|
||||
subscription_builder: normalizeTriggerSubscriptionBuilder(response.subscription_builder),
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@ -303,36 +782,37 @@ export const useTriggerPluginDynamicOptions = (payload: {
|
||||
}, enabled = true) => {
|
||||
return useQuery<{ options: FormOption[] }>({
|
||||
queryKey: [NAME_SPACE, 'dynamic-options', payload.plugin_id, payload.provider, payload.action, payload.parameter, payload.credential_id, payload.credentials, payload.extra],
|
||||
queryFn: () => {
|
||||
queryFn: async () => {
|
||||
if (payload.credentials) {
|
||||
return post<{ options: FormOption[] }>(
|
||||
'/workspaces/current/plugin/parameters/dynamic-options-with-credentials',
|
||||
{
|
||||
return normalizeDynamicOptionsResponse(
|
||||
await consoleClient.workspaces.current.plugin.parameters.dynamicOptionsWithCredentials.post({
|
||||
body: {
|
||||
plugin_id: payload.plugin_id,
|
||||
provider: payload.provider,
|
||||
action: payload.action,
|
||||
parameter: payload.parameter,
|
||||
credential_id: payload.credential_id,
|
||||
credentials: payload.credentials,
|
||||
parameter: payload.parameter,
|
||||
plugin_id: payload.plugin_id,
|
||||
provider: payload.provider,
|
||||
},
|
||||
},
|
||||
{ silent: true },
|
||||
}, {
|
||||
context: { silent: true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
return get<{ options: FormOption[] }>(
|
||||
'/workspaces/current/plugin/parameters/dynamic-options',
|
||||
{
|
||||
params: {
|
||||
|
||||
return normalizeDynamicOptionsResponse(
|
||||
await consoleClient.workspaces.current.plugin.parameters.dynamicOptions.get({
|
||||
query: {
|
||||
action: payload.action,
|
||||
credential_id: payload.credential_id,
|
||||
parameter: payload.parameter,
|
||||
plugin_id: payload.plugin_id,
|
||||
provider: payload.provider,
|
||||
action: payload.action,
|
||||
parameter: payload.parameter,
|
||||
credential_id: payload.credential_id,
|
||||
provider_type: 'trigger',
|
||||
},
|
||||
},
|
||||
{ silent: true },
|
||||
}, {
|
||||
context: { silent: true },
|
||||
}),
|
||||
)
|
||||
},
|
||||
enabled: enabled && !!payload.plugin_id && !!payload.provider && !!payload.action && !!payload.parameter && !!payload.credential_id,
|
||||
|
||||
Loading…
Reference in New Issue
Block a user