ray-template/vite-helper/layout-writer.ts
XiaoDaiGua-Ray 22dfe441e0
feat(layout): add a composable workspace designer
Add layout registration, visual editing, and source generation.

Preserve embedded pages and wait for asynchronous layout renderers.

Add workspace lint and formatting commands.
2026-12-01 17:34:27 +08:00

180 lines
5.0 KiB
TypeScript

import { randomUUID } from 'node:crypto'
import { link, open, readdir, realpath, unlink } from 'node:fs/promises'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { join } from 'node:path'
import type { Plugin } from 'vite'
import {
generateLayoutSource,
layoutDefinitionsDirectory,
layoutFileName,
layoutWriteEndpoint,
parseLayoutDesign,
} from '../apps/admin/src/layout/designer.ts'
import type { LayoutDesign } from '../apps/admin/src/layout/designer.ts'
const bodyLimit = 8192
const localHosts = new Set(['127.0.0.1', 'localhost', '[::1]'])
const localPeers = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
function localBrowserRequest(request: IncomingMessage) {
const { headers, socket } = request
if (!localPeers.has(socket.remoteAddress ?? '') || !headers.origin)
return false
try {
const origin = new URL(headers.origin)
const protocol =
'encrypted' in socket && socket.encrypted ? 'https:' : 'http:'
return (
origin.protocol === protocol &&
localHosts.has(origin.hostname) &&
origin.origin === headers.origin &&
origin.host === headers.host &&
(!headers['sec-fetch-site'] ||
headers['sec-fetch-site'] === 'same-origin') &&
headers['x-ray-layout-write'] === '1' &&
headers['content-type']?.split(';')[0].trim().toLowerCase() ===
'application/json'
)
} catch {
return false
}
}
function reply(
response: ServerResponse,
status: number,
body: { path: string } | { error: string },
) {
response.writeHead(status, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
})
response.end(JSON.stringify(body))
}
async function writeLayout(root: string, design: LayoutDesign) {
const directory = join(await realpath(root), layoutDefinitionsDirectory)
const filename = layoutFileName(design.id)
if ((await realpath(directory)) !== directory)
throw new Error('Invalid layout directory')
const files = await readdir(directory)
if (
files.some((file) =>
['tsx', 'ts', 'jsx', 'js'].some(
(ext) => file === `${design.id}.layout.${ext}`,
),
)
)
return false
// 保证 Vite 只观察到完整源码;并发请求和已有文件由原子的硬链接创建操作仲裁。
const temp = join(directory, `.ray-layout-${randomUUID()}.tmp`)
const file = await open(temp, 'wx')
try {
try {
await file.writeFile(generateLayoutSource(design))
} finally {
await file.close()
}
await link(temp, join(directory, filename))
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
throw error
} finally {
await unlink(temp)
}
return true
}
export function layoutWriterPlugin(projectRoot: string): Plugin {
return {
name: 'ray:layout-lab-writer',
apply: 'serve',
configureServer(server) {
if (server.config.isProduction || server.config.mode === 'production')
return
server.middlewares.use(async (request, response, next) => {
if (request.url !== layoutWriteEndpoint) return next()
if (request.method !== 'POST') {
response.setHeader('Allow', 'POST')
return reply(response, 405, { error: 'method' })
}
if (!localBrowserRequest(request))
return reply(response, 403, { error: 'forbidden' })
let design: LayoutDesign
try {
const chunks: Buffer[] = []
let bytes = 0
for await (const chunk of request.iterator({
destroyOnReturn: false,
})) {
const data = Buffer.from(chunk)
bytes += data.length
if (bytes > bodyLimit) {
request.resume()
return reply(response, 413, { error: 'too-large' })
}
chunks.push(data)
}
design = parseLayoutDesign(
JSON.parse(Buffer.concat(chunks).toString('utf8')),
)
} catch {
return reply(response, 400, { error: 'invalid' })
}
try {
if (!(await writeLayout(projectRoot, design)))
return reply(response, 409, { error: 'exists' })
} catch {
return reply(response, 500, { error: 'write-failed' })
}
// 原子发布的硬链接可能没有触发系统 add 事件。主动刷新 glob 模块及已连接的客户端。
const client = server.environments.client
try {
const catalog = await client.moduleGraph.getModuleByUrl(
'/src/layout/discovery.ts',
)
if (catalog) {
if (server.config.server.hmr === false)
client.moduleGraph.invalidateModule(catalog)
else await client.reloadModule(catalog)
}
} catch (error) {
// 文件已经创建,避免客户端将通知失败当成写入失败并重试。
server.config.logger.error(`[ray:layout-lab-writer] ${String(error)}`)
}
reply(response, 201, {
path: `${layoutDefinitionsDirectory}/${layoutFileName(design.id)}`,
})
})
},
}
}