chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,88 @@
import type { AddressInfo } from 'node:net'
import { createServer } from 'node:http'
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'
import { DifyClient } from '../src/client/base'
describe('upload user fields', () => {
const server = createServer((req, res) => {
void (async () => {
const chunks: Buffer[] = []
for await (const chunk of req as AsyncIterable<Uint8Array>) {
chunks.push(Buffer.from(chunk))
}
const request = new Request('http://localhost', {
method: 'POST',
headers: { 'content-type': req.headers['content-type'] ?? '' },
body: new Uint8Array(Buffer.concat(chunks)),
})
const form = await request.formData()
const file = form.get('file') as File
res.writeHead(200, { 'content-type': 'application/json' })
res.end(
JSON.stringify({
users: form.getAll('user'),
fileName: file.name,
fileText: await file.text(),
extra: form.get('extra'),
}),
)
})().catch(() => {
res.writeHead(500)
res.end()
})
})
let client: DifyClient
beforeAll(async () => {
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const address = server.address() as AddressInfo
client = new DifyClient({
apiKey: 'test',
baseUrl: `http://127.0.0.1:${address.port}`,
maxRetries: 0,
})
})
afterAll(async () => {
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()))
})
})
const makeForm = () => {
const form = new FormData()
form.append('file', new Blob(['payload']), 'sample.txt')
form.append('extra', 'preserved')
return form
}
it.each(['fileUpload', 'audioToText'] as const)(
'%s replaces existing user fields',
async (method) => {
const form = makeForm()
form.append('user', 'stale-user')
form.append('user', 'another-user')
const response = await client[method](form, 'current-user')
expect(response.data).toEqual({
users: ['current-user'],
fileName: 'sample.txt',
fileText: 'payload',
extra: 'preserved',
})
},
)
it.each(['fileUpload', 'audioToText'] as const)(
'%s can reuse native FormData for a new user',
async (method) => {
const form = makeForm()
const first = await client[method](form, 'first-user')
expect(first.data.users).toEqual(['first-user'])
const second = await client[method](form, 'second-user')
expect(second.data.users).toEqual(['second-user'])
expect(second.data.fileText).toBe('payload')
},
)
})
@@ -0,0 +1,216 @@
import type { AddressInfo } from 'node:net'
import { createServer } from 'node:http'
import { Readable } from 'node:stream'
import { afterAll, beforeAll, describe, expect, it } from 'vite-plus/test'
import { ChatClient } from '../src/client/chat'
import { KnowledgeBaseClient } from '../src/client/knowledge-base'
import { HttpClient } from '../src/http/client'
const readBody = async (stream: NodeJS.ReadableStream): Promise<Buffer> => {
const chunks: Buffer[] = []
for await (const chunk of stream) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
}
return Buffer.concat(chunks)
}
describe('HttpClient integration', () => {
const requests: Array<{
url: string
method: string
headers: Record<string, string | string[] | undefined>
body: Buffer
}> = []
const server = createServer((req, res) => {
void (async () => {
const body = await readBody(req)
requests.push({
url: req.url ?? '',
method: req.method ?? '',
headers: req.headers,
body,
})
if (
req.url?.startsWith('/json') ||
req.url?.startsWith('/datasets') ||
req.url?.startsWith('/apps/annotations')
) {
res.writeHead(200, { 'content-type': 'application/json', 'x-request-id': 'req-json' })
res.end(JSON.stringify({ ok: true }))
return
}
if (req.url === '/stream') {
res.writeHead(200, { 'content-type': 'text/event-stream' })
res.end('data: {"answer":"hello"}\n\ndata: {"delta":" world"}\n\n')
return
}
if (req.url === '/bytes') {
res.writeHead(200, { 'content-type': 'application/octet-stream' })
res.end(Buffer.from([1, 2, 3, 4]))
return
}
if (req.url === '/upload-stream') {
res.writeHead(200, { 'content-type': 'application/json' })
res.end(JSON.stringify({ received: body.toString('utf8') }))
return
}
res.writeHead(404, { 'content-type': 'application/json' })
res.end(JSON.stringify({ message: 'not found' }))
})()
})
let client: HttpClient
beforeAll(async () => {
await new Promise<void>((resolve) => {
server.listen(0, '127.0.0.1', () => resolve())
})
const address = server.address() as AddressInfo
client = new HttpClient({
apiKey: 'test-key',
baseUrl: `http://127.0.0.1:${address.port}`,
maxRetries: 0,
retryDelay: 0,
})
})
afterAll(async () => {
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) {
reject(error)
return
}
resolve()
})
})
})
it('uses real fetch for query serialization and json bodies', async () => {
const response = await client.request({
method: 'POST',
path: '/json',
query: { tag_ids: ['a', 'b'], limit: 2 },
data: { user: 'u' },
})
expect(response.requestId).toBe('req-json')
expect(response.data).toEqual({ ok: true })
expect(requests.at(-1)).toMatchObject({
url: '/json?tag_ids=a&tag_ids=b&limit=2',
method: 'POST',
})
expect(requests.at(-1)?.headers.authorization).toBe('Bearer test-key')
expect(requests.at(-1)?.headers['content-type']).toBe('application/json')
expect(requests.at(-1)?.body.toString('utf8')).toBe(JSON.stringify({ user: 'u' }))
})
it.each(['Content-Type', 'content-type', 'CoNtEnT-TyPe'])(
'overrides the JSON content type with %s',
async (headerName) => {
await client.request({
method: 'POST',
path: '/json',
data: { user: 'u' },
headers: { [headerName]: 'application/custom+json' },
})
expect(requests.at(-1)?.headers['content-type']).toBe('application/custom+json')
expect(requests.at(-1)?.body.toString('utf8')).toBe(JSON.stringify({ user: 'u' }))
},
)
it('overrides authorization without combining differently cased defaults', async () => {
await client.request({
method: 'GET',
path: '/json',
headers: { authorization: 'Bearer override-key' },
})
expect(requests.at(-1)?.headers.authorization).toBe('Bearer override-key')
})
it('supports streaming request bodies with duplex fetch', async () => {
const response = await client.request<{ received: string }>({
method: 'POST',
path: '/upload-stream',
data: Readable.from(['hello ', 'world']),
})
expect(response.data).toEqual({ received: 'hello world' })
expect(requests.at(-1)?.body.toString('utf8')).toBe('hello world')
})
it('parses real sse responses into text', async () => {
const stream = await client.requestStream({
method: 'GET',
path: '/stream',
})
await expect(stream.toText()).resolves.toBe('hello world')
})
it('parses real byte responses into buffers', async () => {
const response = await client.request<Buffer, 'bytes'>({
method: 'GET',
path: '/bytes',
responseType: 'bytes',
})
expect(Array.from(response.data.values())).toEqual([1, 2, 3, 4])
})
const keywordRequests = [
{
name: 'datasets',
path: '/datasets',
run: (keyword: string) => new KnowledgeBaseClient(client).listDatasets({ keyword }),
},
{
name: 'documents',
path: '/datasets/ds/documents',
run: (keyword: string) => new KnowledgeBaseClient(client).listDocuments('ds', { keyword }),
},
{
name: 'segments',
path: '/datasets/ds/documents/doc/segments',
run: (keyword: string) =>
new KnowledgeBaseClient(client).listSegments('ds', 'doc', { keyword }),
},
{
name: 'child chunks',
path: '/datasets/ds/documents/doc/segments/seg/child_chunks',
run: (keyword: string) =>
new KnowledgeBaseClient(client).listChildChunks('ds', 'doc', 'seg', { keyword }),
},
{
name: 'annotations',
path: '/apps/annotations',
run: (keyword: string) => new ChatClient(client).listAnnotations({ keyword }),
},
]
it.each(keywordRequests)('allows an empty keyword when listing $name', async ({ path, run }) => {
await run('')
const url = new URL(requests.at(-1)!.url, 'http://localhost')
expect(url.pathname).toBe(path)
expect(url.searchParams.has('keyword')).toBe(true)
expect(url.searchParams.get('keyword')).toBe('')
})
it.each(keywordRequests)(
'still rejects oversized keywords when listing $name',
async ({ run }) => {
await expect(Promise.resolve().then(() => run('a'.repeat(10001)))).rejects.toThrow(
'maximum length',
)
},
)
})
@@ -0,0 +1,48 @@
import type { DifyClientConfig } from '../src/types/common'
import { vi } from 'vite-plus/test'
import { HttpClient } from '../src/http/client'
type FetchMock = ReturnType<typeof vi.fn>
type RequestSpy = ReturnType<typeof vi.fn>
type HttpClientWithFetchMock = {
client: HttpClient
fetchMock: FetchMock
}
type HttpClientWithSpies = HttpClientWithFetchMock & {
request: RequestSpy
requestStream: RequestSpy
requestBinaryStream: RequestSpy
}
export const createHttpClient = (
configOverrides: Partial<DifyClientConfig> = {},
): HttpClientWithFetchMock => {
const fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
const client = new HttpClient({ apiKey: 'test', ...configOverrides })
return { client, fetchMock }
}
export const createHttpClientWithSpies = (
configOverrides: Partial<DifyClientConfig> = {},
): HttpClientWithSpies => {
const { client, fetchMock } = createHttpClient(configOverrides)
const request = vi
.spyOn(client, 'request')
.mockResolvedValue({ data: 'ok', status: 200, headers: {} })
const requestStream = vi
.spyOn(client, 'requestStream')
.mockResolvedValue({ data: null, status: 200, headers: {} } as never)
const requestBinaryStream = vi
.spyOn(client, 'requestBinaryStream')
.mockResolvedValue({ data: null, status: 200, headers: {} } as never)
return {
client,
fetchMock,
request,
requestStream,
requestBinaryStream,
}
}