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,560 @@
/* oxlint-disable antfu/no-import-dist -- Audit the built native mapper against generated repository contracts. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import {
globSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from 'node:fs'
import { join, relative, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { loadConsoleDocument } from '../../contracts/scripts/compose-console-openapi.mjs'
import { describeOperations } from '../dist/operation.js'
import { createRouter } from '../dist/tooling/router.js'
/* oxlint-enable antfu/no-import-dist */
const root = resolve(import.meta.dirname, '..')
const repo = resolve(root, '../..')
const specDir = process.env.DIFY_OPENAPI_DIR ?? resolve(root, '../contracts/openapi')
const enforceAlignment = process.argv.includes('--check')
const consoleOnly = process.argv.includes('--console')
const updateBaseline = process.argv.includes('--update-baseline')
const output = resolve(
process.argv.slice(2).find((arg) => !arg.startsWith('--')) ??
join(root, 'reports/orpc-comparison.json'),
)
const documents = consoleOnly
? ['console-client']
: ['console', 'fastopenapi-console', 'service', 'openapi', 'web', 'inner', 'knowledge-fs']
const report = {
scope:
'All repository OpenAPI operations versus existing generated/api oRPC procedures; static schema input/output types, not validation, errors or transport execution.',
documents: [],
matched: [],
unmatchedOpenApi: [],
unmatchedOrpc: [],
compilerErrors: [],
}
const key = (surface, method, path) => `${surface} ${method.toUpperCase()} ${path}`
report.sourceRevision = spawnSync('git', ['rev-parse', 'HEAD'], {
cwd: repo,
encoding: 'utf8',
}).stdout.trim()
report.compilerVersion = spawnSync(
process.execPath,
[join(root, 'node_modules/typescript/bin/tsc'), '--version'],
{ encoding: 'utf8' },
).stdout.trim()
report.generatedFiles = [...globSync(join(repo, 'packages/contracts/generated/api/**/*.ts'))]
.sort()
.map((file) => ({
file: relative(repo, file),
sha256: createHash('sha256').update(readFileSync(file)).digest('hex'),
}))
report.sdkTypeSourceSha256 = createHash('sha256')
.update(readFileSync(join(root, 'src/types.ts')))
.digest('hex')
const contracts = new Map()
const contractFiles = consoleOnly
? [
...globSync(join(repo, 'packages/contracts/generated/api/console/**/orpc.gen.ts')),
join(repo, 'packages/contracts/generated/enterprise/orpc.gen.ts'),
join(repo, 'packages/contracts/generated/enterprise-app-deploy/orpc.gen.ts'),
]
: [...globSync(join(repo, 'packages/contracts/generated/api/**/orpc.gen.ts'))]
for (const file of contractFiles.sort()) {
// oxlint-disable-next-line antfu/no-top-level-await -- This CLI must load contract metadata before generating the audit.
const exports = await import(pathToFileURL(file))
const surface = consoleOnly
? 'console'
: relative(join(repo, 'packages/contracts/generated/api'), file).split('/')[0]
for (const [name, value] of Object.entries(exports)) {
const def = value?.['~orpc']
if (!def) continue
const id = key(surface, def.route.method, def.route.path)
assert(!contracts.has(id), `Duplicate generated procedure: ${id}`)
contracts.set(id, {
id,
file: relative(repo, file),
name,
hasInputSchema: !!def.inputSchema,
hasOutputSchema: !!def.outputSchema,
})
}
}
function* routes(node, members = []) {
for (const [method, operation] of node.methods) yield { operation, members: [...members, method] }
for (const [name, child] of node.children) yield* routes(child, [...members, name])
}
function deref(schema, spec) {
while (schema?.$ref?.startsWith('#/'))
schema = schema.$ref
.slice(2)
.split('/')
.reduce((v, k) => v?.[k.replaceAll('~1', '/').replaceAll('~0', '~')], spec)
return schema
}
const dir = mkdtempSync(join(root, 'integration/.compare-'))
const lines = []
const assertions = new Map()
const add = (text) => lines.push(text)
const check = (row, name, expression, expected = true) => {
add(`const c${row}_${name}: ${expression} = ${expected};`)
assertions.set(lines.length, { row, name, expected })
report.matched[row].checks[name] = expected
}
try {
add("type Schema = { '~standard': { types?: { input: unknown; output: unknown } } };")
add("type Contract = { '~orpc': { inputSchema?: Schema; outputSchema?: Schema } };")
add(
"type Input<T extends Contract> = NonNullable<NonNullable<T['~orpc']['inputSchema']>['~standard']['types']>['input'];",
)
add(
"type Output<T extends Contract> = NonNullable<NonNullable<T['~orpc']['outputSchema']>['~standard']['types']>['output'];",
)
add(
"type WireOutput<T extends Contract> = NonNullable<NonNullable<T['~orpc']['outputSchema']>['~standard']['types']>['input'];",
)
add('type NormalizeVoid<T> = T extends void ? undefined : T;')
add('type Ext<A,B> = [A] extends [B] ? true : false;')
add('type Any<T> = 0 extends (1 & T) ? true : false;')
add('type Unknown<T> = unknown extends T ? true : false;')
add('type Never<T> = [T] extends [never] ? true : false;')
add(
'type Field<T,K extends PropertyKey> = T extends unknown ? K extends keyof T ? T[K] : undefined : never;',
)
add(
"type RenameHeader<T> = T extends { header: infer H } ? Omit<T,'header'|'headers'> & { headers: H } : T extends { header?: infer H } ? Omit<T,'header'|'headers'> & { headers?: H } : T;",
)
add(
"type SplitBody<T, B = T extends {body: infer Body} ? Body : never> = [B] extends [never] ? T : B extends unknown ? Omit<T,'body'> & {body:B} : never;",
)
add("type WithoutContentType<T> = T extends unknown ? Omit<T, 'contentType'> : never;")
for (const [docIndex, name] of documents.entries()) {
const file =
name === 'knowledge-fs'
? join(repo, 'api/knowledge-fs-contract/knowledge-fs.openapi.json')
: join(specDir, `${name}-openapi.json`)
const bytes = consoleOnly ? JSON.stringify(loadConsoleDocument()) : readFileSync(file)
const spec = JSON.parse(bytes)
const inventory = [...routes(createRouter(describeOperations(spec)))]
report.documents.push({
name,
operations: inventory.length,
sha256: createHash('sha256').update(bytes).digest('hex'),
})
if (!consoleOnly) symlinkSync(file, join(dir, `${name}.openapi`))
const specifier = consoleOnly
? join(repo, 'packages/openapi-content-mapper/examples/repository/console.openapi-source')
: `./${name}.openapi`
add(`import { api as api${docIndex} } from ${JSON.stringify(specifier)};`)
for (const { operation, members } of inventory) {
const surface = consoleOnly || name === 'fastopenapi-console' ? 'console' : name
const path =
name === 'fastopenapi-console'
? operation.path.replace(/^\/console\/api(?=\/|$)/, '') || '/'
: operation.path
const id = key(surface, operation.method, path)
const contract = contracts.get(id)
if (!contract) {
report.unmatchedOpenApi.push({
document: name,
method: operation.method,
path: operation.path,
reason: ['inner', 'knowledge-fs'].includes(name)
? 'No generated/api oRPC surface exists'
: 'No generated procedure for method and path',
responseStatuses: Object.keys(
spec.paths[operation.path][operation.method].responses ?? {},
),
})
continue
}
contracts.delete(id)
const row = report.matched.length
const op = spec.paths[operation.path][operation.method]
const responses = Object.entries(op.responses ?? {})
.filter(([status]) => /^2\d\d$/.test(status))
.map(([status, r]) => ({ status, ...deref(r, spec) }))
const content = deref(op.requestBody, spec)?.content ?? {}
report.matched.push({
id,
document: name,
path: operation.path,
method: operation.method,
sdkMembers: members,
contract,
traits: {
requestMedia: Object.keys(content),
responseMedia: [...new Set(responses.flatMap((r) => Object.keys(r.content ?? {})))],
successStatuses: responses.map((r) => r.status),
jsonBinaryResponse: responses.some((r) => {
const schema = deref(r.content?.['application/json']?.schema, spec)
return schema?.type === 'string' && schema.format === 'binary'
}),
opaqueResponse: responses.some(
(r) =>
!['204', '205'].includes(r.status) &&
(!r.content || Object.values(r.content).some((m) => !m.schema)),
),
},
checks: {},
})
add(
`import type { ${contract.name} as proc${row} } from ${JSON.stringify(resolve(repo, contract.file))};`,
)
add(
`type S${row} = typeof api${docIndex}${members.map((k) => `[${JSON.stringify(k)}]`).join('')};`,
)
add(`type NI${row} = Parameters<S${row}>[0]; type NO${row} = Awaited<ReturnType<S${row}>>;`)
add(`type OI${row} = Input<typeof proc${row}>; type OO${row} = Output<typeof proc${row}>;`)
for (const [label, a, b] of [
['inputSdkToOrpc', `NI${row}`, `OI${row}`],
['inputOrpcToSdk', `OI${row}`, `NI${row}`],
['outputSdkToOrpc', `NO${row}`, `OO${row}`],
['outputOrpcToSdk', `OO${row}`, `NO${row}`],
])
check(row, label, `Ext<${a},${b}>`)
for (const [label, t] of [
['sdkInput', `NI${row}`],
['orpcInput', `OI${row}`],
['sdkOutput', `NO${row}`],
['orpcOutput', `OO${row}`],
]) {
for (const guard of ['Any', 'Unknown', 'Never'])
check(row, `${label}${guard}`, `${guard}<${t}>`, false)
}
check(row, 'renamedHeaderSdkToOrpc', `Ext<RenameHeader<NI${row}>,OI${row}>`)
check(row, 'renamedHeaderOrpcToSdk', `Ext<OI${row},RenameHeader<NI${row}>>`)
check(row, 'sdkOutputString', `Ext<NO${row},string>`)
check(row, 'orpcOutputBlob', `Ext<OO${row},Blob>`)
check(row, 'sdkAcceptsOmittedInput', `Ext<undefined,NI${row}>`)
check(row, 'wireOutputSdkToOrpc', `Ext<NO${row},WireOutput<typeof proc${row}>>`)
check(row, 'wireOutputOrpcToSdk', `Ext<WireOutput<typeof proc${row}>,NO${row}>`)
check(row, 'normalizedVoidSdkToOrpc', `Ext<NormalizeVoid<NO${row}>,NormalizeVoid<OO${row}>>`)
check(row, 'normalizedVoidOrpcToSdk', `Ext<NormalizeVoid<OO${row}>,NormalizeVoid<NO${row}>>`)
for (const field of ['body', 'query', 'params', 'headers', 'header', 'cookie']) {
check(
row,
`${field}SdkToOrpc`,
`Ext<Field<NI${row},'${field}'>,Field<OI${row},'${field}'>>`,
)
check(
row,
`${field}OrpcToSdk`,
`Ext<Field<OI${row},'${field}'>,Field<NI${row},'${field}'>>`,
)
}
if (report.matched[row].traits.responseMedia.includes('text/event-stream')) {
check(
row,
'nonStreamSdkToOrpc',
`Ext<Exclude<NO${row},ReadableStream<Uint8Array>>,Exclude<OO${row},string>>`,
)
check(
row,
'nonStreamOrpcToSdk',
`Ext<Exclude<OO${row},string>,Exclude<NO${row},ReadableStream<Uint8Array>>>`,
)
}
if (report.matched[row].traits.responseMedia.includes('text/event-stream')) {
check(
row,
'nonStreamWireSdkToOrpc',
`Ext<Exclude<NO${row},ReadableStream<Uint8Array>>,Exclude<WireOutput<typeof proc${row}>,string>>`,
)
check(
row,
'nonStreamWireOrpcToSdk',
`Ext<Exclude<WireOutput<typeof proc${row}>,string>,Exclude<NO${row},ReadableStream<Uint8Array>>>`,
)
}
if (Object.keys(content).includes('multipart/form-data')) {
check(row, 'withoutContentTypeSdkToOrpc', `Ext<WithoutContentType<NI${row}>,OI${row}>`)
check(
row,
'withoutContentTypeOrpcToSdk',
`Ext<SplitBody<OI${row}>,WithoutContentType<NI${row}>>`,
)
check(
row,
'multipartSdkToOrpc',
`Ext<WithoutContentType<Extract<NI${row},{contentType?:'multipart/form-data'}>>,OI${row}>`,
)
check(
row,
'multipartOrpcToSdk',
`Ext<OI${row},WithoutContentType<Extract<NI${row},{contentType?:'multipart/form-data'}>>>`,
)
}
}
}
report.unmatchedOrpc = [...contracts.values()]
writeFileSync(join(dir, 'check.ts'), lines.join('\n'))
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
allowImportingTsExtensions: true,
types: ['node'],
lib: ['ES2022', 'DOM'],
},
contentMappers: [
{
package: root,
extensions: ['.openapi', '.openapi-source'],
options: {
sources: consoleOnly
? [
join(
repo,
'packages/openapi-content-mapper/examples/repository/console.openapi-source',
),
]
: [],
},
},
],
include: ['*.ts'],
}),
)
const started = performance.now()
const result = spawnSync(
process.execPath,
[
join(root, 'node_modules/typescript/bin/tsc'),
'--runExternalCode',
'--pretty',
'false',
'-p',
dir,
],
{ cwd: root, encoding: 'utf8', timeout: 180000, maxBuffer: 32 * 1024 * 1024 },
)
assert.ifError(result.error)
assert(
[0, 2].includes(result.status),
`Compiler failed: ${result.status} ${result.signal}\n${result.stdout}\n${result.stderr}`,
)
for (const diagnostic of result.stdout.split('\n').filter(Boolean)) {
const m = /check\.ts\((\d+),\d+\): error TS(\d+): (.*)/.exec(diagnostic)
const assertion = m && assertions.get(Number(m[1]))
if (
assertion &&
m[2] === '2322' &&
/^Type '(?:true|false)' is not assignable to type '(?:true|false)'\.$/.test(m[3])
)
report.matched[assertion.row].checks[assertion.name] = !assertion.expected
else report.compilerErrors.push({ diagnostic, source: m ? lines[Number(m[1]) - 1] : undefined })
}
if (result.stderr.trim()) report.compilerErrors.push({ diagnostic: result.stderr })
for (const row of report.matched) {
const c = row.checks
row.inputCategory =
c.inputSdkToOrpc && c.inputOrpcToSdk
? 'compatible'
: !row.contract.hasInputSchema && c.orpcInputUnknown && c.sdkAcceptsOmittedInput
? 'no-input-schema'
: c.renamedHeaderSdkToOrpc && c.renamedHeaderOrpcToSdk
? 'header-vs-headers'
: c.withoutContentTypeSdkToOrpc && c.withoutContentTypeOrpcToSdk
? 'multipart-selection'
: c.multipartSdkToOrpc && c.multipartOrpcToSdk
? 'multipart-selection'
: 'schema-difference'
row.outputCategory =
c.outputSdkToOrpc && c.outputOrpcToSdk
? 'compatible'
: c.normalizedVoidSdkToOrpc && c.normalizedVoidOrpcToSdk
? 'void-vs-undefined'
: c.nonStreamSdkToOrpc && c.nonStreamOrpcToSdk
? 'raw-stream-vs-string'
: c.nonStreamWireSdkToOrpc && c.nonStreamWireOrpcToSdk
? 'raw-stream-and-parsed-defaults'
: c.wireOutputSdkToOrpc && c.wireOutputOrpcToSdk
? 'parsed-vs-wire-output'
: row.traits.jsonBinaryResponse && c.sdkOutputString && c.orpcOutputBlob
? 'json-binary-vs-blob'
: row.traits.opaqueResponse && c.sdkOutputUnknown
? 'undocumented-output'
: 'schema-difference'
}
// Produce real assignability diagnostics for differences that remain after the
// explicit representation checks. These are evidence, not inferred labels.
if (!report.compilerErrors.length) {
const detailLines = [...lines]
for (const [line, { row, name }] of assertions)
detailLines[line - 1] = detailLines[line - 1].replace(
/= (?:true|false);$/,
`= ${report.matched[row].checks[name]};`,
)
const details = new Map()
for (const [i, row] of report.matched.entries()) {
for (const [category, a, b] of [
['input', `NI${i}`, `OI${i}`],
['output', `NO${i}`, `OO${i}`],
['wireOutput', `NO${i}`, `WireOutput<typeof proc${i}>`],
]) {
if (
category === 'wireOutput'
? row.outputCategory !== 'schema-difference'
: row[`${category}Category`] !== 'schema-difference' &&
row[`${category}Category`] !== 'parsed-vs-wire-output'
)
continue
for (const [direction, from, to] of [
['sdkToOrpc', a, b],
['orpcToSdk', b, a],
]) {
detailLines.push(`const detail${i}_${category}_${direction}: ${to} = null! as ${from};`)
details.set(detailLines.length, { row: i, category, direction })
}
}
}
writeFileSync(join(dir, 'check.ts'), detailLines.join('\n'))
const diagnostics = spawnSync(
process.execPath,
[
join(root, 'node_modules/typescript/bin/tsc'),
'--runExternalCode',
'--pretty',
'false',
'-p',
dir,
],
{ cwd: root, encoding: 'utf8', timeout: 180000, maxBuffer: 64 * 1024 * 1024 },
)
assert.ifError(diagnostics.error)
assert(
[0, 2].includes(diagnostics.status),
`Diagnostic compilation failed: ${diagnostics.status}`,
)
for (const block of diagnostics.stdout
.split(/(?=^.*check\.ts\(\d+,\d+\): error TS)/m)
.filter(Boolean)) {
const match = /check\.ts\((\d+),\d+\): error TS(\d+): ([\s\S]*)/.exec(block)
const detail = match && details.get(Number(match[1]))
if (!detail || !['2322', '2741', '2739', '2559'].includes(match[2]))
report.compilerErrors.push({ diagnostic: block })
else
(report.matched[detail.row].diagnostics ??= []).push({
category: detail.category,
direction: detail.direction,
message: match[3].trim(),
})
}
if (diagnostics.stderr.trim()) report.compilerErrors.push({ diagnostic: diagnostics.stderr })
}
report.categories = { input: {}, output: {} }
for (const row of report.matched)
for (const kind of ['input', 'output']) {
const category = row[`${kind}Category`]
report.categories[kind][category] = (report.categories[kind][category] ?? 0) + 1
}
report.compilerMilliseconds = Math.round(performance.now() - started)
report.valid = report.compilerErrors.length === 0
report.summary = {
matched: report.matched.length,
fullyAssignable: report.matched.filter((r) =>
['inputSdkToOrpc', 'inputOrpcToSdk', 'outputSdkToOrpc', 'outputOrpcToSdk'].every(
(k) => r.checks[k],
),
).length,
inputMismatch: report.matched.filter(
(r) => !r.checks.inputSdkToOrpc || !r.checks.inputOrpcToSdk,
).length,
outputMismatch: report.matched.filter(
(r) => !r.checks.outputSdkToOrpc || !r.checks.outputOrpcToSdk,
).length,
unmatchedOpenApi: report.unmatchedOpenApi.length,
unmatchedOrpc: report.unmatchedOrpc.length,
compilerErrors: report.compilerErrors.length,
}
report.summary.topLevelAnyOrNever = report.matched.filter((r) =>
Object.entries(r.checks).some(([k, v]) => /Any$|Never$/.test(k) && v),
).length
report.summary.inputAndOutputMismatch = report.matched.filter(
(r) =>
(!r.checks.inputSdkToOrpc || !r.checks.inputOrpcToSdk) &&
(!r.checks.outputSdkToOrpc || !r.checks.outputOrpcToSdk),
).length
report.coverage = report.documents.map((d) => ({
document: d.name,
total: d.operations,
compared: report.matched.filter((r) => r.document === d.name).length,
}))
const acceptedInputs = new Set(['compatible', 'no-input-schema', 'multipart-selection'])
const acceptedOutputs = new Set([
'compatible',
'parsed-vs-wire-output',
'undocumented-output',
'raw-stream-vs-string',
'raw-stream-and-parsed-defaults',
'json-binary-vs-blob',
])
report.summary.unexplainedDifferences = report.matched.filter(
(row) => !acceptedInputs.has(row.inputCategory) || !acceptedOutputs.has(row.outputCategory),
).length
mkdirSync(resolve(output, '..'), { recursive: true })
writeFileSync(output, `${JSON.stringify(report, null, 2)}\n`)
process.stdout.write(
JSON.stringify(
{
...report.summary,
categories: report.categories,
compilerMilliseconds: report.compilerMilliseconds,
report: output,
},
null,
2,
),
)
assert.equal(
report.compilerErrors.length,
0,
'Unexpected compiler errors invalidate this audit; see report',
)
if (consoleOnly) {
const baselinePath = join(root, 'integration/console-type-differences.json')
const differences = Object.fromEntries(
report.matched
.filter((row) => row.inputCategory !== 'compatible' || row.outputCategory !== 'compatible')
.map((row) => [row.id, [row.inputCategory, row.outputCategory]])
.sort(([a], [b]) => a.localeCompare(b)),
)
if (updateBaseline) writeFileSync(baselinePath, `${JSON.stringify(differences, null, 2)}\n`)
else
assert.deepEqual(
differences,
JSON.parse(readFileSync(baselinePath, 'utf8')),
'Console type differences changed; inspect the report before updating the reviewed baseline',
)
}
if (enforceAlignment) {
assert.equal(report.summary.topLevelAnyOrNever, 0, 'Vacuous types invalidate compatibility')
assert.equal(
report.summary.unexplainedDifferences,
0,
'Unexpected oRPC type differences; see report',
)
assert.equal(report.summary.unmatchedOrpc, 0, 'Every generated procedure must be compared')
if (consoleOnly)
assert.equal(
report.summary.unmatchedOpenApi,
0,
'Every Console operation must have a contract',
)
}
} finally {
rmSync(dir, { recursive: true, force: true })
}
@@ -0,0 +1,76 @@
/* oxlint-disable vitest/no-import-node-test -- Verify the repository editor setup through the native language server. */
import assert from 'node:assert/strict'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { pathToFileURL } from 'node:url'
import { rpcProcess } from '../test/rpc.mjs'
/* oxlint-enable vitest/no-import-node-test */
const root = resolve(import.meta.dirname, '..')
const repo = resolve(root, '../..')
const web = join(repo, 'web')
test('workspace TS 7.1 resolves composed Console completions and request types from backend sources', async () => {
const settings = JSON.parse(readFileSync(join(repo, '.vscode/settings.example.json'), 'utf8'))
assert.equal(settings['js/ts.contentMappers.enabled'], true)
const compiler = join(repo, settings['js/ts.tsdk.path'], 'bin/tsc')
const directory = mkdtempSync(join(web, '.console-editor-'))
const document = join(
repo,
'packages/openapi-content-mapper/examples/repository/console.openapi-source',
)
const source = [
`import { api as consoleClient, query as consoleQuery } from ${JSON.stringify(document)};`,
"const options = consoleQuery.knowledgeFs.spaces.byControlSpaceId.metadata.get.queryOptions({ input: { params: { control_space_id: 'space' } } });",
'consoleClient.enterprise.appDeploy.accessService.',
].join('\n')
writeFileSync(join(directory, 'index.ts'), source)
writeFileSync(
join(directory, 'tsconfig.json'),
JSON.stringify({
extends: '../tsconfig.json',
contentMappers: [
{
package: '@dify/openapi-content-mapper',
extensions: ['.openapi-source'],
options: { sources: [document] },
},
],
include: ['index.ts', '../next-env.d.ts', '../global.d.ts', '../types/**/*.d.ts'],
}),
)
const rpc = rpcProcess(process.execPath, [compiler, '--lsp', '--stdio'], repo, 60000)
const uri = pathToFileURL(join(directory, 'index.ts')).href
try {
await rpc.request('initialize', {
processId: process.pid,
rootUri: pathToFileURL(repo).href,
initializationOptions: { runExternalCode: true },
workspaceFolders: [{ uri: pathToFileURL(repo).href, name: 'dify' }],
capabilities: {
general: { positionEncodings: ['utf-16'] },
textDocument: { hover: { contentFormat: ['plaintext'] } },
},
})
rpc.notify('initialized', {})
rpc.notify('textDocument/didOpen', {
textDocument: { uri, languageId: 'typescript', version: 1, text: source },
})
const completions = await rpc.request('textDocument/completion', {
textDocument: { uri },
position: { line: 2, character: source.split('\n')[2].length },
})
const labels = (completions.items ?? completions).map((item) => item.label)
assert(labels.includes('getEnvironmentApi'), JSON.stringify(labels))
assert(labels.includes('updateEnvironmentApi'))
const position = { line: 1, character: source.split('\n')[1].indexOf('.get.') + 2 }
const hover = await rpc.request('textDocument/hover', { textDocument: { uri }, position })
assert.match(JSON.stringify(hover), /control_space_id/)
await rpc.request('shutdown')
rpc.notify('exit')
} finally {
rpc.close()
rmSync(directory, { recursive: true, force: true })
}
})
@@ -0,0 +1,125 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Verify the composed migration surface against the existing public contract. */
import assert from 'node:assert/strict'
import { existsSync } from 'node:fs'
import { test } from 'node:test'
import { consoleRouterContract } from '../../contracts/console.ts'
import {
composeConsoleDocuments,
loadConsoleDocument,
} from '../../contracts/scripts/compose-console-openapi.mjs'
import { describeOperations } from '../dist/operation.js'
import { createRouter } from '../dist/tooling/router.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const files = [
'console-openapi.json',
'fastopenapi-console-openapi.json',
'console-client-openapi.json',
].map((name) => new URL(`../../contracts/openapi/${name}`, import.meta.url))
test('every existing Console member retains its name, HTTP method and route', (t) => {
const before = files.map((file) => existsSync(file))
const document = loadConsoleDocument()
assert.deepEqual(loadConsoleDocument(), document, 'In-memory composition must be deterministic')
assert.deepEqual(
files.map((file) => existsSync(file)),
before,
'Export must not create OpenAPI files',
)
const operations = describeOperations(document)
const router = createRouter(operations)
const visited = new Set()
function walk(node, path = []) {
const definition = node['~orpc']
if (!definition) {
for (const [key, child] of Object.entries(node)) walk(child, [...path, key])
return
}
let current = router
for (const member of path.slice(0, -1)) current = current?.children.get(member)
const operation = current?.methods.get(path.at(-1))
assert(operation, `Missing client member: ${path.join('.')}`)
assert.equal(operation.path, definition.route.path, path.join('.'))
assert.equal(operation.method.toUpperCase(), definition.route.method, path.join('.'))
assert(!visited.has(operation), `Two members resolve to the same operation: ${path.join('.')}`)
visited.add(operation)
}
walk(consoleRouterContract)
assert.equal(
visited.size,
operations.size,
'The composed client must not introduce unmatched operations',
)
t.diagnostic(
`${visited.size} Console operations, including Enterprise, App Deploy and FastOpenAPI`,
)
})
test('Human Input v2 keeps the legacy Console client members', () => {
const responses = { 204: { description: 'Success' } }
const document = composeConsoleDocuments([
{
name: 'console',
document: {
openapi: '3.1.0',
paths: {
'/form/human_input/{form_token}': { get: { responses }, post: { responses } },
'/form/human-input/v2/{form_token}': { get: { responses }, post: { responses } },
},
},
},
])
const router = createRouter(describeOperations(document))
const humanInput = router.children.get('form')?.children.get('humanInput')
for (const method of ['get', 'post']) {
assert.equal(
humanInput?.children.get('byFormToken')?.methods.get(method)?.path,
'/form/human_input/{form_token}',
)
assert.equal(
humanInput?.children.get('v2')?.children.get('byFormToken')?.methods.get(method)?.path,
'/form/human-input/v2/{form_token}',
)
}
})
test('composition isolates schemas and rejects ambiguous routes and external references', () => {
const source = (path, type) => ({
openapi: '3.1.0',
paths: {
[path]: {
get: {
responses: {
200: {
content: { 'application/json': { schema: { $ref: '#/components/schemas/Value' } } },
},
},
},
},
},
components: { schemas: { Value: { type } } },
})
const composed = composeConsoleDocuments([
{ name: 'a', document: source('/a', 'string') },
{ name: 'b', document: source('/b', 'number') },
])
assert.equal(composed.components.schemas.a_Value.type, 'string')
assert.equal(
composed.paths['/b'].get.responses[200].content['application/json'].schema.$ref,
'#/components/schemas/b_Value',
)
assert.throws(
() =>
composeConsoleDocuments([
{ name: 'a', document: source('/a', 'string') },
{ name: 'b', document: source('/a', 'number') },
]),
/Duplicate Console path/,
)
const external = source('/a', 'string')
external.components.schemas.Value = { $ref: 'external.json#/Value' }
assert.throws(
() => composeConsoleDocuments([{ name: 'a', document: external }]),
/Unsupported reference/,
)
})
@@ -0,0 +1,770 @@
{
"console DELETE /workspaces/current/human-input/v2/contacts/{contact_id}/im-override": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /account/delete/verify": ["no-input-schema", "compatible"],
"console GET /account/education": ["no-input-schema", "compatible"],
"console GET /account/education/verify": ["no-input-schema", "compatible"],
"console GET /account/integrates": ["no-input-schema", "compatible"],
"console GET /account/profile": ["no-input-schema", "compatible"],
"console GET /agent": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/api-access": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/api-keys": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/build-draft": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/chat-messages": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/composer": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/composer/candidates": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/config/files": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/config/manifest": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/config/skills": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/config/skills/{name}/files/content": [
"compatible",
"undocumented-output"
],
"console GET /agent/{agent_id}/config/skills/{name}/inspect": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /agent/{agent_id}/logs/{conversation_id}/messages": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /agent/{agent_id}/messages/{message_id}": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/sandbox/files": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/trace": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/{agent_id}/versions/{version_id}": ["compatible", "parsed-vs-wire-output"],
"console GET /agent/invite-options": ["compatible", "parsed-vs-wire-output"],
"console GET /api-based-extension": ["no-input-schema", "compatible"],
"console GET /api-key-auth/data-source": ["no-input-schema", "compatible"],
"console GET /app-dsl-version": ["no-input-schema", "compatible"],
"console GET /apps": ["compatible", "parsed-vs-wire-output"],
"console GET /apps/{app_id}/agent/config/files": ["compatible", "parsed-vs-wire-output"],
"console GET /apps/{app_id}/agent/config/manifest": ["compatible", "parsed-vs-wire-output"],
"console GET /apps/{app_id}/agent/config/skills": ["compatible", "parsed-vs-wire-output"],
"console GET /apps/{app_id}/agent/config/skills/{name}/files/content": [
"compatible",
"undocumented-output"
],
"console GET /apps/{app_id}/agent/config/skills/{name}/inspect": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{app_id}/annotation-reply/{action}/status/{job_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{app_id}/annotations/batch-import-status/{job_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{app_id}/chat-messages": ["compatible", "parsed-vs-wire-output"],
"console GET /apps/{app_id}/messages/{message_id}": ["compatible", "parsed-vs-wire-output"],
"console GET /apps/{app_id}/trace": ["compatible", "parsed-vs-wire-output"],
"console GET /apps/{app_id}/workflow-runs/{workflow_run_id}/agent-nodes/{node_id}/sandbox/files": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/candidates": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{app_id}/workflows/draft/runs/{run_id}/node-outputs": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{app_id}/workflows/draft/runs/{run_id}/node-outputs/{node_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{app_id}/workflows/published/runs/{run_id}/node-outputs": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{app_id}/workflows/published/runs/{run_id}/node-outputs/{node_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /apps/{resource_id}/api-keys": ["compatible", "parsed-vs-wire-output"],
"console GET /apps/starred": ["compatible", "parsed-vs-wire-output"],
"console GET /auth/plugin/datasource/default-list": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /auth/plugin/datasource/list": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /billing/invoices": ["no-input-schema", "compatible"],
"console GET /data-source/integrates": ["no-input-schema", "compatible"],
"console GET /datasets/{dataset_id}/documents": ["compatible", "parsed-vs-wire-output"],
"console GET /datasets/{dataset_id}/documents/{document_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /datasets/{dataset_id}/documents/{document_id}/summary-status": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /datasets/{dataset_id}/metadata": ["compatible", "parsed-vs-wire-output"],
"console GET /datasets/{resource_id}/api-keys": ["compatible", "parsed-vs-wire-output"],
"console GET /datasets/api-base-info": ["no-input-schema", "compatible"],
"console GET /datasets/api-keys": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /datasets/knowledge-fs-upgrade-jobs": ["no-input-schema", "compatible"],
"console GET /datasets/metadata/built-in": ["no-input-schema", "compatible"],
"console GET /datasets/process-rule": ["compatible", "parsed-vs-wire-output"],
"console GET /datasets/retrieval-setting": ["no-input-schema", "compatible"],
"console GET /enterprise/sso/oauth2/login": ["no-input-schema", "compatible"],
"console GET /enterprise/sso/oidc/login": ["no-input-schema", "compatible"],
"console GET /enterprise/sso/saml/login": ["no-input-schema", "compatible"],
"console GET /features": ["no-input-schema", "compatible"],
"console GET /features/vector-space": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /files/support-type": ["no-input-schema", "compatible"],
"console GET /files/upload": ["no-input-schema", "compatible"],
"console GET /form/human-input/v2/{form_token}": ["compatible", "parsed-vs-wire-output"],
"console GET /init": ["no-input-schema", "compatible"],
"console GET /installed-apps/{installed_app_id}/messages": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /installed-apps/{installed_app_id}/messages/{message_id}/more-like-this": [
"compatible",
"undocumented-output"
],
"console GET /knowledge-fs/.well-known/jwks.json": ["no-input-schema", "compatible"],
"console GET /knowledge-fs/features": ["no-input-schema", "compatible"],
"console GET /knowledge-fs/research-tasks/{task_id}/events": [
"compatible",
"raw-stream-vs-string"
],
"console GET /knowledge-fs/spaces": ["compatible", "parsed-vs-wire-output"],
"console GET /knowledge-fs/spaces/{control_space_id}": ["compatible", "parsed-vs-wire-output"],
"console GET /knowledge-fs/spaces/{control_space_id}/documents/{document_id}/revisions/{revision}/chunks": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/documents/{document_id}/revisions/{revision}/chunks/{chunk_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/golden-questions": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/logical-documents": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/logical-documents/{document_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/quality/bad-cases": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/quality/bad-cases/{bad_case_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/settings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/tags": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/traces": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /knowledge-fs/spaces/{control_space_id}/traces/{trace_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /onboarding/step-by-step-tour/state": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /ping": ["no-input-schema", "compatible"],
"console GET /rag/pipelines/datasource-plugins": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /rag/pipelines/recommended-plugins": ["compatible", "parsed-vs-wire-output"],
"console GET /setup": ["no-input-schema", "compatible"],
"console GET /snippets/{snippet_id}/workflows/draft/nodes/{node_id}/agent-composer": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /snippets/{snippet_id}/workflows/draft/nodes/{node_id}/agent-composer/candidates": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /spec/schema-definitions": ["no-input-schema", "compatible"],
"console GET /system-features": ["no-input-schema", "compatible"],
"console GET /system-features/license": ["no-input-schema", "compatible"],
"console GET /trial-apps/{app_id}/agent-composer": ["compatible", "parsed-vs-wire-output"],
"console GET /trial-apps/{app_id}/agent/config/files": ["compatible", "parsed-vs-wire-output"],
"console GET /trial-apps/{app_id}/agent/config/skills": ["compatible", "parsed-vs-wire-output"],
"console GET /trial-apps/{app_id}/agent/config/skills/{name}/inspect": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /trial-models": ["no-input-schema", "compatible"],
"console GET /workflow-run-archives": ["no-input-schema", "compatible"],
"console GET /workflow/{workflow_run_id}/pause-details": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/human-input/v2/channel-providers": [
"no-input-schema",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/human-input/v2/channels": ["no-input-schema", "compatible"],
"console GET /workspaces/current/human-input/v2/channels/email/{channel_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/human-input/v2/channels/im/{channel_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces": ["no-input-schema", "compatible"],
"console GET /workspaces/{tenant_id}/model-providers/{provider}/{icon_type}/{lang}": [
"compatible",
"undocumented-output"
],
"console GET /workspaces/current/agent-provider/{provider_name}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/agent-providers": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /workspaces/current/dataset-operators": ["no-input-schema", "compatible"],
"console GET /workspaces/current/default-model": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/endpoints/list": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/endpoints/list/plugin": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/human-input/v2/contacts": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/human-input/v2/contacts/{contact_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/human-input/v2/contacts/batch": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/human-input/v2/im-sync-runs/latest": [
"no-input-schema",
"compatible"
],
"console GET /workspaces/current/human-input/v2/im-sync-runs/latest/results": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/model-providers": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/model-providers/{provider}/models": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/model-providers/{provider}/models/parameter-rules": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/model-providers/credits": ["no-input-schema", "compatible"],
"console GET /workspaces/current/model-providers/summary": ["no-input-schema", "compatible"],
"console GET /workspaces/current/models/model-types/{model_type}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/network-access-groups": [
"no-input-schema",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/network-access-groups/{group_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/network-access-groups/current-ip": [
"no-input-schema",
"compatible"
],
"console GET /workspaces/current/permission": ["no-input-schema", "compatible"],
"console GET /workspaces/current/plugin/{category}/list": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/plugin/debugging-key": ["no-input-schema", "compatible"],
"console GET /workspaces/current/plugin/fetch-manifest": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/plugin/list": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/plugin/marketplace/pkg": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/plugin/permission/fetch": ["no-input-schema", "compatible"],
"console GET /workspaces/current/rbac/access-policies": [
"no-input-schema",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/access-policies/{policy_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/member-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/agents/{agent_id}/access-policies/{policy_id}/role-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/agents/{agent_id}/access-policy": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/agents/{agent_id}/user-access-policies": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/member-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/apps/{app_id}/access-policies/{policy_id}/role-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/apps/{app_id}/access-policy": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/apps/{app_id}/user-access-policies": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/member-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/datasets/{dataset_id}/access-policies/{policy_id}/role-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/datasets/{dataset_id}/access-policy": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/datasets/{dataset_id}/user-access-policies": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/members/{member_id}/rbac-roles": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/my-permissions": ["no-input-schema", "compatible"],
"console GET /workspaces/current/rbac/role-permissions/catalog": [
"no-input-schema",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/role-permissions/catalog/agent": [
"no-input-schema",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/role-permissions/catalog/app": [
"no-input-schema",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/role-permissions/catalog/dataset": [
"no-input-schema",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/roles": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/rbac/roles/{role_id}": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/rbac/roles/{role_id}/members": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/member-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/role-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/workspace/agents/access-policy": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/member-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/role-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/workspace/apps/access-policy": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/member-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/role-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/rbac/workspace/datasets/access-policy": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/skills": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/skills/{skill_id}": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/skills/{skill_id}/export": ["compatible", "undocumented-output"],
"console GET /workspaces/current/skills/{skill_id}/versions": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/skills/{skill_id}/versions/{version_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/skills/tags": ["no-input-schema", "compatible"],
"console GET /workspaces/current/summary": ["no-input-schema", "compatible"],
"console GET /workspaces/current/tool-labels": ["no-input-schema", "compatible"],
"console GET /workspaces/current/tool-provider/api/get": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/tool-provider/api/tools": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/builtin/{provider}/credential/info": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/builtin/{provider}/credential/schema/{credential_type}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/builtin/{provider}/credentials": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/builtin/{provider}/icon": [
"compatible",
"undocumented-output"
],
"console GET /workspaces/current/tool-provider/builtin/{provider}/info": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/builtin/{provider}/oauth/client-schema": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/builtin/{provider}/oauth/custom-client": [
"compatible",
"undocumented-output"
],
"console GET /workspaces/current/tool-provider/builtin/{provider}/tools": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/mcp/tools/{provider_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/mcp/update/{provider_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/workflow/get": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-provider/workflow/tools": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/tool-providers": ["compatible", "parsed-vs-wire-output"],
"console GET /workspaces/current/tools/api": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /workspaces/current/tools/builtin": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /workspaces/current/tools/mcp": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /workspaces/current/tools/workflow": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /workspaces/current/trigger-provider/{provider}/icon": [
"compatible",
"undocumented-output"
],
"console GET /workspaces/current/trigger-provider/{provider}/info": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/trigger-provider/{provider}/oauth/client": [
"compatible",
"parsed-vs-wire-output"
],
"console GET /workspaces/current/triggers": ["no-input-schema", "parsed-vs-wire-output"],
"console GET /workspaces/custom-config": ["no-input-schema", "compatible"],
"console PATCH /knowledge-fs/spaces/{control_space_id}": ["compatible", "parsed-vs-wire-output"],
"console PATCH /knowledge-fs/spaces/{control_space_id}/documents/{document_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console PATCH /knowledge-fs/spaces/{control_space_id}/golden-questions/{question_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console PATCH /knowledge-fs/spaces/{control_space_id}/logical-documents": [
"compatible",
"parsed-vs-wire-output"
],
"console PATCH /knowledge-fs/spaces/{control_space_id}/logical-documents/{document_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console PATCH /knowledge-fs/spaces/{control_space_id}/quality/bad-cases/{bad_case_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console PATCH /knowledge-fs/spaces/{control_space_id}/settings": [
"compatible",
"parsed-vs-wire-output"
],
"console PATCH /onboarding/step-by-step-tour/state": ["compatible", "parsed-vs-wire-output"],
"console PATCH /workspaces/current/human-input/v2/contacts/external/{contact_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console PATCH /workspaces/current/skills/{skill_id}": ["compatible", "parsed-vs-wire-output"],
"console PATCH /workspaces/current/skills/{skill_id}/files": [
"compatible",
"parsed-vs-wire-output"
],
"console PATCH /workspaces/current/skills/{skill_id}/versions/{version_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /agent": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/api-enable": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/api-keys": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/build-draft/checkout": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/config/files": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/config/files/batch": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/config/skills/upload": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/copy": ["compatible", "parsed-vs-wire-output"],
"console POST /agent/{agent_id}/debug-conversation/refresh": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /agent/{agent_id}/trace": ["compatible", "parsed-vs-wire-output"],
"console POST /apps/{app_id}/advanced-chat/workflows/draft/human-input/nodes/{node_id}/form/preview": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /apps/{app_id}/agent/config/files": ["compatible", "parsed-vs-wire-output"],
"console POST /apps/{app_id}/agent/config/files/batch": ["compatible", "parsed-vs-wire-output"],
"console POST /apps/{app_id}/agent/config/skills/upload": ["compatible", "parsed-vs-wire-output"],
"console POST /apps/{app_id}/completion-messages": ["compatible", "undocumented-output"],
"console POST /apps/{app_id}/copy": ["compatible", "parsed-vs-wire-output"],
"console POST /apps/{app_id}/text-to-audio": ["compatible", "undocumented-output"],
"console POST /apps/{app_id}/workflows/draft/human-input/nodes/{node_id}/form/preview": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/copy-from-roster": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer/save-to-roster": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /apps/{resource_id}/api-keys": ["compatible", "parsed-vs-wire-output"],
"console POST /apps/imports": ["multipart-selection", "parsed-vs-wire-output"],
"console POST /apps/imports/{import_id}/confirm": ["compatible", "parsed-vs-wire-output"],
"console POST /datasets/{dataset_id}/documents/download-zip": [
"compatible",
"undocumented-output"
],
"console POST /datasets/{dataset_id}/knowledge-fs-upgrades/{job_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /datasets/{resource_id}/api-keys": ["compatible", "parsed-vs-wire-output"],
"console POST /datasets/api-keys": ["compatible", "parsed-vs-wire-output"],
"console POST /installed-apps/{installed_app_id}/chat-messages": [
"compatible",
"undocumented-output"
],
"console POST /installed-apps/{installed_app_id}/completion-messages": [
"compatible",
"undocumented-output"
],
"console POST /installed-apps/{installed_app_id}/workflows/run": [
"compatible",
"undocumented-output"
],
"console POST /knowledge-fs/query-stream": ["compatible", "raw-stream-vs-string"],
"console POST /knowledge-fs/source-provider-preview/jobs": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /knowledge-fs/spaces/{control_space_id}/documents": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /knowledge-fs/spaces/{control_space_id}/golden-questions": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /knowledge-fs/spaces/{control_space_id}/quality/bad-cases": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /logout": ["no-input-schema", "compatible"],
"console POST /rag/pipeline/dataset": ["compatible", "parsed-vs-wire-output"],
"console POST /rag/pipeline/empty-dataset": ["no-input-schema", "compatible"],
"console POST /rag/pipelines/{pipeline_id}/workflows/published/datasource/nodes/{node_id}/preview": [
"compatible",
"undocumented-output"
],
"console POST /rag/pipelines/{pipeline_id}/workflows/published/run": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /rag/pipelines/imports": ["compatible", "parsed-vs-wire-output"],
"console POST /rag/pipelines/imports/{import_id}/confirm": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /refresh-token": ["no-input-schema", "compatible"],
"console POST /snippets/{snippet_id}/workflows/draft/nodes/{node_id}/agent-composer/copy-from-roster": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /snippets/{snippet_id}/workflows/draft/nodes/{node_id}/agent-composer/save-to-roster": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /trial-apps/{app_id}/chat-messages": ["compatible", "undocumented-output"],
"console POST /trial-apps/{app_id}/completion-messages": ["compatible", "undocumented-output"],
"console POST /trial-apps/{app_id}/workflows/run": ["compatible", "undocumented-output"],
"console POST /workflow-generate": ["compatible", "parsed-vs-wire-output"],
"console POST /workflow-generate/stream": ["compatible", "parsed-vs-wire-output"],
"console POST /workspaces/current/human-input/v2/contacts/external": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/human-input/v2/contacts/platform": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/human-input/v2/im-sync-runs": ["no-input-schema", "compatible"],
"console POST /workspaces/current/human-input/v2/node-data-migration": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/network-access-groups": ["compatible", "parsed-vs-wire-output"],
"console POST /workspaces/current/plugin/list/installations/ids": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/plugin/tasks/delete_all": ["no-input-schema", "compatible"],
"console POST /workspaces/current/plugin/upload/bundle": [
"no-input-schema",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/plugin/upload/github": ["compatible", "parsed-vs-wire-output"],
"console POST /workspaces/current/plugin/upload/pkg": ["compatible", "parsed-vs-wire-output"],
"console POST /workspaces/current/rbac/access-policies": ["compatible", "parsed-vs-wire-output"],
"console POST /workspaces/current/rbac/access-policies/{policy_id}/copy": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/rbac/roles": ["compatible", "parsed-vs-wire-output"],
"console POST /workspaces/current/rbac/roles/{role_id}/copy": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/skills": ["compatible", "parsed-vs-wire-output"],
"console POST /workspaces/current/skills/{skill_id}/assist/messages": [
"compatible",
"undocumented-output"
],
"console POST /workspaces/current/skills/{skill_id}/duplicate": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/skills/{skill_id}/publish": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/skills/{skill_id}/restore": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/skills/import": ["compatible", "parsed-vs-wire-output"],
"console POST /workspaces/current/tool-provider/api/schema": [
"compatible",
"parsed-vs-wire-output"
],
"console POST /workspaces/current/tool-provider/mcp": ["compatible", "parsed-vs-wire-output"],
"console PUT /agent/{agent_id}": ["compatible", "parsed-vs-wire-output"],
"console PUT /agent/{agent_id}/build-draft": ["compatible", "parsed-vs-wire-output"],
"console PUT /agent/{agent_id}/composer": ["compatible", "parsed-vs-wire-output"],
"console PUT /apps/{app_id}/workflows/draft/nodes/{node_id}/agent-composer": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /knowledge-fs/spaces/{control_space_id}/tags": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /snippets/{snippet_id}/workflows/draft/nodes/{node_id}/agent-composer": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/human-input/v2/contacts/{contact_id}/im-bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/human-input/v2/contacts/{contact_id}/im-override": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/network-access-groups/{group_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/access-policies/{policy_id}": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/access-policy-bindings/{binding_id}/lock": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/access-policy-bindings/{binding_id}/unlock": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/agents/{agent_id}/users/{target_account_id}/access-policies": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/apps/{app_id}/users/{target_account_id}/access-policies": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/datasets/{dataset_id}/users/{target_account_id}/access-policies": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/members/{member_id}/rbac-roles": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/roles/{role_id}": ["compatible", "parsed-vs-wire-output"],
"console PUT /workspaces/current/rbac/workspace/agents/access-policies/{policy_id}/bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/workspace/apps/access-policies/{policy_id}/bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/rbac/workspace/datasets/access-policies/{policy_id}/bindings": [
"compatible",
"parsed-vs-wire-output"
],
"console PUT /workspaces/current/skills/{skill_id}/files": ["compatible", "parsed-vs-wire-output"]
}
@@ -0,0 +1,166 @@
/* oxlint-disable vitest/no-import-node-test -- Audit the opt-in exports with the native compiler and actual contracts. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { existsSync, globSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import {
exportCompatibilityTypes,
loadCommunityDocuments,
renderCompatibilityTypes,
selectCommunityDocument,
} from '../../contracts/scripts/export-compatibility-types.ts'
/* oxlint-enable vitest/no-import-node-test */
const root = resolve(import.meta.dirname, '..')
const contracts = resolve(root, '../contracts')
const compiler = join(root, 'node_modules/typescript/bin/tsc')
test('all published contracts names and types remain compatible, including snapshot-only enterprise exports', async (t) => {
const dir = mkdtempSync(join(root, 'integration/.contracts-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
const modules = globSync('generated/**/types.gen.ts', { cwd: contracts }).sort()
const documents = { ...loadCommunityDocuments(false), ...loadCommunityDocuments(true) }
let types = 0
let values = 0
for (const [index, file] of modules.entries()) {
const module = file.slice('generated/'.length, -'/types.gen.ts'.length)
const previous = readFileSync(join(contracts, file), 'utf8')
const document = module.startsWith('api/')
? selectCommunityDocument(module, documents)
: undefined
const current = document
? await renderCompatibilityTypes(document)
: await exportCompatibilityTypes(module)
writeFileSync(join(dir, `module${index}.ts`), current)
const checks = [
`import type * as Old from ${JSON.stringify(join(contracts, file).replace(/\.ts$/, '.js'))};`,
`import type * as Current from './module${index}.js';`,
'type Assert<T extends true> = T;',
'type Assignable<A, B> = [A] extends [B] ? true : false;',
'type IsAny<T> = 0 extends (1 & T) ? true : false;',
]
for (const [, name] of previous.matchAll(/^export type (\w+)\s*=/gm)) {
types++
checks.push(
`type OldToNew${name} = Assert<Assignable<Old.${name}, Current.${name}>>;`,
`type NewToOld${name} = Assert<Assignable<Current.${name}, Old.${name}>>;`,
`type NoAny${name} = Assert<Assignable<IsAny<Current.${name}>, IsAny<Old.${name}>>>;`,
)
}
for (const [, name] of previous.matchAll(/^export const (\w+)\s*=/gm)) {
values++
checks.push(
`type OldValue${name} = Assert<Assignable<typeof Old.${name}, typeof Current.${name}>>;`,
`type NewValue${name} = Assert<Assignable<typeof Current.${name}, typeof Old.${name}>>;`,
)
}
writeFileSync(join(dir, `check${index}.ts`), checks.join('\n'))
}
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
lib: ['ES2022', 'DOM'],
},
include: ['*.ts'],
}),
)
const result = spawnSync(process.execPath, [compiler, '-p', dir, '--pretty', 'false'], {
encoding: 'utf8',
timeout: 120000,
maxBuffer: 8 * 1024 * 1024,
})
assert.ifError(result.error)
assert.equal(result.status, 0, result.stdout + result.stderr)
assert(!existsSync(join(contracts, '.compatibility-output')))
t.diagnostic(
`Checked ${modules.length} modules, ${types} named types and ${values} runtime enum objects in both directions`,
)
})
test('mapper subpaths expose the existing types without conditions or changing legacy runtime imports', (t) => {
const dir = mkdtempSync(join(root, 'integration/.subpaths-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
for (const mapper of [false, true]) {
const path = mapper
? '@dify/openapi-content-mapper/console/datasets'
: '@dify/contracts/api/console/datasets/types.gen'
writeFileSync(
join(dir, 'index.ts'),
`
import type {DatasetCreatePayload, PostDatasetsData, PostDatasetsErrors, PostDatasetsResponses, PostDatasetsError, PostDatasetsResponse} from '${path}';
import type {AccessMode} from '${mapper ? '@dify/openapi-content-mapper/enterprise' : '@dify/contracts/enterprise/types.gen'}';
import {AccessMode as AccessModes} from '@dify/contracts/enterprise/types.gen';
const body: DatasetCreatePayload = {name: 'Docs'};
const request: PostDatasetsData = {url: '/datasets', body};
const response: PostDatasetsResponse = null! as PostDatasetsResponses[201];
const error: PostDatasetsError = null! as PostDatasetsErrors[409];
const mode: AccessMode = AccessModes.ACCESS_MODE_PRIVATE;
// @ts-expect-error legacy requests still require the URL
const bad: PostDatasetsData = {body};
// @ts-expect-error status maps must not become any
const wrong: PostDatasetsResponses[201] = 'wrong';
`,
)
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
},
contentMappers: mapper
? [
{
package: root,
extensions: ['.openapi-types'],
},
]
: [],
include: ['index.ts'],
}),
)
const result = spawnSync(
process.execPath,
[compiler, '--runExternalCode', '--traceResolution', '-p', dir],
{
encoding: 'utf8',
timeout: 180000,
maxBuffer: 16 * 1024 * 1024,
},
)
assert.ifError(result.error)
assert.equal(result.status, 0, (result.stdout + result.stderr).slice(-12000))
assert.match(
result.stdout,
mapper
? /contracts\/console\/datasets\.openapi-types/
: /generated\/api\/console\/datasets\/types\.gen\.ts/,
)
}
const runtime = spawnSync(
process.execPath,
[
'--input-type=module',
'-e',
`
import assert from 'node:assert/strict';
import {AccessMode} from '@dify/contracts/enterprise/types.gen';
assert.equal(AccessMode.ACCESS_MODE_PRIVATE, 'ACCESS_MODE_PRIVATE');
assert(import.meta.resolve('@dify/contracts/enterprise/types.gen').endsWith('/generated/enterprise/types.gen.ts'));
await assert.rejects(import('@dify/openapi-content-mapper/console/datasets'), {code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'});
`,
],
{ cwd: root, encoding: 'utf8' },
)
assert.equal(runtime.status, 0, runtime.stdout + runtime.stderr)
})
@@ -0,0 +1,125 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Verify standalone Console imports with the built mapper and bundler. */
import assert from 'node:assert/strict'
import { Buffer } from 'node:buffer'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { gzipSync } from 'node:zlib'
import { build } from 'vite'
import { loadConsoleDocument } from '../../contracts/scripts/compose-console-openapi.mjs'
import { openapi } from '../dist/tooling/vite.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const repository = resolve(import.meta.dirname, '../../..')
test('a standalone metadata consumer prunes every unused console operation', async (t) => {
const directory = await mkdtemp(join(import.meta.dirname, '.console-bundle-'))
try {
const spec = loadConsoleDocument()
const path = '/knowledge-fs/spaces/{control_space_id}/metadata'
const fullSpec = join(directory, 'console.openapi')
const entry = join(directory, 'consumer.ts')
await writeFile(fullSpec, JSON.stringify(spec))
await writeFile(
entry,
`import { api, query } from './console.openapi';
export const loadMetadata = (input) => api.knowledgeFs.spaces.byControlSpaceId.metadata.get(input);
export const metadataOptions = (input) => query.knowledgeFs.spaces.byControlSpaceId.metadata.get.queryOptions({ input });
`,
)
const reduced = join(directory, 'reduced.openapi')
await writeFile(
reduced,
JSON.stringify({
...spec,
paths: {
[path]: { ...spec.paths[path], post: undefined, patch: undefined, delete: undefined },
},
}),
)
for (const document of [fullSpec, reduced]) {
await writeFile(
`${document}.errors.ts`,
`export * from ${JSON.stringify(join(repository, 'packages/contracts/generated/api/console/errors.gen.ts'))};`,
)
await writeFile(
`${document}.queries.ts`,
`const defaults = { queryOptions: { retry: false, staleTime: 30000 } };
export { defaults as 'GET ${path}' };`,
)
}
async function bundle(useReduced) {
const result = await build({
configFile: false,
root: directory,
logLevel: 'silent',
plugins: [
...(useReduced
? [
{
name: 'one-operation-control',
enforce: 'pre',
resolveId(source) {
if (source === './console.openapi') return reduced
},
},
]
: []),
openapi(),
],
build: {
write: false,
minify: true,
lib: { entry, formats: ['es'] },
rollupOptions: {
output: { chunkFileNames: 'error-[hash].js' },
},
},
})
if (!useReduced) {
const chunks = (Array.isArray(result) ? result : [result])
.flatMap((item) => item.output)
.filter((file) => file.type === 'chunk')
const initial = chunks
.filter((file) => file.isEntry)
.map((file) => file.code)
.join('\n')
const deferred = chunks
.filter((file) => !file.isEntry)
.map((file) => file.code)
.join('\n')
assert(
!initial.includes('knowledge_fs_access_denied'),
'Validators must load only when a request fails',
)
t.diagnostic(
`Metadata entry: ${gzipSync(initial).length} gzip; deferred error validation: ${gzipSync(deferred).length} gzip.`,
)
}
return (Array.isArray(result) ? result : [result])
.flatMap((item) => item.output)
.filter((item) => item.type === 'chunk')
.map((item) => item.code)
.join('\n')
}
const full = await bundle(false)
const single = await bundle(true)
assert.equal(full.replace(/^\/\/.*$/gm, ''), single.replace(/^\/\/.*$/gm, ''))
assert(full.includes('/knowledge-fs/spaces/'))
for (const unused of [
'/files/upload',
'/datasets',
'/chat-messages',
'parseDocument',
'draft_workflow_not_sync',
'environment_deployments',
'zKnowledgeFsSpaceResponse',
])
assert(!full.includes(unused), `Unused code retained: ${unused}`)
t.diagnostic(
`Standalone metadata consumer: ${Buffer.byteLength(full)} bytes JS, ${gzipSync(full).length} gzip, including the SDK transport.`,
)
} finally {
await rm(directory, { recursive: true, force: true })
}
})
@@ -0,0 +1,193 @@
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from 'node:fs/promises'
import { join, relative, resolve } from 'node:path'
import { test } from 'node:test'
import { loadConsoleDocument } from '../../contracts/scripts/compose-console-openapi.mjs'
const repository = resolve(import.meta.dirname, '../../..')
const web = join(repository, 'web')
const next = join(web, 'node_modules/next/dist/bin/next')
async function javascript(directory) {
const entries = await readdir(directory, { withFileTypes: true })
return (
await Promise.all(
entries.map(async (entry) => {
const file = join(directory, entry.name)
if (entry.isDirectory()) return javascript(file)
return entry.name.endsWith('.js') ? readFile(file, 'utf8') : ''
}),
)
).join('\n')
}
for (const bundler of ['turbopack', 'webpack']) {
test(`Next ${bundler}: Console and Marketplace imports keep separate transports and prune unused operations`, async () => {
const consoleSpec = loadConsoleDocument()
const alias = 'enterprise.access.getMetadata'
consoleSpec.paths['/knowledge-fs/spaces/{control_space_id}/metadata'].get['x-client-path'] =
alias.split('.')
const dir = await mkdtemp(join(web, '.openapi-next-'))
// Match production: contracts owns the document but only Web depends on the SDK.
const specDir = await mkdtemp(join(repository, 'packages/contracts/.openapi-next-'))
try {
await mkdir(join(dir, 'app'))
await writeFile(join(dir, 'package.json'), JSON.stringify({ private: true, type: 'module' }))
await writeFile(
join(dir, 'next.config.mjs'),
`
const loader = { loader: '@dify/openapi-content-mapper/loader', options: { runtime: ${JSON.stringify(relative(specDir, join(dir, 'runtime.js')))}, sidecars: ${JSON.stringify(relative(specDir, join(dir, 'spec.openapi')))} } };
const marketplaceLoader = { loader: '@dify/openapi-content-mapper/loader', options: { runtime: ${JSON.stringify(relative(specDir, join(dir, 'marketplace-runtime.js')))}, sidecars: ${JSON.stringify(relative(specDir, join(dir, 'marketplace.openapi')))} } };
const namespaceLoader = { loader: '@dify/openapi-content-mapper/loader' };
export default {
experimental: { cpus: 1, extensionAlias: { '.js': ['.ts', '.js'] } },
turbopack: { root: ${JSON.stringify(repository)}, rules: { '*console-spec.openapi-source': { loaders: [loader], as: '*.js' }, '*marketplace-spec.json': { loaders: [marketplaceLoader], as: '*.js' }, '*openapi-namespace.js': { loaders: [namespaceLoader], as: '*.js' } } },
webpack(config) { config.module.rules.push({ test: /console-spec\\.openapi-source$/, type: 'javascript/auto', use: [loader] }, { test: /marketplace-spec\\.json$/, type: 'javascript/auto', use: [marketplaceLoader] }, { test: /openapi-namespace\\.js$/, type: 'javascript/auto', use: [namespaceLoader] }); return config; },
};
`,
)
await writeFile(
join(specDir, 'console-export.mjs'),
`process.stdout.write(${JSON.stringify(
JSON.stringify({
...consoleSpec,
info: { title: 'SCHEMA_METADATA_MUST_DISAPPEAR', version: '1' },
paths: {
...consoleSpec.paths,
'/UNUSED_ENDPOINT_MUST_DISAPPEAR': {
get: { responses: { 200: { description: 'OK' } } },
},
},
}),
)});`,
)
await writeFile(
join(specDir, 'console-spec.openapi-source'),
JSON.stringify({ command: ['node', 'console-export.mjs'], inputs: ['console-export.mjs'] }),
)
await symlink(join(specDir, 'console-spec.openapi-source'), join(dir, 'spec.openapi'))
await writeFile(
join(specDir, 'marketplace-spec.json'),
JSON.stringify({
openapi: '3.1.0',
info: { title: 'Independent document', version: '1' },
paths: {
'/templates/{templateId}': {
get: {
'x-client-path': ['templateDetail'],
parameters: [
{ name: 'templateId', in: 'path', required: true, schema: { type: 'string' } },
],
responses: { 200: { description: 'OK' } },
},
},
'/template-collections': { get: { responses: { 200: { description: 'Unused' } } } },
},
}),
)
await symlink(join(specDir, 'marketplace-spec.json'), join(dir, 'marketplace.openapi'))
await writeFile(
join(dir, 'marketplace.openapi.queries.ts'),
"const policy = { queryOptions: { staleTime: 3131 } }; export { policy as 'GET /templates/{templateId}' };",
)
await writeFile(
join(dir, 'marketplace-runtime.js'),
`
import { createClient } from '@dify/openapi-content-mapper';
export default { queryKeyPrefix: ['marketplace'], createClient: () => createClient({ baseUrl: 'https://marketplace.test', fetch: async url => Response.json({ value: String(url) }) }) };
`,
)
const policy = `const selected = { queryOptions: { staleTime: 4242 } }; const unused = { queryOptions: { meta: { marker: 'UNUSED_POLICY_MUST_DISAPPEAR' } } }; export { selected as 'GET /knowledge-fs/spaces/{control_space_id}/metadata', unused as 'GET /UNUSED_ENDPOINT_MUST_DISAPPEAR' };`
const errors = `const selected = { CONFLICT: { status: 409 } }; const unused = { UNUSED: { status: 400, message: 'UNUSED_ERROR_MUST_DISAPPEAR' } }; export { selected as 'GET /knowledge-fs/spaces/{control_space_id}/metadata', unused as 'GET /UNUSED_ENDPOINT_MUST_DISAPPEAR' };`
await writeFile(
join(dir, 'spec.openapi.queries.ts'),
`export * from ${JSON.stringify(bundler === 'webpack' ? './policies.js' : './policies.ts')};`,
)
await writeFile(join(dir, 'policies.ts'), policy)
await writeFile(
join(dir, 'spec.openapi.errors.ts'),
`export * from ${JSON.stringify(bundler === 'webpack' ? './errors.js' : './errors.ts')};`,
)
await writeFile(join(dir, 'errors.ts'), errors)
await writeFile(
join(dir, 'runtime.js'),
`
import { createClient } from '@dify/openapi-content-mapper';
export default {
queryKeyPrefix: ['bound'],
createClient: ({ context }) => createClient({ baseUrl: 'https://bound.test', fetch: async url => context.user === 'conflict' ? Response.json({ code: 'CONFLICT' }, { status: 409 }) : Response.json({ value: String(url) + ':' + context.user }) }),
};
`,
)
await writeFile(
join(dir, 'app/layout.jsx'),
'export default function Layout({ children }) { return <html><body>{children}</body></html> }',
)
await writeFile(
join(dir, 'app/button.jsx'),
`
'use client';
import { api, query } from '../spec.openapi';
import { api as marketplace, query as marketplaceQuery } from '../marketplace.openapi';
export default function Button() {
return <><button onClick={() => marketplace.templateDetail({ params: { templateId: 'template-1' } })}>{JSON.stringify(marketplaceQuery.templateDetail.key())}</button><button onClick={() => api.${alias}({ params: { control_space_id: 'space-1' } }, { context: { user: 'client' } })}>{JSON.stringify(query.${alias}.key())}</button></>;
}
`,
)
await writeFile(
join(dir, 'app/page.jsx'),
`
import { api, query } from '../spec.openapi';
import { api as marketplace, query as marketplaceQuery } from '../marketplace.openapi';
import Button from './button';
export default async function Page() {
const market = await marketplace.templateDetail({ params: { templateId: 'template-1' } });
const marketOptions = marketplaceQuery.templateDetail.queryOptions({ input: { params: { templateId: 'template-1' } } });
const response = await api.${alias}({ params: { control_space_id: 'space-1' } }, { context: { user: 'server' } });
const defined = await api.${alias}({ params: { control_space_id: 'space-1' } }, { context: { user: 'conflict' } }).catch(error => error.defined);
const options = query.${alias}.queryOptions({ input: { params: { control_space_id: 'space-1' } } });
return <><p>{market.value};market-stale:{marketOptions.staleTime}</p><p>{response.value}</p><p>defined-error:{String(defined)};stale:{options.staleTime}</p><Button /></>;
}
`,
)
const result = spawnSync(process.execPath, [next, 'build', `--${bundler}`], {
cwd: dir,
env: {
...process.env,
NEXT_TELEMETRY_DISABLED: '1',
NODE_OPTIONS: '--max-old-space-size=1024',
RAYON_NUM_THREADS: '1',
},
encoding: 'utf8',
timeout: 120_000,
killSignal: 'SIGKILL',
maxBuffer: 4 * 1024 * 1024,
})
assert.equal(result.status, 0, `${result.error ?? ''}\n${result.stdout}\n${result.stderr}`)
const html = await readFile(join(dir, '.next/server/app/index.html'), 'utf8')
assert(html.includes('https://bound.test/knowledge-fs/spaces/space-1/metadata:server'))
assert(html.includes('bound'))
assert(html.replaceAll(/<!--.*?-->/g, '').includes('defined-error:true;stale:4242'))
assert(html.includes('4242'))
assert(
html
.replaceAll(/<!--.*?-->/g, '')
.includes('https://marketplace.test/templates/template-1;market-stale:3131'),
)
assert(html.includes('marketplace'))
const client = await javascript(join(dir, '.next/static/chunks'))
assert(client.includes('/knowledge-fs/spaces/'))
assert(!client.includes('/datasets'))
assert(!client.includes('/template-collections'))
assert(!client.includes('UNUSED_ENDPOINT_MUST_DISAPPEAR'))
assert(!client.includes('SCHEMA_METADATA_MUST_DISAPPEAR'))
assert(!client.includes('UNUSED_POLICY_MUST_DISAPPEAR'))
assert(!client.includes('UNUSED_ERROR_MUST_DISAPPEAR'))
} finally {
await rm(dir, { recursive: true, force: true })
await rm(specDir, { recursive: true, force: true })
}
})
}
@@ -0,0 +1,46 @@
/* oxlint-disable vitest/no-import-node-test -- Compare every generated error map with the current Console contracts. */
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { consoleRouterContract } from '../../contracts/console.ts'
import * as maps from '../../contracts/generated/api/console/errors.gen.ts'
/* oxlint-enable vitest/no-import-node-test */
test('standalone error maps preserve every Console status, code and validated payload', async (t) => {
let operations = 0
let cases = 0
async function walk(node) {
const definition = node?.['~orpc']
if (!definition) {
for (const child of Object.values(node)) await walk(child)
return
}
if (!Object.keys(definition.errorMap).length) return
const key = `${definition.route.method} ${definition.route.path}`
const actual = maps[key]
assert(actual, `Missing ${key}`)
assert.deepEqual(Object.keys(actual), Object.keys(definition.errorMap))
operations++
for (const [code, expected] of Object.entries(definition.errorMap)) {
assert.equal(actual[code].status, expected.status)
assert.equal(actual[code].message, expected.message)
assert.equal(!!actual[code].data, !!expected.data)
if (!expected.data) continue
for (const value of [
{ code, message: 'message', status: expected.status, extra: 'must be stripped' },
{ code, message: 'message', status: expected.status, details: { value: [1, null] } },
{ code: 'unknown', message: 1, status: 'invalid' },
]) {
assert.deepEqual(
await actual[code].data['~standard'].validate(value),
await expected.data['~standard'].validate(value),
key,
)
cases++
}
}
}
await walk(consoleRouterContract)
assert.equal(operations, Object.keys(maps).length)
assert(operations > 0)
t.diagnostic(`${operations} operation maps, ${cases} payload comparisons`)
})
@@ -0,0 +1,125 @@
/* oxlint-disable vitest/no-import-node-test -- Compare native mapper types with the repository's generated contracts. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
/* oxlint-enable vitest/no-import-node-test */
const root = resolve(import.meta.dirname, '..')
const contracts = resolve(root, '../contracts')
const specDir = process.env.DIFY_OPENAPI_DIR ?? join(contracts, 'openapi')
test('five generated oRPC contracts match, except intentional stream and multipart differences', () => {
const dir = mkdtempSync(join(root, 'integration/.orpc-'))
try {
for (const name of ['console', 'service', 'openapi'])
symlinkSync(join(specDir, `${name}-openapi.json`), join(dir, `${name}.openapi`))
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
allowImportingTsExtensions: true,
types: ['node'],
lib: ['ES2022', 'DOM'],
},
contentMappers: [{ package: root, extensions: ['.openapi'] }],
include: ['*.ts'],
}),
)
const checks = [
['listDatasets', 'consoleApi.datasets.get', 'datasets.get', [true, true], [true, true]],
['createDataset', 'consoleApi.datasets.post', 'datasets.post', [true, true], [true, true]],
[
'uploadFile',
'consoleApi.files.upload.post',
'files.upload.post',
[true, true],
[true, true],
],
[
'chatMessage',
'serviceApi.chatMessages.post',
'chatMessages.post',
[true, true],
[false, false],
],
[
'chatRun',
'openapiApi.apps.byAppId.chat.run.post',
'run2.post',
[false, false],
[true, true],
],
]
const source = `
import { api as consoleApi } from './console.openapi';
import { api as serviceApi } from './service.openapi';
import { api as openapiApi } from './openapi.openapi';
import type { datasets } from '../../../contracts/generated/api/console/datasets/orpc.gen.ts';
import type { files } from '../../../contracts/generated/api/console/files/orpc.gen.ts';
import type { chatMessages } from '../../../contracts/generated/api/service/orpc.gen.ts';
import type { run2 } from '../../../contracts/generated/api/openapi/orpc.gen.ts';
// Read the actual procedure's Standard Schema input/output types, including Zod defaults.
// This uses the generated contract schemas, not the parallel types.gen.ts declarations.
type Schema = { '~standard': { types?: { input: unknown; output: unknown } } };
type Contract = { '~orpc': { inputSchema?: Schema; outputSchema?: Schema } };
type Input<T extends Contract> = NonNullable<NonNullable<T['~orpc']['inputSchema']>['~standard']['types']>['input'];
type Output<T extends Contract> = NonNullable<NonNullable<T['~orpc']['outputSchema']>['~standard']['types']>['output'];
type Ext<A, B> = [A] extends [B] ? true : false;
type Any<T> = 0 extends (1 & T) ? true : false;
type Unknown<T> = unknown extends T ? true : false;
${checks
.map(
([name, api, contract, input, output]) => `
type ${name}NewIn = Parameters<typeof ${api}>[0];
type ${name}OldIn = Input<typeof ${contract}>;
type ${name}NewOut = Awaited<ReturnType<typeof ${api}>>;
type ${name}OldOut = Output<typeof ${contract}>;
export const ${name}Input: [Ext<${name}NewIn, ${name}OldIn>, Ext<${name}OldIn, ${name}NewIn>] = ${JSON.stringify(input)};
export const ${name}Output: [Ext<${name}NewOut, ${name}OldOut>, Ext<${name}OldOut, ${name}NewOut>] = ${JSON.stringify(output)};
export const ${name}NotAny: [Any<${name}NewIn>, Any<${name}OldIn>, Any<${name}NewOut>, Any<${name}OldOut>] = [false, false, false, false];
export const ${name}NotUnknown: [Unknown<${name}NewIn>, Unknown<${name}OldIn>, Unknown<${name}NewOut>, Unknown<${name}OldOut>] = [false, false, false, false];
`,
)
.join('\n')}
type NewBlocking = Exclude<chatMessageNewOut, ReadableStream<Uint8Array>>;
type OldBlocking = Exclude<chatMessageOldOut, string>;
export const blockingOutput: [Ext<NewBlocking, OldBlocking>, Ext<OldBlocking, NewBlocking>] = [true, true];
// Keep the refreshed discovery field checked explicitly, so stale exports fail this test.
type NewUpgrade = listDatasetsNewOut['data'][number]['knowledge_fs_upgrade'];
type OldUpgrade = listDatasetsOldOut['data'][number]['knowledge_fs_upgrade'];
export const upgrade: [Ext<NewUpgrade, OldUpgrade>, Ext<OldUpgrade, NewUpgrade>] = [true, true];
`
writeFileSync(join(dir, 'check.ts'), source)
const result = spawnSync(
process.execPath,
[
join(root, 'node_modules/typescript/bin/tsc'),
'--runExternalCode',
'--pretty',
'false',
'-p',
dir,
],
{ cwd: root, encoding: 'utf8', timeout: 60000 },
)
assert.ifError(result.error)
assert.equal(
result.status,
0,
result.stdout +
result.stderr +
[...result.stdout.matchAll(/check\.ts\((\d+),/g)]
.map((match) => `\n${source.split('\n')[Number(match[1]) - 1]}`)
.join(''),
)
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
@@ -0,0 +1,300 @@
import assert from 'node:assert/strict'
import { spawn } from 'node:child_process'
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
const root = resolve(import.meta.dirname, '..')
function run(command, args, cwd) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
cwd,
env: {
...process.env,
GOMAXPROCS: '1',
GOMEMLIMIT: '512MiB',
RAYON_NUM_THREADS: '1',
NODE_OPTIONS: '--max-old-space-size=1024',
pnpm_config_verify_deps_before_run: 'false',
},
stdio: ['ignore', 'pipe', 'pipe'],
timeout: 180_000,
killSignal: 'SIGKILL',
})
let output = ''
child.stdout.on('data', (chunk) => {
output = (output + chunk).slice(-32_768)
})
child.stderr.on('data', (chunk) => {
output = (output + chunk).slice(-32_768)
})
child.on('error', reject)
child.on('close', (code) =>
code === 0 ? resolve(output) : reject(new Error(`${command} exited ${code}:\n${output}`)),
)
})
}
async function files(directory, prefix = '') {
const found = []
for (const entry of await readdir(directory, { withFileTypes: true })) {
const name = `${prefix}${entry.name}`
if (entry.isDirectory()) found.push(...(await files(join(directory, entry.name), `${name}/`)))
else found.push(name)
}
return found
}
test('packed SDK installs and works outside the workspace with npm and official Vite', async () => {
const manifest = JSON.parse(await readFile(join(root, 'package.json'), 'utf8'))
const directory = await mkdtemp(join(tmpdir(), 'openapi-package-'))
try {
const tarball = process.env.OPENAPI_PACKAGE_TARBALL
? resolve(process.env.OPENAPI_PACKAGE_TARBALL)
: join(directory, 'sdk.tgz')
await run('pnpm', ['pack', '--out', tarball], root)
await writeFile(
join(directory, 'package.json'),
JSON.stringify({ private: true, type: 'module' }),
)
await run(
'npm',
[
'install',
'--ignore-scripts',
'--no-audit',
'--no-fund',
'--package-lock=false',
tarball,
'typescript@7.1.0-beta',
'vite@8.3.5',
],
directory,
)
const installed = join(directory, 'node_modules', manifest.name)
const packed = JSON.parse(await readFile(join(installed, 'package.json'), 'utf8'))
assert(!packed.exports['./console/*'], 'Dify-only subpaths must stay out of the standalone SDK')
assert(
!packed.exports['./enterprise'],
'Dify-only subpaths must stay out of the standalone SDK',
)
assert.equal(packed.name, manifest.name)
assert.equal(packed.version, manifest.version)
assert(!packed.private)
assert(!packed.dependencies.vite)
assert.equal(packed.peerDependenciesMeta.vite.optional, true)
for (const lifecycle of ['preinstall', 'install', 'postinstall', 'prepare'])
assert(
!packed.scripts?.[lifecycle],
`Consumer lifecycle must not build the package: ${lifecycle}`,
)
assert.equal(packed.license, 'SEE LICENSE IN LICENSE')
assert.equal(
await readFile(join(root, 'LICENSE'), 'utf8'),
await readFile(join(root, '../../LICENSE'), 'utf8'),
)
assert.equal(
await readFile(join(installed, 'LICENSE'), 'utf8'),
await readFile(join(root, 'LICENSE'), 'utf8'),
)
for (const section of ['dependencies', 'optionalDependencies', 'peerDependencies'])
for (const version of Object.values(packed[section] ?? {}))
assert(
!/^(?:catalog|workspace|link|file):/.test(version),
`Unresolved package dependency: ${version}`,
)
const packedFiles = await files(installed)
assert(packedFiles.includes('README.md'))
assert(packedFiles.includes('CHANGELOG.md'))
for (const file of packedFiles)
assert(
/^(?:dist\/.*\.(?:js|d\.ts)|package\.json|README\.md|LICENSE|CHANGELOG\.md)$/.test(file),
`Unexpected packaged file: ${file}`,
)
for (const target of Object.values(packed.exports)) {
if (typeof target === 'string') continue
assert(packedFiles.includes(target.types.slice(2)), `Missing declarations: ${target.types}`)
assert(packedFiles.includes(target.default.slice(2)), `Missing runtime: ${target.default}`)
}
assert(packedFiles.includes(packed.typescript.contentMapper.exec[1]))
await writeFile(
join(directory, 'export.mjs'),
`console.log(JSON.stringify({
openapi: '3.1.0', paths: { '/status': { get: { responses: { 200: { content: {
'application/json': { schema: { type: 'object', required: ['name'], properties: { name: { type: 'string' } } } }
} } } } } }
}));`,
)
await writeFile(
join(directory, 'backend.openapi-source'),
JSON.stringify({
command: ['node', 'export.mjs'],
inputs: ['export.mjs'],
}),
)
await writeFile(
join(directory, 'backend.openapi-source.config.ts'),
`
export { default } from './pets.yaml.config.ts';
export type { Context } from './pets.yaml.config.ts';
`,
)
await writeFile(
join(directory, 'pets.yaml'),
`
openapi: 3.1.0
paths:
/pets/{petId}:
get:
parameters:
- name: petId
in: path
required: true
schema:
type: integer
responses:
'200':
content:
application/json:
schema:
type: object
required: [name]
properties:
name:
type: string
/UNUSED_ENDPOINT:
get:
responses:
'204':
description: unused
`,
)
await writeFile(
join(directory, 'pets.yaml.config.ts'),
`
import type { RuntimeConfig } from '@dify/openapi-content-mapper';
import { createClient } from '@dify/openapi-content-mapper';
export type Context = { name?: string };
const runtime: RuntimeConfig<Context> = {
queryKeyPrefix: ['pets'],
createClient: ({context}) => createClient({
baseUrl: 'https://example.test',
fetch: async () => context?.name === 'conflict'
? Response.json({code: 'CONFLICT'}, {status: 409})
: Response.json({name: context?.name ?? 'Mochi'}),
}),
};
export default runtime;
`,
)
await writeFile(
join(directory, 'pets.yaml.queries.ts'),
`const defaults = {queryOptions: {staleTime: 1234}}; export {defaults as 'GET /pets/{petId}'};`,
)
await writeFile(
join(directory, 'pets.yaml.errors.ts'),
`const errors = {CONFLICT: {status: 409}}; export {errors as 'GET /pets/{petId}'};`,
)
await writeFile(
join(directory, 'index.ts'),
`
import { api, query } from './pets.yaml';
import { api as backend } from './backend.openapi-source';
import { safe } from '@orpc/client';
const backendName: string = (await backend.status.get()).name;
// @ts-expect-error command-source types survive packaging
const wrongBackendName: number = (await backend.status.get()).name;
const result = await safe(api.pets.byPetId.get({params: {petId: 1}}));
if (result.isDefined) { const code: 'CONFLICT' = result.error.code; }
const pet = await api.pets.byPetId.get({params: {petId: 1}}, {context: {name: 'Mochi'}});
const name: string = pet.name;
query.pets.byPetId.get.queryOptions({input: {params: {petId: 1}}, context: {name: 'Mochi'}});
// @ts-expect-error inferred request types survive packaging
api.pets.byPetId.get({params: {petId: 'wrong'}});
// @ts-expect-error sidecar context survives packaging
api.pets.byPetId.get({params: {petId: 1}}, {context: {name: 123}});
`,
)
for (const module of ['NodeNext', 'ESNext']) {
await writeFile(
join(directory, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
skipLibCheck: true,
target: 'ES2022',
module,
moduleResolution: module === 'NodeNext' ? 'NodeNext' : 'Bundler',
types: [],
allowImportingTsExtensions: true,
},
contentMappers: [
{
package: manifest.name,
extensions: ['.yaml', '.openapi', '.openapi-source'],
options: { sources: ['./backend.openapi-source'] },
},
],
include: ['*.ts'],
}),
)
await run(
process.execPath,
['node_modules/typescript/bin/tsc', '--runExternalCode', '--noEmit'],
directory,
)
}
await writeFile(
join(directory, 'runtime.mjs'),
`
import assert from 'node:assert/strict';
import * as document from './pets.yaml';
import { api as backend } from './backend.openapi-source';
import { safe } from '@orpc/client';
assert.deepEqual(await backend.status.get(undefined, {context: {name: 'backend'}}), {name: 'backend'});
assert.deepEqual(Object.keys(document), ['api', 'query']);
assert.deepEqual(await document.api.pets.byPetId.get({params: {petId: 1}}, {context: {name: 'packed'}}), {name: 'packed'});
assert.deepEqual(document.query.key(), [['pets'], {}]);
assert.equal(document.query.pets.byPetId.get.queryOptions({input: {params: {petId: 1}}}).staleTime, 1234);
const failure = await safe(document.api.pets.byPetId.get({params: {petId: 1}}, {context: {name: 'conflict'}}));
assert.equal(failure.isDefined, true);
assert.equal(failure.error.code, 'CONFLICT');
assert.equal(typeof (await import('@dify/openapi-content-mapper/loader')).default, 'function');
`,
)
await run(process.execPath, ['--import', `${manifest.name}/register`, 'runtime.mjs'], directory)
await writeFile(
join(directory, 'entry.mjs'),
`
import { api } from './pets.yaml';
import { api as backend } from './backend.openapi-source';
export const getPet = (input) => api.pets.byPetId.get(input);
export const getStatus = () => backend.status.get();
`,
)
await writeFile(
join(directory, 'bundle.mjs'),
`
import assert from 'node:assert/strict';
import { build } from 'vite';
import { openapi } from '@dify/openapi-content-mapper/vite';
const result = await build({
configFile: false, logLevel: 'silent', plugins: [openapi()],
build: { write: false, lib: {entry: './entry.mjs', formats: ['es']} },
});
const code = result[0].output.filter(file => file.type === 'chunk').map(file => file.code).join('\\n');
assert(code.includes('/pets/{petId}'));
assert(code.includes('/status'));
assert(!code.includes('export.mjs'));
assert(!code.includes('UNUSED_ENDPOINT'));
assert(!code.includes('parseDocument'));
`,
)
await run(process.execPath, ['bundle.mjs'], directory)
} finally {
await rm(directory, { recursive: true, force: true })
}
})
@@ -0,0 +1,395 @@
/* oxlint-disable vitest/no-import-node-test, antfu/no-import-dist -- Native compiler and built SDK integration against unchanged repository documents. */
import assert from 'node:assert/strict'
import { Buffer } from 'node:buffer'
import { spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { once } from 'node:events'
import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { createServer } from 'node:http'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { pathToFileURL } from 'node:url'
import { gzipSync } from 'node:zlib'
import { build } from 'vite'
import { createClient } from '../dist/index.js'
import { describeOperations } from '../dist/operation.js'
import { createRouter } from '../dist/tooling/router.js'
import { transformSpec } from '../dist/tooling/transform.js'
import { openapi } from '../dist/tooling/vite.js'
import { rpcProcess } from '../test/rpc.mjs'
import '../dist/tooling/register.js'
/* oxlint-enable vitest/no-import-node-test, antfu/no-import-dist */
const root = resolve(import.meta.dirname, '..')
const specDir = process.env.DIFY_OPENAPI_DIR ?? resolve(root, '../contracts/openapi')
const names = [
'console',
'fastopenapi-console',
'inner',
'openapi',
'service',
'web',
'knowledge-fs',
]
const files = names.map((name) =>
name === 'knowledge-fs'
? resolve(root, '../../api/knowledge-fs-contract/knowledge-fs.openapi.json')
: join(specDir, `${name}-openapi.json`),
)
const compiler = join(root, 'node_modules/typescript/bin/tsc')
function routes(node, path = []) {
return [...node.methods]
.map(([method, operation]) => ({ members: [...path, method], operation }))
.concat([...node.children].flatMap(([key, child]) => routes(child, [...path, key])))
}
test('unchanged Dify and KnowledgeFS OpenAPI documents', { timeout: 120000 }, async (t) => {
for (const file of files)
assert(
existsSync(file),
`Missing ${file}. Supply DIFY_OPENAPI_DIR with existing generated OpenAPI files; this test never regenerates or edits them.`,
)
const dir = mkdtempSync(join(root, 'integration/.repository-'))
const specs = files.map((file) => JSON.parse(readFileSync(file, 'utf8')))
const contents = files.map((file) => readFileSync(file, 'utf8'))
const entries = names.map((name) => join(dir, `${name}.openapi`))
const hash = (text) => createHash('sha256').update(text).digest('hex')
try {
for (const [index, file] of files.entries()) symlinkSync(file, entries[index])
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
strict: true,
noEmit: true,
skipLibCheck: true,
target: 'ES2022',
module: 'NodeNext',
types: ['node'],
lib: ['ES2022', 'DOM'],
},
contentMappers: [{ package: root, extensions: ['.openapi'] }],
include: ['*.ts'],
}),
)
await t.test('all operations survive mapping; source hashes and counts are recorded', () => {
specs.forEach((spec, index) => {
const transformed = transformSpec(contents[index], entries[index])
assert.equal(transformed.diagnostics, undefined, JSON.stringify(transformed.diagnostics))
const operations = describeOperations(spec)
const declared = Object.values(spec.paths).reduce(
(count, item) =>
count +
Object.keys(item).filter((method) =>
['get', 'post', 'put', 'patch', 'delete', 'head', 'options', 'trace'].includes(
method,
),
).length,
0,
)
assert.equal(
operations.size,
declared,
'No unsupported operation may be silently filtered out',
)
assert.equal(routes(createRouter(operations)).length, operations.size)
t.diagnostic(
`${names[index]}: ${Object.keys(spec.paths).length} paths, ${operations.size} operations, ${Buffer.byteLength(contents[index])} bytes, sha256 ${hash(contents[index])}`,
)
})
})
await t.test('native TS 7.1 checks every route plus real request/response assertions', () => {
const allRoutes = specs
.flatMap((spec, index) => [
`import { api as api${index} } from './${names[index]}.openapi';`,
...routes(createRouter(describeOperations(spec))).map(({ members }, routeIndex) => {
const expression = `api${index}${members.map((key) => `[${JSON.stringify(key)}]`).join('')}`
return `export type Input${index}_${routeIndex} = Parameters<typeof ${expression}>; export type Output${index}_${routeIndex} = Awaited<ReturnType<typeof ${expression}>>;`
}),
])
.join('\n')
writeFileSync(join(dir, 'all-routes.ts'), allRoutes)
writeFileSync(
join(dir, 'assertions.ts'),
`
import { api as consoleApi, query as consoleQuery } from './console.openapi';
import { api as service } from './service.openapi';
import { api as web } from './web.openapi';
import { api as inner } from './inner.openapi';
import { api as openapi } from './openapi.openapi';
import { api as fast } from './fastopenapi-console.openapi';
import { api as knowledge } from './knowledge-fs.openapi';
type IsAny<T> = 0 extends (1 & T) ? true : false;
const datasets = await consoleApi.datasets.get({query: {page: 1, ids: ['id']}});
const total: number = datasets.total;
const redirect: Awaited<ReturnType<typeof consoleApi.mcp.oauth.callback.get>> = undefined;
const notAny: IsAny<typeof datasets> = false;
// @ts-expect-error actual pagination type is numeric
const wrongTotal: string = datasets.total;
// @ts-expect-error actual query limit is numeric
consoleApi.datasets.get({query: {limit: '10'}});
consoleApi.datasets.post({body: {name: 'Example'}});
// @ts-expect-error required dataset name comes from a local schema reference
consoleApi.datasets.post({body: {}});
const upload = await consoleApi.files.upload.post({body: {file: new File(['file'], 'file.txt'), source: 'datasets'}});
const fileId: string = upload.id;
// @ts-expect-error binary file accepts Blob/File, not a string
consoleApi.files.upload.post({body: {file: 'file.txt'}});
// @ts-expect-error file is required
consoleApi.files.upload.post({body: {source: 'datasets'}});
const options = consoleQuery.datasets.get.queryOptions({input: {query: {page: 1}}});
type QueryResult = Awaited<ReturnType<typeof options.queryFn>>;
const queryTotal: number = (null! as QueryResult).total;
await service.datasets.byDatasetId.document.createByFile.post({params: {dataset_id: 'id'}, body: {file: new Blob(['file'])}});
await service.datasets.byDatasetId.document.create_by_file.post({params: {dataset_id: 'id'}, body: {file: new Blob(['file'])}});
await openapi.apps.byAppId.chat.run.post({params: {app_id: 'id'}, contentType: 'multipart/form-data', body: {query: 'hello', inputs: {enabled: true}}});
await openapi.apps.byAppId.chat.run.post({params: {app_id: 'id'}, body: {query: 'hello', attachments: ['path.txt']}});
await openapi.apps.byAppId.chat.run.post({params: {app_id: 'id'}, contentType: 'multipart/form-data', body: {query: 'hello', attachments: [new File(['file'], 'file.txt')]}});
// @ts-expect-error binary values need explicit multipart selection when JSON is also available
openapi.apps.byAppId.chat.run.post({params: {app_id: 'id'}, body: {query: 'hello', attachments: [new Blob(['file'])]}});
const parameters = await web.parameters.get();
const question: string | undefined = parameters.suggested_questions?.[0];
const opaque: unknown = await inner.agentConfig.byAgentId.env.patch({params: {agent_id: 'id'}});
// @ts-expect-error an undocumented 200 body must remain unknown, not invent a shape
opaque.success;
await fast.console.api.ping.get();
const health = await knowledge.health.get();
const runtime: 'cloudflare-workers' | 'node-docker' = health.runtime;
await knowledge.uploadSessions.byId.smallFile.post({params: {id: 'id'}, query: {knowledgeSpaceId: 'space'}, body: new Blob(['bytes'])});
// @ts-expect-error raw binary upload does not accept a JSON object
knowledge.uploadSessions.byId.smallFile.post({params: {id: 'id'}, query: {knowledgeSpaceId: 'space'}, body: {file: 'x'}});
const bulk = knowledge.knowledgeSpaces.byId.documents.bulk.post({params: {id: 'id'}, body: {files: [new File(['a'], 'a.txt')]}});
type Chat = Awaited<ReturnType<typeof service.chatMessages.post>>;
const stream: Extract<Chat, ReadableStream<Uint8Array>> = new ReadableStream<Uint8Array>();
`,
)
const started = performance.now()
const result = spawnSync(
process.execPath,
[compiler, '--runExternalCode', '--pretty', 'false', '-p', dir],
{ cwd: root, encoding: 'utf8', timeout: 90000 },
)
assert.ifError(result.error)
assert.equal(result.status, 0, result.stdout + result.stderr)
t.diagnostic(`Native compilation: ${Math.round(performance.now() - started)} ms`)
})
await t.test('native editor completions and hover work on the full console spec', async () => {
const rpc = rpcProcess(process.execPath, [compiler, '--lsp', '--stdio'], root)
try {
await rpc.request('initialize', {
processId: process.pid,
rootUri: pathToFileURL(dir).href,
capabilities: {},
initializationOptions: { runExternalCode: true },
})
rpc.notify('initialized', {})
const uri = pathToFileURL(join(dir, 'editor.ts')).href
const text =
"import { api } from './console.openapi';\nconst result = await api.datasets.get();\nresult.total;\napi.datasets."
rpc.notify('textDocument/didOpen', {
textDocument: { uri, languageId: 'typescript', version: 1, text },
})
const completions = await rpc.request('textDocument/completion', {
textDocument: { uri },
position: { line: 3, character: 13 },
})
const labels = (completions.items ?? completions).map((item) => item.label)
assert(labels.includes('get') && labels.includes('post'))
const hover = await rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line: 2, character: 9 },
})
assert.match(JSON.stringify(hover), /total.*number/)
} finally {
rpc.close()
}
})
await t.test(
'real HTTP serialization: query, multipart, binary, relative servers and streaming',
async () => {
const [
{ api: consoleApi },
,
,
{ api: publicApi },
{ api: serviceApi },
,
{ api: knowledge },
] = await Promise.all(entries.map((file) => import(pathToFileURL(file).href)))
const requests = []
const server = createServer(async (req, res) => {
try {
const chunks = []
for await (const chunk of req) chunks.push(chunk)
const body = Buffer.concat(chunks)
const request = new Request(`http://localhost${req.url}`, {
method: req.method,
headers: req.headers,
...(req.method !== 'GET' ? { body } : {}),
})
const contentType = req.headers['content-type'] ?? ''
const data = contentType.startsWith('multipart/')
? await request.formData()
: body.toString()
requests.push({ path: req.url, headers: req.headers, data })
if (req.url === '/v1/chat-messages') {
res.writeHead(200, { 'Content-Type': 'text/event-stream' })
res.write('data: {"event":"message","answer":"hello"}\n\n')
} else {
res.setHeader('Content-Type', 'application/json')
res.end(
JSON.stringify({ data: [], total: 0, id: 'uploaded', name: 'test.txt', size: 5 }),
)
}
} catch (error) {
res.writeHead(500).end(String(error))
}
})
server.listen(0, '127.0.0.1')
await once(server, 'listening')
const origin = `http://127.0.0.1:${server.address().port}`
const previousLocation = Object.getOwnPropertyDescriptor(globalThis, 'location')
try {
Object.defineProperty(globalThis, 'location', {
configurable: true,
value: new URL(origin),
})
const client = createClient({ headers: { 'Content-Type': 'application/json' } })
await consoleApi.datasets.get({ query: { ids: ['a', 'b'], page: 2 } }, { client })
assert.equal(requests.at(-1).path, '/console/api/datasets?ids=a&ids=b&page=2')
await consoleApi.files.upload.post(
{ body: { file: new File(['hello'], 'test.txt'), source: 'datasets' } },
{ client },
)
assert.match(requests.at(-1).headers['content-type'], /^multipart\/form-data; boundary=/)
assert.equal(requests.at(-1).data.get('file').name, 'test.txt')
assert.equal(await requests.at(-1).data.get('file').text(), 'hello')
assert.equal(requests.at(-1).data.get('source'), 'datasets')
const direct = createClient({ baseUrl: origin })
await knowledge.uploadSessions.byId.smallFile.post(
{
params: { id: 'a/b' },
query: { knowledgeSpaceId: 'space' },
body: new Blob(['binary']),
},
{ client: direct },
)
assert.equal(
requests.at(-1).path,
'/upload-sessions/a%2Fb/small-file?knowledgeSpaceId=space',
)
assert.equal(requests.at(-1).headers['content-type'], 'application/octet-stream')
assert.equal(requests.at(-1).data, 'binary')
await knowledge.knowledgeSpaces.byId.documents.bulk.post(
{
params: { id: 'id' },
body: { files: [new File(['a'], 'a.txt'), new File(['b'], 'b.txt')] },
},
{ client: direct },
)
assert.deepEqual(
requests
.at(-1)
.data.getAll('files')
.map((file) => file.name),
['a.txt', 'b.txt'],
)
for (const member of ['createByFile', 'create_by_file']) {
await serviceApi.datasets.byDatasetId.document[member].post(
{ params: { dataset_id: 'id' }, body: { file: new File(['file'], 'file.txt') } },
{ client },
)
}
assert.equal(requests.at(-2).path, '/v1/datasets/id/document/create-by-file')
assert.equal(requests.at(-1).path, '/v1/datasets/id/document/create_by_file')
await publicApi.apps.byAppId.chat.run.post(
{
params: { app_id: 'id' },
contentType: 'multipart/form-data',
body: { query: 'hello', inputs: { enabled: true } },
},
{ client },
)
assert.equal(requests.at(-1).path, '/openapi/v1/apps/id/chat:run')
assert.equal(await requests.at(-1).data.get('query').text(), '"hello"')
assert.equal(await requests.at(-1).data.get('inputs').text(), '{"enabled":true}')
const stream = await serviceApi.chatMessages.post(
{ body: { query: 'hello', inputs: {}, user: 'test', response_mode: 'streaming' } },
{ client, signal: AbortSignal.timeout(3000) },
)
assert(stream instanceof ReadableStream)
const reader = stream.getReader()
assert.match(new TextDecoder().decode((await reader.read()).value), /"answer":"hello"/)
await reader.cancel()
} finally {
if (previousLocation) Object.defineProperty(globalThis, 'location', previousLocation)
else delete globalThis.location
server.closeAllConnections()
await new Promise((resolve) => server.close(resolve))
}
},
)
for (const [index, members, route] of [
[0, 'datasets.get', '/datasets'],
[6, 'health.get', '/health'],
]) {
for (const namespace of ['api', 'query'])
await t.test(
`${names[index]} ${namespace}: full-document bundle equals one-path bundle`,
async () => {
async function bundle(file) {
writeFileSync(
join(dir, 'entry.ts'),
`import { ${namespace} } from './${file}'; export const operation = ${namespace}.${members}${namespace === 'query' ? '.queryOptions' : ''};`,
)
const result = await build({
configFile: false,
root: dir,
logLevel: 'silent',
plugins: [openapi()],
build: {
write: false,
minify: true,
lib: { entry: join(dir, 'entry.ts'), formats: ['es'] },
},
})
return (Array.isArray(result) ? result : [result])
.flatMap((result) => result.output)
.filter((file) => file.type === 'chunk')
.map((file) => file.code)
.join('\n')
}
const full = await bundle(`${names[index]}.openapi`)
const reduced = {
...specs[index],
paths: { [route]: { ...specs[index].paths[route], post: undefined } },
}
writeFileSync(join(dir, 'reduced.openapi'), JSON.stringify(reduced))
const small = await bundle('reduced.openapi')
const normalize = (code) => code.replace(/^\/\/.*$/gm, '')
assert.equal(normalize(full), normalize(small))
for (const marker of [
'/files/upload',
'/upload-sessions/',
'DatasetCreatePayload',
'parseDocument',
'YAMLParseError',
])
assert(!full.includes(marker), `Unexpected unused content: ${marker}`)
t.diagnostic(
`${names[index]} ${namespace}: ${Buffer.byteLength(full)} bytes, ${gzipSync(full).length} gzip`,
)
},
)
}
} finally {
for (const [index, file] of files.entries())
assert.equal(
hash(readFileSync(file, 'utf8')),
hash(contents[index]),
'Source document must stay untouched',
)
rmSync(dir, { recursive: true, force: true })
}
})
@@ -0,0 +1,79 @@
/* oxlint-disable vitest/no-import-node-test -- Exercise native TS hover resolution against real Python exports. */
import assert from 'node:assert/strict'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { join, resolve } from 'node:path'
import { test } from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { rpcProcess } from '../test/rpc.mjs'
import navigation from '../vscode/locations.cjs'
/* oxlint-enable vitest/no-import-node-test */
const root = resolve(import.meta.dirname, '..')
const compiler = join(root, 'node_modules/typescript/bin/tsc')
test(
'subpath type hovers navigate to Python models and handlers through aliases and re-exports',
{ timeout: 180000 },
async (t) => {
const dir = mkdtempSync(join(root, 'integration/.navigation-'))
t.after(() => rmSync(dir, { recursive: true, force: true }))
writeFileSync(
join(dir, 'types.ts'),
"export type { DatasetCreatePayload as Payload, PostDatasetsData as Request, PostDatasetsResponse as Response } from '@dify/openapi-content-mapper/console/datasets';",
)
const source = [
"import type { Payload, Request, Response } from './types.js';",
'export const payload: Payload = { name: "Docs" };',
'export const request: Request = { url: "/datasets", body: payload };',
'export function response(value: Response) { return value; }',
].join('\n')
writeFileSync(join(dir, 'index.ts'), source)
writeFileSync(
join(dir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: { strict: true, noEmit: true, target: 'ES2022', module: 'NodeNext' },
contentMappers: [{ package: root, extensions: ['.openapi-types'] }],
include: ['*.ts'],
}),
)
const rpc = rpcProcess(process.execPath, [compiler, '--lsp', '--stdio'], root, 120000)
t.after(() => rpc.close())
const uri = pathToFileURL(join(dir, 'index.ts')).href
await rpc.request('initialize', {
processId: process.pid,
rootUri: pathToFileURL(dir).href,
initializationOptions: { runExternalCode: true },
capabilities: { textDocument: { hover: { contentFormat: ['markdown'] } } },
})
rpc.notify('initialized', {})
rpc.notify('textDocument/didOpen', {
textDocument: { uri, languageId: 'typescript', version: 1, text: source },
})
for (const [line, name, definition] of [
[1, 'Payload', 'class DatasetCreatePayload(BaseModel):'],
[
2,
'Request',
'def post(self, req_data: DatasetCreatePayload, request_context: RequestContext):',
],
[
3,
'Response',
'def post(self, req_data: DatasetCreatePayload, request_context: RequestContext):',
],
]) {
const hover = await rpc.request('textDocument/hover', {
textDocument: { uri },
position: { line, character: source.split('\n')[line].indexOf(name) },
})
const locations = navigation.backendLocations([hover.contents].flat())
assert.equal(locations.length, 1, JSON.stringify(hover))
const target = fileURLToPath(locations[0].uri)
assert.equal(target, resolve(root, '../../api/controllers/console/datasets/datasets.py'))
assert.equal(
readFileSync(target, 'utf8').split('\n')[locations[0].line - 1].trim(),
definition,
)
}
},
)