130 lines
5.7 KiB
TypeScript
130 lines
5.7 KiB
TypeScript
import { readFileSync } from 'node:fs'
|
|
import { readFile } from 'node:fs/promises'
|
|
import { dirname, relative, resolve as resolvePath } from 'node:path'
|
|
import type { UserConfig, TsdownPlugin } from 'tsdown'
|
|
import { clientCssPlugin } from './vendor/dsh-mnemon/tsdown.config.ts'
|
|
|
|
const PLUGIN_ID = 'dsh-brain'
|
|
const VENDOR_ROOT = 'vendor/dsh-mnemon'
|
|
const MNEMON_ENTRY = '\0dsh-brain-mnemon-entry.mjs'
|
|
|
|
function mnemonClientPlugin(): TsdownPlugin {
|
|
const paths = JSON.parse(readFileSync(VENDOR_ROOT + '/tsconfig.json', 'utf8')).compilerOptions.paths as Record<string, string[]>
|
|
const css = clientCssPlugin()
|
|
const resolveCss = css.resolveId
|
|
const loadCss = css.load
|
|
if (typeof resolveCss !== 'function' || typeof loadCss !== 'function') {
|
|
throw new Error('Mnemon CSS plugin must expose resolveId and load hooks')
|
|
}
|
|
return {
|
|
name: 'dsh-brain-mnemon-browser',
|
|
resolveId(source, importer, options) {
|
|
if (source === 'brain:mnemon-client') return MNEMON_ENTRY
|
|
const asset = /^(dsh-brain-mnemon-[^/]+)\/(presentation\/[^/]+)$/.exec(source)
|
|
if (asset !== null) {
|
|
const path = resolvePath(VENDOR_ROOT, 'plugins', asset[1], asset[2])
|
|
return source.endsWith('.module.css') ? resolveCss.call(this, path, undefined, options) : path
|
|
}
|
|
if (source === 'dsh-brain-mnemon/client' || importer?.replaceAll('\\', '/').includes('/' + VENDOR_ROOT + '/')) {
|
|
return resolveCss.call(this, source, importer, options)
|
|
}
|
|
return null
|
|
},
|
|
load(id, options) {
|
|
if (id === MNEMON_ENTRY) {
|
|
const from = (path: string) => JSON.stringify(resolvePath(VENDOR_ROOT, path))
|
|
return [
|
|
'export { apply as applyMnemon, inject as mnemonServices } from ' + from('src/client/index.ts'),
|
|
...Object.entries({ Runtime: 'runtime', Documents: 'documents', MemorySpaces: 'memory-spaces', Skills: 'skills' }).map(([name, source]) => {
|
|
const specifier = Object.keys(paths).find(key => key.endsWith('-' + source + '/client'))
|
|
const entry = specifier === undefined ? undefined : paths[specifier]?.[0]
|
|
if (entry === undefined) throw new Error('Missing vendored browser entry for Mnemon ' + source)
|
|
return 'export { apply as apply' + name + ' } from ' + from(entry)
|
|
}),
|
|
].join('\n')
|
|
}
|
|
return loadCss.call(this, id, options)
|
|
},
|
|
renderChunk(code) {
|
|
// The upstream CSS loader uses absolute virtual IDs internally.
|
|
return code.replace(/^[ \t]*\/\/ \\0dsh-brain-mnemon-css:[^\r\n]*[\r\n]+/gm, '')
|
|
},
|
|
}
|
|
}
|
|
const CSS_VIRTUAL_PREFIX = '\0dsh-brain-css:'
|
|
const CSS_VIRTUAL_SUFFIX = '.mjs'
|
|
|
|
function cssHash(value: string): string {
|
|
let hash = 2166136261
|
|
for (let index = 0; index < value.length; index += 1) {
|
|
hash ^= value.charCodeAt(index)
|
|
hash = Math.imul(hash, 16777619)
|
|
}
|
|
return (hash >>> 0).toString(36)
|
|
}
|
|
|
|
/** Minimal CSS-modules inliner: scope class names, inject one <style> tag. */
|
|
function brainCssPlugin(): TsdownPlugin {
|
|
return {
|
|
name: 'dsh-brain-css-modules-inline',
|
|
resolveId(source: string, importer: string | undefined) {
|
|
if (!source.endsWith('.module.css')) return null
|
|
const absolute = importer === undefined ? source : resolvePath(dirname(importer), source)
|
|
const rel = relative(process.cwd(), absolute).replaceAll('\\', '/')
|
|
return CSS_VIRTUAL_PREFIX + rel + CSS_VIRTUAL_SUFFIX
|
|
},
|
|
async load(virtualId: string) {
|
|
if (!virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null
|
|
const fileId = resolvePath(process.cwd(), virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length))
|
|
this.addWatchFile(fileId)
|
|
const source = await readFile(fileId, 'utf8')
|
|
const filename = relative(process.cwd(), fileId).replaceAll('\\', '/')
|
|
const classMap: Record<string, string> = {}
|
|
for (const match of source.matchAll(/\.([A-Za-z_][A-Za-z0-9_-]*)/g)) {
|
|
const local = match[1]
|
|
if (classMap[local] === undefined) classMap[local] = 'dshbrain_' + cssHash(filename + ':' + local)
|
|
}
|
|
let css = source
|
|
for (const local of Object.keys(classMap).sort((left, right) => right.length - left.length)) {
|
|
css = css.replace(new RegExp('\\.' + local + '(?![\\w-])', 'g'), '.' + classMap[local])
|
|
}
|
|
return [
|
|
'const css = ' + JSON.stringify(css) + ';',
|
|
'const tagId = ' + JSON.stringify(filename) + ';',
|
|
'if (typeof document !== "undefined" && typeof document.querySelector === "function" && typeof document.createElement === "function") {',
|
|
' let tag = document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]");',
|
|
' if (!tag) { tag = document.createElement("style"); tag.dataset.pluginCss = tagId; document.head.appendChild(tag); }',
|
|
' if (tag.textContent !== css) tag.textContent = css;',
|
|
'}',
|
|
'export default ' + JSON.stringify(classMap) + ';',
|
|
].join('\n')
|
|
},
|
|
}
|
|
}
|
|
|
|
export default {
|
|
name: PLUGIN_ID + '/client',
|
|
entry: { index: 'src-client/index.ts' },
|
|
outDir: 'client',
|
|
format: 'cjs',
|
|
platform: 'browser',
|
|
target: 'es2022',
|
|
fixedExtension: false,
|
|
outExtensions: () => ({ js: '.js' }),
|
|
dts: false,
|
|
sourcemap: false,
|
|
clean: false,
|
|
tsconfig: VENDOR_ROOT + '/tsconfig.json',
|
|
deps: {
|
|
neverBundle: [/^react(?:\/.*)?$/, /^react-dom(?:\/.*)?$/, /^@deepseek-ai\/dsh-client-ui-primitives(?:\/.*)?$/],
|
|
alwaysBundle: [/^dsh-brain-mnemon(?:[-/]|$)/],
|
|
},
|
|
define: { 'process.env.NODE_ENV': '"production"' },
|
|
plugins: [mnemonClientPlugin(), brainCssPlugin()],
|
|
outputOptions: {
|
|
banner: `window.__ModuleLoader__.load({ id: '${PLUGIN_ID}', factory: (require) => {`,
|
|
intro: 'var module = { exports: {} }; var exports = module.exports;',
|
|
footer: 'return module.exports; } });',
|
|
},
|
|
} satisfies UserConfig
|