-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtsdown.config.ts
More file actions
147 lines (141 loc) · 6.02 KB
/
Copy pathtsdown.config.ts
File metadata and controls
147 lines (141 loc) · 6.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import { readFile } from 'node:fs/promises'
import { existsSync } from 'node:fs'
import { createRequire } from 'node:module'
import { basename, dirname, resolve as resolvePath } from 'node:path'
import { fileURLToPath } from 'node:url'
import { transform } from 'lightningcss'
import type { UserConfig } from 'tsdown'
import { CLIENT_EXTERNALS, findUnsafeClientRequire } from './src/shared/client-bundle-guard.ts'
function resolveBrowserPkg(spec: string): string {
const resolved = import.meta.resolve(spec)
return resolved.startsWith('file:') ? fileURLToPath(resolved) : resolved
}
/**
* mermaid's architecture diagrams import cytoscape. Output format is CJS, so
* rolldown would pick cytoscape's "require" export and hoist
* require("cytoscape") — DSH ModuleLoader has no such factory. Point at the
* ESM file by path (createRequire cannot use the "import"-only subpath).
*/
function resolveMermaidCytoscapeEsm(): string {
const mermaidPkg = fileURLToPath(new URL(import.meta.resolve('mermaid/package.json')))
const cytoscapeCjs = createRequire(mermaidPkg).resolve('cytoscape')
const esm = resolvePath(dirname(cytoscapeCjs), 'cytoscape.esm.mjs')
if (!existsSync(esm)) {
throw new Error(`找不到 mermaid 附带的 cytoscape ESM(${esm})。请重新安装依赖后再构建。`)
}
return esm
}
const PACKAGE_ID = 'dsh-workbench-plugin'
const CSS_VIRTUAL_PREFIX = '\0dsh-css:'
const CSS_VIRTUAL_SUFFIX = '.mjs'
const host: UserConfig = {
name: PACKAGE_ID,
entry: { index: 'src/index.ts' },
outDir: 'lib',
format: ['esm'],
platform: 'node',
target: 'es2024',
dts: false,
clean: true,
sourcemap: false,
fixedExtension: false,
external: [/^@deepseek-ai\//, /^node:/, 'node-pty'],
outputOptions: {
entryFileNames: 'index.js',
},
}
const client: UserConfig = {
name: `${PACKAGE_ID}/client`,
entry: { client: 'src/client/index.ts' },
outDir: 'lib',
format: 'cjs',
platform: 'browser',
// Do not inherit package.json engines.node (node22…): that makes rolldown
// pick fflate's Node export, which does createRequire("module") and crashes
// DSH ModuleLoader at plugin load.
target: 'es2024',
dts: false,
sourcemap: true,
clean: false,
external: [...CLIENT_EXTERNALS],
noExternal: (id: string) => (CLIENT_EXTERNALS.includes(id as (typeof CLIENT_EXTERNALS)[number]) ? undefined : true),
alias: {
'node:process': resolvePath('src/client/shims/node-process.ts'),
'node:path': resolvePath('src/client/shims/node-path.ts'),
'node:url': resolvePath('src/client/shims/node-url.ts'),
'node:module': resolvePath('src/client/shims/node-module.ts'),
module: resolvePath('src/client/shims/node-module.ts'),
fflate: resolveBrowserPkg('fflate/browser'),
cytoscape: resolveMermaidCytoscapeEsm(),
},
define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production'),
'import.meta.env.MODE': JSON.stringify(process.env.NODE_ENV ?? 'production'),
'import.meta.env': JSON.stringify({ MODE: process.env.NODE_ENV ?? 'production' }),
},
plugins: [{
name: 'dsh-forbid-node-require',
generateBundle(_opts: unknown, bundle: Record<string, { type: string; code?: string }>) {
for (const [fileName, chunk] of Object.entries(bundle)) {
if (chunk.type !== 'chunk' || chunk.code === undefined) continue
const forbidden = findUnsafeClientRequire(chunk.code)
if (forbidden !== undefined) {
throw new Error(`${fileName} 含有 ${forbidden}。DSH 网页 ModuleLoader 只能加载平台白名单模块,其余依赖必须打进 client.js`)
}
}
},
}, {
name: 'dsh-css-modules-inline',
resolveId(source: string, importer: string | undefined) {
if (!source.endsWith('.css')) return null
const abs = importer !== undefined ? resolvePath(dirname(importer), source) : source
if (existsSync(abs)) return CSS_VIRTUAL_PREFIX + abs + CSS_VIRTUAL_SUFFIX
try {
const resolved = import.meta.resolve(source)
const file = resolved.startsWith('file:') ? new URL(resolved).pathname : resolved
if (existsSync(file)) return CSS_VIRTUAL_PREFIX + file + CSS_VIRTUAL_SUFFIX
} catch { /* fall through */ }
return null
},
async load(virtualId: string) {
if (!virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null
const fileId = virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)
this.addWatchFile(fileId)
const source = await readFile(fileId)
const modules = fileId.endsWith('.module.css')
const { code, exports: cssExports } = transform({
filename: fileId,
code: source,
cssModules: modules ? { pattern: '[hash]_[local]' } : false,
minify: true,
})
const classMap: Record<string, string> = {}
if (modules) {
for (const [local, exp] of Object.entries(cssExports ?? {})) classMap[local] = exp.name
}
return [
`const css = ${JSON.stringify(code.toString())};`,
`const tagId = ${JSON.stringify(`${PACKAGE_ID}/${basename(fileId)}`)};`,
'if (typeof document !== \'undefined\' && document.querySelector(\'style[data-plugin-css=\' + JSON.stringify(tagId) + \']\') === null) {',
' const tag = document.createElement(\'style\');',
` tag.dataset.plugin = ${JSON.stringify(PACKAGE_ID)};`,
' tag.dataset.pluginCss = tagId;',
' tag.textContent = css;',
' document.head.appendChild(tag);',
'}',
`export default ${JSON.stringify(classMap)};`,
].join('\n')
},
}],
outputOptions: {
entryFileNames: 'client.js',
// The DSH web ModuleLoader wraps this bundle in a CJS factory that cannot
// load sibling chunks, so every dependency (mermaid lazy diagram modules
// included) must land in this single file.
inlineDynamicImports: true,
banner: `window.__ModuleLoader__.load({ id: ${JSON.stringify(PACKAGE_ID)}, factory: (require) => {`,
footer: 'return module.exports; } });',
intro: 'var module = { exports: {} }; var exports = module.exports;',
},
}
export default [host, client]