chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
+176
@@ -0,0 +1,176 @@
|
||||
import { spawn } from 'node:child_process'
|
||||
import { realpathSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import unusedConfig from '../oxlint.unused.config.json' with { type: 'json' }
|
||||
|
||||
type OxlintDiagnostic = {
|
||||
labels?: { file?: string; span?: { line: number; column: number } }[]
|
||||
filename?: string
|
||||
code?: string
|
||||
message?: string
|
||||
}
|
||||
|
||||
const scriptDir = path.dirname(fileURLToPath(import.meta.url))
|
||||
const repoRoot = path.resolve(scriptDir, '../../..')
|
||||
const webDir = path.join(repoRoot, 'web')
|
||||
const unusedLintConfig = path.resolve(scriptDir, '../oxlint.unused.config.json')
|
||||
const require = createRequire(import.meta.url)
|
||||
const vitePlusEntry = realpathSync(require.resolve('vite-plus'))
|
||||
const vitePlusRequire = createRequire(vitePlusEntry)
|
||||
// Resolve the bundled binary directly so Vite+ cannot inject unrelated project lint rules.
|
||||
const oxlintPackagePath = vitePlusRequire.resolve('oxlint/package.json')
|
||||
const oxlintManifest = vitePlusRequire(oxlintPackagePath)
|
||||
const oxlintBin =
|
||||
typeof oxlintManifest.bin === 'string' ? oxlintManifest.bin : oxlintManifest.bin?.oxlint
|
||||
if (!oxlintBin) throw new Error('Unable to resolve the bundled Oxlint executable.')
|
||||
const oxlint = path.resolve(path.dirname(oxlintPackagePath), oxlintBin)
|
||||
|
||||
function run(command: string, args: string[], options: { cwd?: string } = {}) {
|
||||
return new Promise<{ status: number | null; stdout: string; stderr: string }>(
|
||||
(resolve, reject) => {
|
||||
const child = spawn(command, args, {
|
||||
cwd: options.cwd,
|
||||
env: process.env,
|
||||
shell: false,
|
||||
})
|
||||
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
child.stdout.on('data', (data) => (stdout += data))
|
||||
child.stderr.on('data', (data) => (stderr += data))
|
||||
child.on('error', reject)
|
||||
child.on('close', (status) => resolve({ status, stdout, stderr }))
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
function parseOxlintJson(stdout: string): { diagnostics?: OxlintDiagnostic[] } {
|
||||
const jsonStart = stdout.indexOf('{')
|
||||
if (jsonStart === -1) throw new Error('Oxlint produced no JSON output.')
|
||||
|
||||
return JSON.parse(stdout.slice(jsonStart))
|
||||
}
|
||||
|
||||
function relativeDiagnostic(diagnostic: OxlintDiagnostic) {
|
||||
const label = diagnostic.labels?.[0]
|
||||
const diagnosticFile = label?.file ?? diagnostic.filename
|
||||
const filePath = diagnosticFile
|
||||
? path.relative(
|
||||
webDir,
|
||||
path.isAbsolute(diagnosticFile) ? diagnosticFile : path.join(webDir, diagnosticFile),
|
||||
)
|
||||
: '<unknown>'
|
||||
const span = label?.span ? `:${label.span.line}:${label.span.column}` : ''
|
||||
|
||||
return `${filePath}${span} ${diagnostic.code ?? ''} ${diagnostic.message ?? ''}`.trim()
|
||||
}
|
||||
|
||||
async function ensureCleanWorktree() {
|
||||
const result = await run('git', ['status', '--porcelain=v1'], { cwd: repoRoot })
|
||||
if (result.status !== 0) {
|
||||
process.stderr.write(result.stderr)
|
||||
throw new Error('Failed to check git status.')
|
||||
}
|
||||
|
||||
if (!result.stdout.trim()) return
|
||||
|
||||
console.error('This check runs knip --fix and must start from a clean worktree.')
|
||||
console.error('Commit or stash your changes first, then run it again.')
|
||||
console.error(result.stdout)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
async function restoreWorktree() {
|
||||
const restoreResult = await run('git', ['restore', '--staged', '--worktree', '.'], {
|
||||
cwd: repoRoot,
|
||||
})
|
||||
if (restoreResult.status !== 0) {
|
||||
process.stdout.write(restoreResult.stdout)
|
||||
process.stderr.write(restoreResult.stderr)
|
||||
throw new Error('Failed to restore tracked files after knip --fix.')
|
||||
}
|
||||
|
||||
const cleanResult = await run('git', ['clean', '-fd', '--', 'web'], {
|
||||
cwd: repoRoot,
|
||||
})
|
||||
if (cleanResult.status !== 0) {
|
||||
process.stdout.write(cleanResult.stdout)
|
||||
process.stderr.write(cleanResult.stderr)
|
||||
throw new Error('Failed to clean untracked files after knip --fix.')
|
||||
}
|
||||
}
|
||||
|
||||
const knip = fileURLToPath(new URL('../bin/knip.js', import.meta.resolve('knip')))
|
||||
let shouldRestore = false
|
||||
let hasUnusedMessages = false
|
||||
|
||||
try {
|
||||
await ensureCleanWorktree()
|
||||
shouldRestore = true
|
||||
|
||||
console.log('Running knip --production --fix...')
|
||||
const knipResult = await run(
|
||||
process.execPath,
|
||||
[knip, '--workspace', 'web', '--production', '--fix'],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
},
|
||||
)
|
||||
if (knipResult.status !== 0) {
|
||||
process.stdout.write(knipResult.stdout)
|
||||
process.stderr.write(knipResult.stderr)
|
||||
throw new Error('knip --production --fix failed.')
|
||||
}
|
||||
|
||||
console.log('Running isolated Oxlint unused checks after knip --fix...')
|
||||
const lintResult = await run(
|
||||
process.execPath,
|
||||
[
|
||||
oxlint,
|
||||
'--config',
|
||||
unusedLintConfig,
|
||||
// CLI ignore patterns are relative to Web's cwd, not the shared config directory.
|
||||
...unusedConfig.ignorePatterns.flatMap((pattern) => ['--ignore-pattern', pattern]),
|
||||
'--format',
|
||||
'json',
|
||||
'.',
|
||||
],
|
||||
{ cwd: webDir },
|
||||
)
|
||||
|
||||
let lintOutput
|
||||
try {
|
||||
lintOutput = parseOxlintJson(lintResult.stdout)
|
||||
} catch {
|
||||
process.stdout.write(lintResult.stdout)
|
||||
process.stderr.write(lintResult.stderr)
|
||||
throw new Error('Failed to parse Oxlint JSON output.')
|
||||
}
|
||||
|
||||
const unusedMessages = (lintOutput.diagnostics ?? []).map(relativeDiagnostic)
|
||||
if (lintResult.status !== 0 && unusedMessages.length === 0) {
|
||||
process.stdout.write(lintResult.stdout)
|
||||
process.stderr.write(lintResult.stderr)
|
||||
throw new Error(`Oxlint unused check failed with exit code ${lintResult.status}.`)
|
||||
}
|
||||
|
||||
if (unusedMessages.length > 0) {
|
||||
hasUnusedMessages = true
|
||||
console.error('Unused declarations remain after applying knip --production --fix.')
|
||||
console.error(
|
||||
'Remove these declarations; if they are only referenced by tests, remove the matching tests too.',
|
||||
)
|
||||
for (const message of unusedMessages) console.error(message)
|
||||
} else {
|
||||
console.log('No Oxlint unused declarations remain after knip --production --fix.')
|
||||
}
|
||||
} finally {
|
||||
if (shouldRestore) {
|
||||
console.log('Restoring checkout after knip --fix...')
|
||||
await restoreWorktree()
|
||||
}
|
||||
}
|
||||
|
||||
if (hasUnusedMessages) process.exit(1)
|
||||
@@ -0,0 +1,202 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import fs from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import path from 'node:path'
|
||||
import process from 'node:process'
|
||||
import ts from 'typescript'
|
||||
|
||||
const webRoot = path.resolve(import.meta.dirname, '../../../web')
|
||||
const repositoryRoot = path.resolve(webRoot, '..')
|
||||
const configPath = path.resolve(import.meta.dirname, '../a11y.config.ts')
|
||||
const require = createRequire(import.meta.url)
|
||||
const vitePlusRequire = createRequire(require.resolve('vite-plus/package.json'))
|
||||
const oxlintPackageDirectory = path.dirname(vitePlusRequire.resolve('oxlint/package.json'))
|
||||
const oxlintEntry = path.resolve(oxlintPackageDirectory, 'bin', 'oxlint')
|
||||
const inputArguments = process.argv.slice(2)
|
||||
const dependencyMode = inputArguments.includes('--deps')
|
||||
const inputTargets = inputArguments.filter((argument) => argument !== '--deps')
|
||||
|
||||
function printUsage() {
|
||||
console.error(`Usage:
|
||||
pnpm lint:a11y <page-file-or-directory> [...]
|
||||
pnpm lint:a11y --deps <entry-file> [...]`)
|
||||
}
|
||||
|
||||
if (inputTargets.length === 0) {
|
||||
printUsage()
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const unsupportedOption = inputTargets.find((target) => target.startsWith('-'))
|
||||
|
||||
if (unsupportedOption) {
|
||||
console.error(`Unknown option: ${unsupportedOption}`)
|
||||
printUsage()
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const resolvedTargets = inputTargets.map((target) => {
|
||||
if (path.isAbsolute(target)) return target
|
||||
|
||||
if (target === 'web' || target.startsWith('web/') || target.startsWith('web\\'))
|
||||
return path.resolve(repositoryRoot, target)
|
||||
|
||||
return path.resolve(webRoot, target)
|
||||
})
|
||||
|
||||
const sourceExtensions = new Set(['.cjs', '.cts', '.js', '.jsx', '.mjs', '.mts', '.ts', '.tsx'])
|
||||
const jsxExtensions = new Set(['.jsx', '.tsx'])
|
||||
const ignoredDirectories = new Set([
|
||||
'.next',
|
||||
'.vinext',
|
||||
'coverage',
|
||||
'dist',
|
||||
'node_modules',
|
||||
'storybook-static',
|
||||
])
|
||||
|
||||
function isWithinWebRoot(filePath: string) {
|
||||
const relativePath = path.relative(webRoot, filePath)
|
||||
return relativePath !== '' && !relativePath.startsWith('..') && !path.isAbsolute(relativePath)
|
||||
}
|
||||
|
||||
function isTraversableSourceFile(filePath: string) {
|
||||
if (!isWithinWebRoot(filePath) || !sourceExtensions.has(path.extname(filePath))) return false
|
||||
if (/\.d\.[cm]?ts$/u.test(filePath)) return false
|
||||
|
||||
return !path
|
||||
.relative(webRoot, filePath)
|
||||
.split(path.sep)
|
||||
.some((segment) => ignoredDirectories.has(segment))
|
||||
}
|
||||
|
||||
function formatTypeScriptDiagnostics(diagnostics: readonly ts.Diagnostic[]) {
|
||||
return ts.formatDiagnostics(diagnostics, {
|
||||
getCanonicalFileName: (fileName: string) => fileName,
|
||||
getCurrentDirectory: () => webRoot,
|
||||
getNewLine: () => ts.sys.newLine,
|
||||
})
|
||||
}
|
||||
|
||||
function readCompilerOptions() {
|
||||
const tsconfigPath = ts.findConfigFile(webRoot, ts.sys.fileExists, 'tsconfig.json')
|
||||
|
||||
if (!tsconfigPath) throw new Error('Unable to find web/tsconfig.json.')
|
||||
|
||||
const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile)
|
||||
|
||||
if (configFile.error) throw new Error(formatTypeScriptDiagnostics([configFile.error]))
|
||||
|
||||
const parsedConfig = ts.parseJsonConfigFileContent(
|
||||
configFile.config,
|
||||
ts.sys,
|
||||
path.dirname(tsconfigPath),
|
||||
undefined,
|
||||
tsconfigPath,
|
||||
)
|
||||
const errors = parsedConfig.errors.filter(
|
||||
(diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error,
|
||||
)
|
||||
|
||||
if (errors.length > 0) throw new Error(formatTypeScriptDiagnostics(errors))
|
||||
|
||||
return parsedConfig.options
|
||||
}
|
||||
|
||||
function collectLocalDependencies(entryFiles: string[]) {
|
||||
for (const entryFile of entryFiles) {
|
||||
let stats
|
||||
|
||||
try {
|
||||
stats = fs.statSync(entryFile)
|
||||
} catch {
|
||||
throw new Error(`Entry file does not exist: ${entryFile}`)
|
||||
}
|
||||
|
||||
if (!stats.isFile()) throw new Error(`--deps only accepts entry files: ${entryFile}`)
|
||||
if (!isTraversableSourceFile(entryFile))
|
||||
throw new Error(
|
||||
`Entry file must be a JavaScript or TypeScript source file under web/: ${entryFile}`,
|
||||
)
|
||||
}
|
||||
|
||||
const compilerOptions = readCompilerOptions()
|
||||
const canonicalFileName = ts.sys.useCaseSensitiveFileNames
|
||||
? (fileName: string) => fileName
|
||||
: (fileName: string) => fileName.toLowerCase()
|
||||
const resolutionCache = ts.createModuleResolutionCache(
|
||||
webRoot,
|
||||
canonicalFileName,
|
||||
compilerOptions,
|
||||
)
|
||||
const visitedFiles = new Map<string, string>()
|
||||
const pending = [...entryFiles]
|
||||
|
||||
while (pending.length > 0) {
|
||||
const currentFile = path.resolve(pending.pop()!)
|
||||
const canonicalCurrentFile = canonicalFileName(currentFile)
|
||||
|
||||
if (visitedFiles.has(canonicalCurrentFile)) continue
|
||||
visitedFiles.set(canonicalCurrentFile, currentFile)
|
||||
|
||||
const sourceText = ts.sys.readFile(currentFile)
|
||||
|
||||
if (sourceText === undefined) throw new Error(`Unable to read imported file: ${currentFile}`)
|
||||
|
||||
const importedFiles = ts.preProcessFile(sourceText, true, true).importedFiles
|
||||
|
||||
for (const importedFile of importedFiles) {
|
||||
const resolvedModule = ts.resolveModuleName(
|
||||
importedFile.fileName,
|
||||
currentFile,
|
||||
compilerOptions,
|
||||
ts.sys,
|
||||
resolutionCache,
|
||||
).resolvedModule
|
||||
|
||||
if (!resolvedModule || resolvedModule.isExternalLibraryImport) continue
|
||||
|
||||
const dependencyPath = path.resolve(resolvedModule.resolvedFileName)
|
||||
|
||||
if (isTraversableSourceFile(dependencyPath)) pending.push(dependencyPath)
|
||||
}
|
||||
}
|
||||
|
||||
const files = [...visitedFiles.values()]
|
||||
.filter((filePath) => jsxExtensions.has(path.extname(filePath)))
|
||||
.sort()
|
||||
|
||||
console.log(
|
||||
`Resolved ${files.length} JSX source ${files.length === 1 ? 'file' : 'files'} from ${entryFiles.length} ${entryFiles.length === 1 ? 'entry' : 'entries'}.`,
|
||||
)
|
||||
|
||||
return files
|
||||
}
|
||||
|
||||
let targets = resolvedTargets
|
||||
|
||||
if (dependencyMode) {
|
||||
try {
|
||||
targets = collectLocalDependencies(resolvedTargets)
|
||||
} catch (error) {
|
||||
console.error(error instanceof Error ? error.message : String(error))
|
||||
process.exit(2)
|
||||
}
|
||||
}
|
||||
|
||||
if (targets.length === 0) {
|
||||
console.log('No JSX or TSX source files found to lint.')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const result = spawnSync(process.execPath, [oxlintEntry, '-c', configPath, ...targets], {
|
||||
cwd: webRoot,
|
||||
stdio: 'inherit',
|
||||
})
|
||||
|
||||
if (result.error) {
|
||||
console.error(`Failed to start the accessibility lint: ${result.error.message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
process.exit(result.status ?? 1)
|
||||
Reference in new issue
Block a user