/** * webapi/datascreen.ts — 镜像 jnpf-web-datascreen-vue3 独立大屏 webapp (v0.13+ jxcj 2026-07-01) * * 重要发现 (jxcj 2026-07-01): * - jnpf 6.x 大屏 web 端是 **jnpf-web-datascreen-vue3 独立编译项目** (不是 jnpf-web-apps-main) * - 路径: jnpf/前端/jnpf-web-datascreen-vue3/src/api/visual.js * - 端点: /visual/save (POST), /visual/list (GET), /visual/detail (GET), /visual/update, /visual/remove * - nginx 代理 /api/visual/* → 32000 (jnpf-datareport-univer 微服务, 跟大屏/报表同微服务) * - 大屏 web 端 addObj body: { visual: {password, category, status, title}, config: {detail, component} } * * 镜像源: jnpf/前端/jnpf-web-datascreen-vue3/src/api/visual.js (整文件) * export const addObj = (data) => request({ url: baseUrl + '/save', method: 'post', data: { visual: {...}, config: {...} } }) * * 之前 dacli bigscreen create 走 /extend/BigData (jnpf "大数据测试" 端点, 错), 报 BS-新12 silent fail * 现镜像 web 端 visual.js addObj 走 /api/visual/save * * 特殊处理: visual.js 用 `import request from '../axios'` (相对路径, 不是 defHttp), * loadWebModule 默认规则不替换. 不用 loader, 直接读 + 手动 replace + dynamic import. */ import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, dirname, basename } from 'node:path' import { pathToFileURL } from 'node:url' import { JnpfClient } from '../core/client.ts' import { initDatascreenShim } from './_datascreen_shim.ts' const DATASCREEN_SRC = '/home/ubuntu/ccWorkDir/jnpf/前端/jnpf-web-datascreen-vue3/src/api/visual.js' const DATASCREEN_OPTION_CONFIG_SRC = '/home/ubuntu/ccWorkDir/jnpf/前端/jnpf-web-datascreen-vue3/src/option/config.js' const DATASCREEN_OPTION_COMPONENTS_DIR = '/home/ubuntu/ccWorkDir/jnpf/前端/jnpf-web-datascreen-vue3/src/option/components' const SHIM_DIR = dirname(new URL(import.meta.url).pathname) const DATASCREEN_SHIM_PATH = join(SHIM_DIR, '_datascreen_shim.ts') let cached: any = null /** * 初始化 webapi 层: 读 + 替换 + dynamic import (跟 _loader.ts 一样的技巧, 但单独处理) * - 替换 1: `import { url } from '@/config'` → 删掉 (我们不需要 baseURL, 走主 client) * - 替换 2: `import { config } from '@/option/config'` → 删掉 * - 替换 3: `import request from '../axios'` → `import { request } from ''` * - 替换 4: `import { url } from '@/config'; import { config } from '@/option/config' const baseUrl = url + '/visual'` * → 删掉, 但 baseUrl 在 visual.js 里被所有方法用. 我们需要保留 const baseUrl = '/visual' (path 形式) * - 替换 5: `let header = window.$glob.header || {}; config.headers = Object.assign(config.headers, header);` * → 注: shim 已有 headers, 删掉这几行避免 window.$glob 引用 * - 替换 6: `const token = localStorage.getItem("token") || ''` → 注: shim 不需 token */ export async function initWebapi(client: JnpfClient): Promise { if (cached) return initDatascreenShim(client) const code = readFileSync(DATASCREEN_SRC, 'utf-8') const patched = code // 替换 axios import 为 shim .replace( /import\s+request\s+from\s+['"]\.\.\/axios['"]/, `import { request } from '${DATASCREEN_SHIM_PATH}'\nconst config = {}; // mock @/option/config (jnpf 大屏默认配置, 简化)`, ) // 替换 baseUrl 定义 (web 端用 url + '/visual', 我们用 const baseUrl = '/visual' 简化) .replace( /const\s+baseUrl\s*=\s*url\s*\+\s*['"]\/visual['"]/, `const baseUrl = '/visual'`, ) // 删掉 web 端 import (axios 拦截器引用了 url/config/window/localStorage, 我们不需要) .replace( /import\s*\{[^}]*\}\s*from\s*['"]@\/config['"];?/g, '', ) .replace( /import\s*\{[^}]*\}\s*from\s*['"]@\/option\/config['"];?/g, '', ) .replace( /let\s+header\s*=\s*window\.\$glob\.[^;]+;[\s\S]*?config\.headers\s*=\s*Object\.assign[^;]+;?/g, '', ) .replace( /const\s+token\s*=\s*localStorage\.[^;]+;?/g, '', ) .replace( /config\.headers\['Authorization'\][^;]+;?/g, '', ) .replace( /const\s+appCode\s*=[^;]+;?/g, '', ) .replace( /config\.headers\['App-Code'\][^;]+;?/g, '', ) // 写 tmp file + dynamic import const tmpDir = join(tmpdir(), 'dacli-datascreen-' + Date.now()) mkdirSync(tmpDir, { recursive: true }) const tmpFile = join(tmpDir, 'visual.mjs') writeFileSync(tmpFile, patched) cached = await import(pathToFileURL(tmpFile).href) } export function isWebapiLoaded(): boolean { return cached !== null } export const loadDatascreen: any = new Proxy({} as any, { get(_target, prop) { if (!cached) { throw new Error(`datascreen 模块未初始化, 请先 await initWebapi(client)`) } return cached[prop] }, }) /** 创建大屏 (镜像 web visual.js: addObj) */ export async function addObj(params: { title: string category: string status?: number password?: string width?: number height?: number config?: Record }): Promise { return loadDatascreen.addObj(params) } /** 大屏列表 (镜像 web visual.js: getList) */ export async function getList(params?: Record): Promise { return loadDatascreen.getList(params) } /** 大屏详情 (镜像 web visual.js: getObj) */ export async function getObj(id: string): Promise { return loadDatascreen.getObj(id) } /** 大屏分类 (镜像 web visual.js: getCategory) */ export async function getCategory(params?: Record): Promise { return loadDatascreen.getCategory(params) } /** 更新大屏 (镜像 web visual.js: updateObj) */ export async function updateObj(data: Record): Promise { return loadDatascreen.updateObj(data) } /** 删除大屏 (镜像 web visual.js: delObj) */ export async function delObj(id: string): Promise { return loadDatascreen.delObj(id) } // ===================================================================== // Phase 1+2: 镜像 option/config.js (基础配置) + option/components/*.vue (组件元数据) // 详见 dacli/docs/cmd-review/v0.13-webapi-form-workflow-refactor.md §8.2 // ===================================================================== /** * Phase 1: 镜像 jnpf-web-datascreen-vue3/src/option/config.js 第 35-72 行的 `config` 对象. * * 用途: dacli bigscreen construct 命令构造 save payload 时, config.detail = JSON.stringify(this.config), * 这个 this.config 必须跟 web 设计器初始值一致 (web 端 `result.vue:50` 也 import { config as defaultConfig }) * 跟 web 端 `result.vue:163` 的 `Object.assign(defaultConfig, json.detail)` 行为一致 — * 即 defaultConfig 是基础模板, json.detail 是覆盖. * * 注: 38 组件 metadata (themeList/colorOption/tableOption/dicOption) 暂时省略, 那些是设计器面板的 dic data, * 跟 save payload 无关 (save 只 save config + nav, 不 save 元数据). * Phase 5+ 如果要镜像 `header.vue:200-211` 完整 formdata 构造, 还需要 themeList 等. * * 实现策略: 直接读 web 端 option/config.js, 提取 `export const config = { ... }` 字面量对象, 用 Function 解析. * 跟 web 端 `result.vue:50` `import { config } from '@/option/config'` 行为一致 — 都是同一个对象. */ let cachedBaseConfig: Record | null = null export function getBaseConfig(): Record { if (cachedBaseConfig) return cachedBaseConfig // 简化兜底: web 端 option/config.js 第 35-72 行的默认 config 对象 (跟 shim 保持一致) const fallback: Record = { width: 1920, height: 1080, query: "function(){\n return window.$glob.params || {}\n}", header: "function(){\n return window.$glob.params || {}\n}", screen: 'x', mark: { show: false, text: '', fontSize: 20, color: 'rgba(100,100,100,0.2)', degree: -20 }, scale: 1, backgroundImage: `/img/bg/bg.png`, url: '', group: [], glob: [], theme: {}, themeId: '', filters: {}, style: '', before: '', overflow: false, styles: { show: false, contrast: 100, saturate: 100, brightness: 100, opacity: 100, grayscale: 0, hueRotate: 0, invert: 0, blur: 0 }, gradeShow: false, gradeLen: 30, } if (!existsSync(DATASCREEN_OPTION_CONFIG_SRC)) { cachedBaseConfig = fallback return cachedBaseConfig } try { const code = readFileSync(DATASCREEN_OPTION_CONFIG_SRC, 'utf-8') // 提取 `export const config = { ... }` 字面量 (顶层 config 对象) // 用括号配对法, 避免非贪婪 regex 在嵌套对象 (mark, styles) 处误终止 const startIdx = code.indexOf('export const config = {') if (startIdx === -1) { cachedBaseConfig = fallback return cachedBaseConfig } let depth = 0 let bodyStart = -1 let bodyEnd = -1 for (let i = startIdx; i < code.length; i++) { const ch = code[i] if (ch === '{') { if (depth === 0) bodyStart = i + 1 depth++ } else if (ch === '}') { depth-- if (depth === 0) { bodyEnd = i break } } } if (bodyStart === -1 || bodyEnd === -1) { cachedBaseConfig = fallback return cachedBaseConfig } const body = code.slice(bodyStart, bodyEnd) // 解析: `width: 1920, ...` 转成 JS 对象 // 注: web 端 config 引用了 `theme: themeList` (同级 export), Function 不会跨文件 import. // 在 scope 里 mock 一下 themeList = {} 即可, theme 字段对 save payload 暂时不影响. // eslint-disable-next-line no-new-func const parsed = Function('themeList', `return ({${body}})`)({}) if (parsed && typeof parsed === 'object') { cachedBaseConfig = parsed as Record } else { cachedBaseConfig = fallback } } catch (err) { console.warn('[datascreen] getBaseConfig 解析失败, 用 fallback:', err) cachedBaseConfig = fallback } return cachedBaseConfig } /** * Phase 2: 镜像 jnpf-web-datascreen-vue3/src/option/components/.vue 的 default data 段. * * 用途: dacli bigscreen construct 命令构造组件 entry (nav 数组元素) 时, 知道每个 prop 类型 * (bar/line/pie/text/map/...) 的 default data 形状 (data/option/component/group/index 等). * web 端 `build.vue` 通过 `import.meta.globEager` 加载 38 个 .vue, 然后拖拽时调 `initData()` * 派生一个 nav entry. dacli 端不能跑 vue compiler, 只能: * 1. 列目录 (fs.readdirSync) 找 .vue 文件 * 2. 提取 ` 段 const scriptMatch = code.match(/]*>([\s\S]*?)<\/script>/) if (!scriptMatch) return null const { name, dataKeys, hasData } = parseVueScript(scriptMatch[1]) const result: ComponentDefaults = { prop, name, filePath, hasData, dataKeys, isOptionConfig: true } componentFileCache.set(prop, result) return result } catch (err) { console.warn(`[datascreen] getComponentDefaults(${prop}) 解析失败:`, err) return null } } /** 列出 option/components/ 下所有 prop 名 (e.g. ['audio', 'bar', 'borderBox', ...]) */ export function listComponentProps(): string[] { return listComponentFiles() } /** * v0.15+ (P1-4, 2026-07-02): 镜像 web 端 build.vue:1040-1042 validProp 真值源 * * 镜像源: jnpf-web-datascreen-vue3/src/option/config.js:268 dicOption.dataList * - 30 hardcoded props (含 code/imgList/imgTabs/rectangle 等 components/*.vue 目录里没有的) * - + website.componentsList.filter(ele => ele.data === true).map(ele => ele.name) * * 旧版 listComponentProps() 走 option/components/*.vue 目录扫描, 漏 code/imgList/imgTabs/rectangle * → 误报 "prop=code 不在 36 个有效列表里", 但 web 设计器完全允许 * * 实现: 正则读 dicOption.dataList 数组字面量, 取 hardcoded 部分 (website.componentsList 需要登录态) * * @returns 30 个硬编码 valid props */ export function getValidProps(): string[] { if (!existsSync(DATASCREEN_OPTION_CONFIG_SRC)) { return listComponentFiles() // 兜底走旧逻辑 } try { const code = readFileSync(DATASCREEN_OPTION_CONFIG_SRC, 'utf-8') // 找 dicOption.dataList 数组字面量 // 匹配: dataList: ['xxx', 'yyy', ...].concat(...) const m = code.match(/dataList:\s*\[([^\]]+)\]/) if (!m) return listComponentFiles() // 提取 hardcoded 部分 ('xxx' 形式), 跳过后续 .concat(...) const arr = m[1] const props: string[] = [] const re = /'([^']+)'/g let mm: RegExpExecArray | null while ((mm = re.exec(arr)) !== null) { props.push(mm[1]) } // 去重 return Array.from(new Set(props)) } catch { return listComponentFiles() } } // ===================================================================== // Phase 3: 镜像 save 数据结构 (header.vue:200-211) → constructConfigDetail + constructComponentJson // 详见 dacli/docs/cmd-review/v0.13-webapi-form-workflow-refactor.md §8.2.4 阶段 3 // // 镜像源: // - jnpf/前端/jnpf-web-datascreen-vue3/src/page/group/header.vue:200-211 (save 按钮 formdata) // const formdata = { // visual: { id, backgroundUrl }, // config: { id, visualId, detail: JSON.stringify(this.contain.config), // component: JSON.stringify(this.contain.nav) } // } // updateComponent(formdata) // POST /visual/update // - jnpf/前端/jnpf-web-datascreen-vue3/src/option/config.js (基础 config 对象) // - jnpf/前端/jnpf-web-datascreen-vue3/src/option/components/.vue (组件元数据) // ===================================================================== /** * 构造 save formdata 的 visual + config 段 (镜像 header.vue:200-211) * * 用途: dacli bigscreen construct 命令构造 save payload 时, 把 baseConfig + nav 数组包装成 * web 端 updateComponent 期望的 formdata 结构. updateComponent = /api/visual/update. * * 参数: * - baseConfig: 来自 getBaseConfig() 的基础 config 对象 (可被用户字段覆盖) * - nav: 来自 constructComponentJson() 的组件列表数组 * - visualId: 已有大屏的 visual.id (新建时传 undefined) * * 返回: * { * visual: { id?, backgroundUrl }, * config: { visualId?, detail: JSON string, component: JSON string } * } * * 注: * - 镜像 web 端: config.id 不需要, 后端用 visualId 关联 visual + config 两表 * - backgroundUrl 在新建时是空字符串, 后续上传缩略图后才有 */ export function constructConfigDetail( baseConfig: Record, nav: Array>, options: { visualId?: string; backgroundUrl?: string } = {}, ): { visual: Record; config: Record } { const visual: Record = {} if (options.visualId) visual.id = options.visualId if (options.backgroundUrl !== undefined) visual.backgroundUrl = options.backgroundUrl const config: Record = { detail: JSON.stringify(baseConfig), component: JSON.stringify(nav), } if (options.visualId) config.visualId = options.visualId return { visual, config } } /** * 构造组件 nav 数组元素 (镜像 build.vue:705-709 + option/components/.vue) * * 镜像源: web 端 build.vue 的 nav 数组元素结构 * { index, name, display, lock, group, option, component: {prop}, data: {dataType, value, url, sql, ...}, children? } * * 参数 (c prop 来自 web 端 option/components/ 下的 36 个 .vue 文件): * - prop: 组件类型 ('bar'/'line'/'text'/'map'/'video'/'table'/'iframe'/...) * - x, y, w, h: 位置 + 尺寸 (默认 0/0/400/300) * - dataType: 0-7 镜像 build.vue:666-689 * 0=static(无), 1=api(有 url), 2=sql(有 sql), 3=ws(有 url), * 4=record(有 value), 5=public(有 url), 6=mqtt(有 url), 7=node * - value: static/record 类型数据值 * - url: api/ws/public/mqtt 类型 URL * - sql: sql 类型 SQL 语句 * - children: 文件夹/轮播子组件 (isFolder 判断) * * 返回: nav 数组元素, 含 index/name/display/lock/group/option/component/data/children * * 注: * - index 用全局自增 id (web 端 build.vue 用 Date.now() 派生), 简单用时间戳 + 位置 * - option 用 getComponentDefaults() 拿 data() 第一层 key 作为 option 默认 shape * (简化: 不深拷 data 体, 假设 option 字段列表够渲染配置面板用) * - isFolder 镜像 build.vue:690-692: activeObj.children 存在即为文件夹 (轮播) */ export interface NavEntryInput { prop: string x?: number y?: number w?: number h?: number dataType?: number value?: string | number url?: string sql?: string /** 嵌套子组件 (文件夹/轮播) */ children?: NavEntryInput[] /** web 端 index 字段, 缺省时用 Date.now() + random 派生 */ index?: number } export interface NavEntry { index: number name: string display: boolean lock: boolean group: number option: Record component: Record data: { dataType: number value?: string | number url?: string sql?: string [key: string]: unknown } children?: NavEntry[] } let _navIndexSeed = Date.now() & 0xffffff export function constructComponentJson(components: NavEntryInput[]): NavEntry[] { return components.map((c, i) => { const idx = c.index !== undefined ? c.index : (_navIndexSeed = (_navIndexSeed + 1) & 0xffffff) const navEntry: NavEntry = { index: idx, name: c.prop, display: true, lock: false, group: 0, option: getComponentDefaults(c.prop) ? (getComponentDefaults(c.prop) as unknown as Record) : {}, component: { prop: c.prop, x: c.x ?? 0, y: c.y ?? i * 320, // 简单纵向堆叠, 避免组件重叠 w: c.w ?? 400, h: c.h ?? 300, }, data: { dataType: c.dataType ?? 0, ...(c.value !== undefined ? { value: c.value } : {}), ...(c.url !== undefined ? { url: c.url } : {}), ...(c.sql !== undefined ? { sql: c.sql } : {}), }, } if (c.children && c.children.length > 0) { navEntry.children = constructComponentJson(c.children) } return navEntry }) }