mirror of
https://github.com/langgenius/dify.git
synced 2026-01-14 06:07:33 +08:00
Signed-off-by: NeatGuyCoding <15627489+NeatGuyCoding@users.noreply.github.com> Signed-off-by: lyzno1 <yuanyouhuilyz@gmail.com> Signed-off-by: kenwoodjw <blackxin55+@gmail.com> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: Yunlu Wen <wylswz@163.com> Co-authored-by: Joel <iamjoel007@gmail.com> Co-authored-by: GareArc <chen4851@purdue.edu> Co-authored-by: NFish <douxc512@gmail.com> Co-authored-by: Davide Delbianco <davide.delbianco@outlook.com> Co-authored-by: minglu7 <1347866672@qq.com> Co-authored-by: Ponder <ruan.lj@foxmail.com> Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com> Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com> Co-authored-by: heyszt <270985384@qq.com> Co-authored-by: Asuka Minato <i@asukaminato.eu.org> Co-authored-by: Guangdong Liu <liugddx@gmail.com> Co-authored-by: Eric Guo <eric.guocz@gmail.com> Co-authored-by: NeatGuyCoding <15627489+NeatGuyCoding@users.noreply.github.com> Co-authored-by: XlKsyt <caixuesen@outlook.com> Co-authored-by: Dhruv Gorasiya <80987415+DhruvGorasiya@users.noreply.github.com> Co-authored-by: crazywoola <427733928@qq.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: lyzno1 <92089059+lyzno1@users.noreply.github.com> Co-authored-by: hj24 <mambahj24@gmail.com> Co-authored-by: GuanMu <ballmanjq@gmail.com> Co-authored-by: 非法操作 <hjlarry@163.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Tonlo <123lzs123@gmail.com> Co-authored-by: Yusuke Yamada <yamachu.dev@gmail.com> Co-authored-by: Novice <novice12185727@gmail.com> Co-authored-by: kenwoodjw <blackxin55+@gmail.com> Co-authored-by: Ademílson Tonato <ademilsonft@outlook.com> Co-authored-by: znn <jubinkumarsoni@gmail.com> Co-authored-by: yangzheli <43645580+yangzheli@users.noreply.github.com>
195 lines
5.9 KiB
TypeScript
195 lines
5.9 KiB
TypeScript
import type { AfterResponseHook, BeforeErrorHook, BeforeRequestHook, Hooks } from 'ky'
|
|
import ky from 'ky'
|
|
import type { IOtherOptions } from './base'
|
|
import Toast from '@/app/components/base/toast'
|
|
import { API_PREFIX, APP_VERSION, CSRF_COOKIE_NAME, CSRF_HEADER_NAME, MARKETPLACE_API_PREFIX, PASSPORT_HEADER_NAME, PUBLIC_API_PREFIX, WEB_APP_SHARE_CODE_HEADER_NAME } from '@/config'
|
|
import Cookies from 'js-cookie'
|
|
import { getWebAppAccessToken, getWebAppPassport } from './webapp-auth'
|
|
|
|
const TIME_OUT = 100000
|
|
|
|
export const ContentType = {
|
|
json: 'application/json',
|
|
stream: 'text/event-stream',
|
|
audio: 'audio/mpeg',
|
|
form: 'application/x-www-form-urlencoded; charset=UTF-8',
|
|
download: 'application/octet-stream', // for download
|
|
downloadZip: 'application/zip', // for download
|
|
upload: 'multipart/form-data', // for upload
|
|
}
|
|
|
|
export type FetchOptionType = Omit<RequestInit, 'body'> & {
|
|
params?: Record<string, any>
|
|
body?: BodyInit | Record<string, any> | null
|
|
}
|
|
|
|
const afterResponse204: AfterResponseHook = async (_request, _options, response) => {
|
|
if (response.status === 204) return Response.json({ result: 'success' })
|
|
}
|
|
|
|
export type ResponseError = {
|
|
code: string
|
|
message: string
|
|
status: number
|
|
}
|
|
|
|
const afterResponseErrorCode = (otherOptions: IOtherOptions): AfterResponseHook => {
|
|
return async (_request, _options, response) => {
|
|
const clonedResponse = response.clone()
|
|
if (!/^([23])\d{2}$/.test(String(clonedResponse.status))) {
|
|
const bodyJson = clonedResponse.json() as Promise<ResponseError>
|
|
switch (clonedResponse.status) {
|
|
case 403:
|
|
bodyJson.then((data: ResponseError) => {
|
|
if (!otherOptions.silent)
|
|
Toast.notify({ type: 'error', message: data.message })
|
|
if (data.code === 'already_setup')
|
|
globalThis.location.href = `${globalThis.location.origin}/signin`
|
|
})
|
|
break
|
|
case 401:
|
|
return Promise.reject(response)
|
|
// fall through
|
|
default:
|
|
bodyJson.then((data: ResponseError) => {
|
|
if (!otherOptions.silent)
|
|
Toast.notify({ type: 'error', message: data.message })
|
|
})
|
|
return Promise.reject(response)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
const beforeErrorToast = (otherOptions: IOtherOptions): BeforeErrorHook => {
|
|
return (error) => {
|
|
if (!otherOptions.silent)
|
|
Toast.notify({ type: 'error', message: error.message })
|
|
return error
|
|
}
|
|
}
|
|
|
|
const beforeRequestPublicWithCode = (request: Request) => {
|
|
request.headers.set('Authorization', `Bearer ${getWebAppAccessToken()}`)
|
|
const shareCode = globalThis.location.pathname.split('/').filter(Boolean).pop() || ''
|
|
// some pages does not end with share code, so we need to check it
|
|
// TODO: maybe find a better way to access app code?
|
|
if (shareCode === 'webapp-signin' || shareCode === 'check-code')
|
|
return
|
|
request.headers.set(WEB_APP_SHARE_CODE_HEADER_NAME, shareCode)
|
|
request.headers.set(PASSPORT_HEADER_NAME, getWebAppPassport(shareCode))
|
|
}
|
|
|
|
const baseHooks: Hooks = {
|
|
afterResponse: [
|
|
afterResponse204,
|
|
],
|
|
}
|
|
|
|
const baseClient = ky.create({
|
|
hooks: baseHooks,
|
|
timeout: TIME_OUT,
|
|
})
|
|
|
|
export const getBaseOptions = (): RequestInit => ({
|
|
method: 'GET',
|
|
mode: 'cors',
|
|
credentials: 'include', // always send cookies、HTTP Basic authentication.
|
|
headers: new Headers({
|
|
'Content-Type': ContentType.json,
|
|
}),
|
|
redirect: 'follow',
|
|
})
|
|
|
|
async function base<T>(url: string, options: FetchOptionType = {}, otherOptions: IOtherOptions = {}): Promise<T> {
|
|
const baseOptions = getBaseOptions()
|
|
const { params, body, headers, ...init } = Object.assign({}, baseOptions, options)
|
|
const {
|
|
isPublicAPI = false,
|
|
isMarketplaceAPI = false,
|
|
bodyStringify = true,
|
|
needAllResponseContent,
|
|
deleteContentType,
|
|
getAbortController,
|
|
} = otherOptions
|
|
|
|
let base: string
|
|
if (isMarketplaceAPI)
|
|
base = MARKETPLACE_API_PREFIX
|
|
else if (isPublicAPI)
|
|
base = PUBLIC_API_PREFIX
|
|
else
|
|
base = API_PREFIX
|
|
|
|
if (getAbortController) {
|
|
const abortController = new AbortController()
|
|
getAbortController(abortController)
|
|
options.signal = abortController.signal
|
|
}
|
|
|
|
const fetchPathname = base + (url.startsWith('/') ? url : `/${url}`)
|
|
if (!isMarketplaceAPI)
|
|
(headers as any).set(CSRF_HEADER_NAME, Cookies.get(CSRF_COOKIE_NAME()) || '')
|
|
|
|
if (deleteContentType)
|
|
(headers as any).delete('Content-Type')
|
|
|
|
// ! For Marketplace API, help to filter tags added in new version
|
|
if (isMarketplaceAPI)
|
|
(headers as any).set('X-Dify-Version', APP_VERSION)
|
|
|
|
const client = baseClient.extend({
|
|
hooks: {
|
|
...baseHooks,
|
|
beforeError: [
|
|
...baseHooks.beforeError || [],
|
|
beforeErrorToast(otherOptions),
|
|
],
|
|
beforeRequest: [
|
|
...baseHooks.beforeRequest || [],
|
|
isPublicAPI && beforeRequestPublicWithCode,
|
|
].filter((h): h is BeforeRequestHook => Boolean(h)),
|
|
afterResponse: [
|
|
...baseHooks.afterResponse || [],
|
|
afterResponseErrorCode(otherOptions),
|
|
],
|
|
},
|
|
})
|
|
|
|
const res = await client(fetchPathname, {
|
|
...init,
|
|
headers,
|
|
credentials: isMarketplaceAPI
|
|
? 'omit'
|
|
: (options.credentials || 'include'),
|
|
retry: {
|
|
methods: [],
|
|
},
|
|
...(bodyStringify ? { json: body } : { body: body as BodyInit }),
|
|
searchParams: params,
|
|
fetch(resource: RequestInfo | URL, options?: RequestInit) {
|
|
if (resource instanceof Request && options) {
|
|
const mergedHeaders = new Headers(options.headers || {})
|
|
resource.headers.forEach((value, key) => {
|
|
mergedHeaders.append(key, value)
|
|
})
|
|
options.headers = mergedHeaders
|
|
}
|
|
return globalThis.fetch(resource, options)
|
|
},
|
|
})
|
|
|
|
if (needAllResponseContent)
|
|
return res as T
|
|
const contentType = res.headers.get('content-type')
|
|
if (
|
|
contentType
|
|
&& [ContentType.download, ContentType.audio, ContentType.downloadZip].includes(contentType)
|
|
)
|
|
return await res.blob() as T
|
|
|
|
return await res.json() as T
|
|
}
|
|
|
|
export { base }
|