@realnation/content-config 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -90,6 +90,24 @@ export default {
90
90
  minimum、maximum、minLength、maxLength、pattern、anyOf、format,另加 $schema、title、description、x-label。
91
91
  用到别的会被当成问题报出来。
92
92
 
93
+ ## 画布说明 canvas-config.json(0.5.0 起,体验端)
94
+
95
+ 给 AI 摆元件、改属性用(待办 #80):说明模块放到 UI Editor 画布上的元件是什么、模块真读哪些属性、两档默认版面、什么配置下才出现、摆放约束。
96
+ 体验端仓写 `src/canvas-config.ts`(默认导出 `CanvasConfigSpec`,类型在 `@realnation/content-config/canvas`),vite.config 加:
97
+
98
+ ```ts
99
+ import { canvasConfig } from '@realnation/content-config/canvas';
100
+ // plugins: [..., pageEventsPlugin(), canvasConfig()]
101
+ ```
102
+
103
+ 构建时检查并写 `assets/canvas-config.json`(与 `page-events.js` 同目录),不过关构建失败。规矩:
104
+
105
+ - 键是 componentName。`kind: 'system'` 是登记在 editor_tabs.components 的;`kind: 'pushed'` 是 page-data 推的,要写 `key`、`type`、英文 `appearsWhen`,可选机器可读的 `when`(`{ 内容配置读回的请求体里的路径: 值 }`,如 `{ 'design.wheelCount': 2 }`)。
106
+ - 面板项的类型、默认值、选项、范围不写,以后台登记的 collocation 为准;`properties` 只写模块真读的属性的英文说明(宿主统一套在外框上的位置、大小、颜色、字体不列),`ignores` 列面板上有、模块不读的。
107
+ - `layout`、`layoutVariants`、`key` 都从模块代码 import 同一份常量(如 placeholders.ts),不抄数字。`layout` 0.6.0 起可选:位置写在模块代码里的(模块自己会挪元件)才写;只登记在平台(collocation 的 values)的不写,默认位置以登记为准,不抄一份进来。推送元件的 key、componentName 与 `module` 要在构建用到的源码里原样找得到(另加 `src/page-events.ts`),对不上构建失败。
108
+ - `constraints` 只写模块自己的摆放规矩:`aspect`、`minWidth`、`minHeight`、`anchorsTo`(压在谁的正中)、`overlapAllowed`、`face`(盒子里真正画东西的是贴着远离某条边的正方形,如转盘的圆,`anchorsTo` 对准它的中心,`aspect` 在那条边为左右时宽高对调)。不出屏、不压角标这类平台规矩不写在这里。
109
+ - 说明文字一律英文。完整样例:体验仓 qiksense-lottery-spin-and-win-experience 的 `src/canvas-config.ts`。
110
+
93
111
  ## 其他用法
94
112
 
95
113
  - `import { validate } from '@realnation/content-config/validate'`:返回问题清单,空数组 = 通过(skill 读到说明后用它校验要提交的请求体)。
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@realnation/content-config",
3
- "version": "0.4.0",
4
- "description": "qiksense 模块内容配置的机器可读说明:构建时导出 content-config.json,并用字段说明校验默认请求体",
3
+ "version": "0.6.0",
4
+ "description": "qiksense 模块内容配置的机器可读说明:构建时导出 content-config.json,并用字段说明校验默认请求体;0.5.0 起另导出画布说明 canvas-config.json(体验端)",
5
5
  "type": "module",
6
6
  "exports": {
7
7
  ".": {
@@ -15,6 +15,10 @@
15
15
  "./exits": {
16
16
  "types": "./src/exits.d.ts",
17
17
  "import": "./src/exits.mjs"
18
+ },
19
+ "./canvas": {
20
+ "types": "./src/canvas.d.ts",
21
+ "import": "./src/canvas.mjs"
18
22
  }
19
23
  },
20
24
  "files": [
@@ -0,0 +1,76 @@
1
+ import type { Plugin } from 'vite';
2
+
3
+ /** 一档版面(设计坐标:竖屏 360×640、横屏 640×360) */
4
+ export interface CanvasBox {
5
+ 'x-position': number;
6
+ 'y-position': number;
7
+ width: number;
8
+ height: number;
9
+ }
10
+
11
+ /** 推送条件:{ 内容配置请求体里的路径: 值 },全部相等才成立,写法同 dynamicExits 的 when */
12
+ export type CanvasWhen = Record<string, string | number | boolean | null>;
13
+
14
+ export interface CanvasElement {
15
+ /** system:登记在 editor_tabs.components,新建节点就有,不能删、不能复制;pushed:page-data 推出来的,编号 display-<tab>-<key> */
16
+ kind: 'system' | 'pushed';
17
+ /** pushed 必填:page-data 里的 key,引用代码里的常量 */
18
+ key?: string;
19
+ /** 所在页签 id */
20
+ tab: string;
21
+ /** pushed 必填:page-data 里的 type(平台拼写 compnent) */
22
+ type?: 'compnent' | 'image' | 'image-ratio-clip' | 'text' | 'video' | 'button';
23
+ /** 英文,给 AI:访客看到什么、模块拿它做什么、运营通常怎么改 */
24
+ description: string;
25
+ /** pushed 必填,英文:什么配置下才推 */
26
+ appearsWhen?: string;
27
+ /** 机器可读的推送条件(可选) */
28
+ when?: CanvasWhen;
29
+ /** 两档默认版面:系统元件写出厂画布的位置,推送元件引用 propertyByRatio 的同一份常量 */
30
+ /** 两档默认版面。位置写在模块代码里的才写(从同一份常量 import);只登记在平台的不写,以登记为准(0.6.0 起可选) */
31
+ layout?: { v: CanvasBox; h: CanvasBox };
32
+ /** 模块按配置挪自己元件时的版面(共用包 2.31 起 target: 'system',只在运营没动过时挪) */
33
+ layoutVariants?: Record<string, { when?: CanvasWhen; appearsWhen: string; v?: CanvasBox; h?: CanvasBox }>;
34
+ /** 推送元件新建时抄同页哪个元件的样式(共用包 2.32 起) */
35
+ styleFrom?: string;
36
+ /** 模块真读的画布属性 { uuid: { description } };宿主统一套在外框上的位置、大小、字号、颜色、字体不列。类型、范围、选项以 collocation 为准 */
37
+ properties: Record<string, { description: string }>;
38
+ /** 面板上有、模块不读的属性,让 AI 别白改 */
39
+ ignores?: string[];
40
+ /** 图片、视频型:素材从哪来、比例锁 */
41
+ assets?: { source: 'from config' | 'operator' | 'none'; ratioSize?: string; description: string };
42
+ /** 模块自己的摆放规矩;不出屏、不压角标这类平台规矩不写在这里 */
43
+ constraints?: {
44
+ /** 宽:高。写了 face.awayFrom 的,按那条边在上下时写;在左右时盒子横放,读取方把宽高对调 */
45
+ aspect?: string;
46
+ minWidth?: number;
47
+ minHeight?: number;
48
+ anchorsTo?: { element: string; at: 'center' | 'top' | 'bottom' | 'left' | 'right' };
49
+ overlapAllowed?: string[];
50
+ /** 盒子里真正画东西的是一个正方形(如转盘的圆),贴着远离 awayFrom 属性所指那条边的一端;anchorsTo 指向它时对准正方形中心 */
51
+ face?: { shape: 'square'; awayFrom?: string };
52
+ };
53
+ }
54
+
55
+ /** 体验端 src/canvas-config.ts 默认导出的形状 */
56
+ export interface CanvasConfigSpec {
57
+ /** 与 page-data 的 detail.type 同一个字 */
58
+ module: string;
59
+ /** 键 = componentName */
60
+ elements: Record<string, CanvasElement>;
61
+ /** 可选:页签 id → 英文说明 */
62
+ pages?: Record<string, { description: string }>;
63
+ }
64
+
65
+ /** 构建产物 canvas-config.json 的形状 */
66
+ export interface CanvasConfigFile extends CanvasConfigSpec {
67
+ format: 1;
68
+ }
69
+
70
+ export declare const CANVAS_FORMAT: 1;
71
+ export declare function validateCanvasConfig(spec: unknown): string[];
72
+ export declare function checkCanvasNames(spec: CanvasConfigSpec, root: string, options?: { files?: string[]; exclude?: string[] }): string[];
73
+ export declare function canvasConfigDoc(spec: CanvasConfigSpec): CanvasConfigFile;
74
+ export declare function buildCanvasConfig(root: string, entry?: string, options?: { files?: string[] }): Promise<CanvasConfigFile>;
75
+ export declare function canvasConfig(options?: { entry?: string; fileName?: string; extraFiles?: string[] }): Plugin;
76
+ export default canvasConfig;
package/src/canvas.mjs ADDED
@@ -0,0 +1,228 @@
1
+ // 画布说明 canvas-config.json(0.5.0 起,待办 #80,PF 2026-10-22 定乙、2026-11-12 定第七节五件事):
2
+ // 模块体验端说明自己放到 UI Editor 画布上的元件,给 AI 摆元件、改属性用。
3
+ // 一个模块一份,构建时由体验端的 src/canvas-config.ts 生成,放在 remoteEntry.js、page-events.js 同一目录。
4
+ //
5
+ // 只写后台登记(collocation)里没有的东西:英文说明、两档默认版面、什么配置下才出现、模块真读的属性、摆放约束。
6
+ // 面板项的类型、默认值、选项、范围以 collocation 为准,这里不重复(PF 2026-11-12「31 甲」)。
7
+ // 推送条件写英文 appearsWhen,另可选填机器能读的 when(「32 乙」),写法同 dynamicExits 的 when:
8
+ // { 内容配置请求体里的路径: 值 },路径是读回的整份请求体(如 Spin and Win 的 design.wheelCount)。
9
+
10
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
11
+ import { join, resolve, sep } from 'node:path'
12
+ import { pathToFileURL } from 'node:url'
13
+ import { stripScriptComments } from './labels.mjs'
14
+
15
+ export const CANVAS_FORMAT = 1
16
+
17
+ const KINDS = new Set(['system', 'pushed'])
18
+ // page-data 里的 type(平台拼写 compnent,别「修正」)
19
+ const PUSHED_TYPES = new Set(['compnent', 'image', 'image-ratio-clip', 'text', 'video', 'button'])
20
+ const ELEMENT_KEYS = new Set(['kind', 'key', 'tab', 'type', 'description', 'appearsWhen', 'when', 'layout', 'layoutVariants', 'styleFrom', 'properties', 'ignores', 'assets', 'constraints'])
21
+ const BOX_KEYS = ['x-position', 'y-position', 'width', 'height']
22
+ const ASSET_SOURCES = new Set(['from config', 'operator', 'none'])
23
+ const ANCHOR_AT = new Set(['center', 'top', 'bottom', 'left', 'right'])
24
+ const CONSTRAINT_KEYS = new Set(['aspect', 'minWidth', 'minHeight', 'anchorsTo', 'overlapAllowed', 'face'])
25
+ // 说明给 AI 看,一律英文:出现中日韩文字就算没写成英文
26
+ const CJK = /[ -〿㐀-鿿＀-￯]/
27
+
28
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v)
29
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v)
30
+ const isText = (v) => typeof v === 'string' && v.trim().length > 0
31
+
32
+ function english(errors, where, v) {
33
+ if (!isText(v)) errors.push(`${where}:要写一句英文`)
34
+ else if (CJK.test(v)) errors.push(`${where}:要写英文(给 AI 看),现在有中文`)
35
+ }
36
+
37
+ function checkWhen(errors, where, when) {
38
+ if (!isObj(when) || !Object.keys(when).length) return errors.push(`${where}:写成 { "请求体里的路径": 值 },至少一条`)
39
+ for (const [k, v] of Object.entries(when)) {
40
+ if (!/^[A-Za-z_$][\w$]*(\.[\w$]+)*$/.test(k)) errors.push(`${where}:路径 ${k} 要用点号分隔的字段名`)
41
+ if (v !== null && !['string', 'number', 'boolean'].includes(typeof v)) errors.push(`${where}.${k}:值只能是字符串、数字、布尔或 null`)
42
+ }
43
+ }
44
+
45
+ function checkBox(errors, where, box) {
46
+ if (!isObj(box)) return errors.push(`${where}:要写 { x-position, y-position, width, height }`)
47
+ for (const k of BOX_KEYS) if (!isNum(box[k])) errors.push(`${where}.${k}:要是数字`)
48
+ for (const k of Object.keys(box)) if (!BOX_KEYS.includes(k)) errors.push(`${where}:不认识的键 ${k}(只写位置与大小)`)
49
+ if (isNum(box.width) && box.width <= 0) errors.push(`${where}.width:要大于 0`)
50
+ if (isNum(box.height) && box.height <= 0) errors.push(`${where}.height:要大于 0`)
51
+ }
52
+
53
+ function checkLayout(errors, where, layout, { partial = false } = {}) {
54
+ for (const o of ['v', 'h']) {
55
+ if (layout[o] === undefined && partial) continue
56
+ checkBox(errors, `${where}.${o}`, layout[o])
57
+ }
58
+ }
59
+
60
+ // 检查一份画布说明(src/canvas-config.ts 的默认导出,或产物 canvas-config.json 去掉 format 的部分)。返回问题清单,空数组为通过
61
+ export function validateCanvasConfig(spec) {
62
+ const errors = []
63
+ if (!isObj(spec)) return ['画布说明要是一个对象 { module, elements, pages? }']
64
+ for (const k of Object.keys(spec)) if (!['format', 'module', 'elements', 'pages'].includes(k)) errors.push(`不认识的顶层键 ${k}`)
65
+ if (!isText(spec.module)) errors.push('module:写模块推送里 page-data 的 detail.type(如 spin-and-win)')
66
+ if (!isObj(spec.elements) || !Object.keys(spec.elements).length) {
67
+ errors.push('elements:至少写一个元件,键是 componentName')
68
+ return errors
69
+ }
70
+ const names = new Set(Object.keys(spec.elements))
71
+ const tabs = new Set()
72
+ for (const [name, el] of Object.entries(spec.elements)) {
73
+ const w = `elements.${name}`
74
+ if (!isObj(el)) { errors.push(`${w}:要是一个对象`); continue }
75
+ for (const k of Object.keys(el)) if (!ELEMENT_KEYS.has(k)) errors.push(`${w}:不认识的键 ${k}`)
76
+ if (!KINDS.has(el.kind)) errors.push(`${w}.kind:写 system(登记在 editor_tabs.components)或 pushed(page-data 推出来的)`)
77
+ if (!isText(el.tab)) errors.push(`${w}.tab:写所在页签 id(如 Main)`)
78
+ else tabs.add(el.tab)
79
+ english(errors, `${w}.description`, el.description)
80
+ if (el.kind === 'pushed') {
81
+ if (!isText(el.key)) errors.push(`${w}.key:推送元件要写 page-data 里的 key`)
82
+ if (!PUSHED_TYPES.has(el.type)) errors.push(`${w}.type:推送元件要写 page-data 里的 type(${[...PUSHED_TYPES].join('、')})`)
83
+ english(errors, `${w}.appearsWhen`, el.appearsWhen)
84
+ } else if (el.kind === 'system') {
85
+ if (el.key !== undefined) errors.push(`${w}.key:系统元件没有 key`)
86
+ if (el.type !== undefined && el.type !== 'compnent') errors.push(`${w}.type:系统元件固定是 compnent,可不写`)
87
+ if (el.appearsWhen !== undefined || el.when !== undefined) errors.push(`${w}:系统元件新建节点就有,不写 appearsWhen、when`)
88
+ }
89
+ if (el.when !== undefined) checkWhen(errors, `${w}.when`, el.when)
90
+ // 0.6.0 起可选:位置写在模块代码里的(模块自己挪元件,如 Spin and Win)照写;只登记在平台的不写,以登记为准
91
+ if (el.layout !== undefined) {
92
+ if (!isObj(el.layout)) errors.push(`${w}.layout:写两档默认版面 { v: {…}, h: {…} },位置只登记在平台的就不写`)
93
+ else checkLayout(errors, `${w}.layout`, el.layout)
94
+ }
95
+ if (el.layoutVariants !== undefined) {
96
+ if (!isObj(el.layoutVariants)) errors.push(`${w}.layoutVariants:写 { 变体名: { when, appearsWhen, v, h } }`)
97
+ else for (const [vn, v] of Object.entries(el.layoutVariants)) {
98
+ const vw = `${w}.layoutVariants.${vn}`
99
+ if (!isObj(v)) { errors.push(`${vw}:要是一个对象`); continue }
100
+ for (const k of Object.keys(v)) if (!['when', 'appearsWhen', 'v', 'h'].includes(k)) errors.push(`${vw}:不认识的键 ${k}`)
101
+ english(errors, `${vw}.appearsWhen`, v.appearsWhen)
102
+ if (v.when !== undefined) checkWhen(errors, `${vw}.when`, v.when)
103
+ if (v.v === undefined && v.h === undefined) errors.push(`${vw}:v、h 至少写一档`)
104
+ checkLayout(errors, vw, v, { partial: true })
105
+ }
106
+ }
107
+ if (el.styleFrom !== undefined && !names.has(el.styleFrom)) errors.push(`${w}.styleFrom:${el.styleFrom} 不是本模块的元件`)
108
+ if (!isObj(el.properties)) errors.push(`${w}.properties:写模块真读的画布属性 { uuid: { description } },一个都不读写 {}`)
109
+ else for (const [uuid, p] of Object.entries(el.properties)) {
110
+ if (!isObj(p)) { errors.push(`${w}.properties.${uuid}:写 { description }`); continue }
111
+ for (const k of Object.keys(p)) if (k !== 'description') errors.push(`${w}.properties.${uuid}:只写 description(类型、范围、选项以后台登记的 collocation 为准)`)
112
+ english(errors, `${w}.properties.${uuid}.description`, p.description)
113
+ }
114
+ if (el.ignores !== undefined) {
115
+ if (!Array.isArray(el.ignores) || !el.ignores.every(isText)) errors.push(`${w}.ignores:写属性 uuid 的数组`)
116
+ else for (const u of el.ignores) if (isObj(el.properties) && u in el.properties) errors.push(`${w}.ignores:${u} 同时写在 properties 里`)
117
+ }
118
+ if (el.assets !== undefined) {
119
+ const a = el.assets
120
+ if (!isObj(a)) errors.push(`${w}.assets:写 { source, ratioSize?, description }`)
121
+ else {
122
+ for (const k of Object.keys(a)) if (!['source', 'ratioSize', 'description'].includes(k)) errors.push(`${w}.assets:不认识的键 ${k}`)
123
+ if (!ASSET_SOURCES.has(a.source)) errors.push(`${w}.assets.source:写 ${[...ASSET_SOURCES].join('、')} 之一`)
124
+ if (a.ratioSize !== undefined && !/^\d+(\.\d+)?:\d+(\.\d+)?$/.test(a.ratioSize)) errors.push(`${w}.assets.ratioSize:写成 "宽:高"`)
125
+ english(errors, `${w}.assets.description`, a.description)
126
+ }
127
+ }
128
+ if (el.constraints !== undefined) {
129
+ const c = el.constraints
130
+ if (!isObj(c)) { errors.push(`${w}.constraints:要是一个对象`); continue }
131
+ for (const k of Object.keys(c)) if (!CONSTRAINT_KEYS.has(k)) errors.push(`${w}.constraints:不认识的键 ${k}(平台规矩不写在这里)`)
132
+ if (c.aspect !== undefined && !/^\d+(\.\d+)?:\d+(\.\d+)?$/.test(c.aspect)) errors.push(`${w}.constraints.aspect:写成 "宽:高"`)
133
+ for (const k of ['minWidth', 'minHeight']) if (c[k] !== undefined && !(isNum(c[k]) && c[k] > 0)) errors.push(`${w}.constraints.${k}:要是正数`)
134
+ if (c.anchorsTo !== undefined) {
135
+ if (!isObj(c.anchorsTo) || !names.has(c.anchorsTo.element) || c.anchorsTo.element === name) errors.push(`${w}.constraints.anchorsTo.element:要是本模块的另一个元件`)
136
+ if (!ANCHOR_AT.has(c.anchorsTo?.at)) errors.push(`${w}.constraints.anchorsTo.at:写 ${[...ANCHOR_AT].join('、')} 之一`)
137
+ }
138
+ // face:盒子里真正画东西的是一个正方形(转盘的圆),贴着远离某条边的一端放;那条边由一个属性给(top / right / bottom / left)。
139
+ // anchorsTo 指向它的元件对准的是这个正方形的中心,不是盒子中心
140
+ if (c.face !== undefined) {
141
+ if (!isObj(c.face) || c.face.shape !== 'square') errors.push(`${w}.constraints.face:写 { shape: 'square', awayFrom: '<属性 uuid>' }`)
142
+ else if (c.face.awayFrom !== undefined && !(isObj(el.properties) && c.face.awayFrom in el.properties)) errors.push(`${w}.constraints.face.awayFrom:${c.face.awayFrom} 要是 properties 里的属性(值为 top、right、bottom、left)`)
143
+ for (const k of Object.keys(c.face ?? {})) if (!['shape', 'awayFrom'].includes(k)) errors.push(`${w}.constraints.face:不认识的键 ${k}`)
144
+ }
145
+ if (c.overlapAllowed !== undefined) {
146
+ if (!Array.isArray(c.overlapAllowed)) errors.push(`${w}.constraints.overlapAllowed:写元件名的数组`)
147
+ else for (const o of c.overlapAllowed) if (!names.has(o) || o === name) errors.push(`${w}.constraints.overlapAllowed:${o} 不是本模块的另一个元件`)
148
+ }
149
+ }
150
+ }
151
+ if (spec.pages !== undefined) {
152
+ if (!isObj(spec.pages)) errors.push('pages:写 { 页签 id: { description } }')
153
+ else for (const [tab, p] of Object.entries(spec.pages)) {
154
+ if (!isObj(p)) { errors.push(`pages.${tab}:写 { description }`); continue }
155
+ for (const k of Object.keys(p)) if (k !== 'description') errors.push(`pages.${tab}:只写 description`)
156
+ english(errors, `pages.${tab}.description`, p.description)
157
+ }
158
+ }
159
+ return errors
160
+ }
161
+
162
+ // 推送元件的 key 与 componentName、本模块的 module 名都要在构建用到的源码里(去掉注释后)原样出现过,
163
+ // 防止推送改了名字说明没跟上。说明文件本身不算
164
+ export function checkCanvasNames(spec, root, { files = [], exclude = [] } = {}) {
165
+ const src = resolve(root, 'src') + sep
166
+ const skip = new Set(exclude.map((e) => resolve(root, e)))
167
+ const texts = files
168
+ .map((f) => resolve(f))
169
+ .filter((f) => f.startsWith(src) && !skip.has(f) && /\.(vue|ts|tsx|js|jsx|mjs)$/.test(f))
170
+ .map((f) => { try { return stripScriptComments(readFileSync(f, 'utf8')) } catch { return '' } })
171
+ const all = texts.join('\n')
172
+ const has = (s) => all.includes(`'${s}'`) || all.includes(`"${s}"`) || all.includes(`\`${s}\``)
173
+ const missing = []
174
+ if (isText(spec.module) && !has(spec.module)) missing.push(`module ${spec.module} 在源码里找不到(应与 page-data 的 detail.type 同一个字)`)
175
+ for (const [name, el] of Object.entries(spec.elements ?? {})) {
176
+ if (el?.kind !== 'pushed') continue
177
+ if (!has(name)) missing.push(`elements.${name}:推送元件的 componentName 在源码里找不到`)
178
+ if (isText(el.key) && !has(el.key)) missing.push(`elements.${name}.key:${el.key} 在源码里找不到`)
179
+ }
180
+ return missing
181
+ }
182
+
183
+ // 产物:format 在最前,键的顺序照源文件
184
+ export function canvasConfigDoc(spec) {
185
+ const doc = { format: CANVAS_FORMAT, module: spec.module, elements: spec.elements }
186
+ if (spec.pages !== undefined) doc.pages = spec.pages
187
+ return JSON.parse(JSON.stringify(doc))
188
+ }
189
+
190
+ async function loadSpecFile(root, entry) {
191
+ let build
192
+ try { ({ build } = await import('esbuild')) } catch { throw new Error('canvas-config:构建时要用 esbuild 加载 src/canvas-config.ts(vite 自带)。这个项目里找不到它,请 npm install -D esbuild') }
193
+ const dir = join(root, 'node_modules', '.content-config')
194
+ mkdirSync(dir, { recursive: true })
195
+ const out = join(dir, `canvas-${process.pid}-${Date.now()}.mjs`)
196
+ const result = await build({ entryPoints: [resolve(root, entry)], bundle: true, format: 'esm', platform: 'node', packages: 'external', write: false, logLevel: 'silent', alias: { '@': resolve(root, 'src') } })
197
+ writeFileSync(out, result.outputFiles[0].text)
198
+ try { return (await import(pathToFileURL(out).href)).default } finally { rmSync(out, { force: true }) }
199
+ }
200
+
201
+ // 读出说明、检查、核对名字,返回要写进 canvas-config.json 的内容;不合规时抛错,逐条列出
202
+ export async function buildCanvasConfig(root, entry = 'src/canvas-config.ts', { files } = {}) {
203
+ const spec = await loadSpecFile(root, entry)
204
+ const errors = validateCanvasConfig(spec)
205
+ if (!errors.length && files) errors.push(...checkCanvasNames(spec, root, { files, exclude: [entry] }))
206
+ if (errors.length) throw new Error(`canvas-config:画布说明没通过检查(${errors.length} 处)\n ${errors.join('\n ')}`)
207
+ return canvasConfigDoc(spec)
208
+ }
209
+
210
+ // vite 插件:体验端 vite.config 里加 canvasConfig(),构建时生成 assets/canvas-config.json(与 page-events.js 同目录)
211
+ export function canvasConfig({ entry = 'src/canvas-config.ts', fileName = 'assets/canvas-config.json', extraFiles = ['src/page-events.ts'] } = {}) {
212
+ let root = process.cwd()
213
+ return {
214
+ name: 'realnation-canvas-config',
215
+ apply: 'build',
216
+ configResolved(config) { root = config.root },
217
+ async generateBundle() {
218
+ // 构建用到的源码,加上只在推送清单(page-events.ts,另打的包)里用到的源码
219
+ const used = [...this.getModuleIds()].filter((id) => !id.startsWith('\0')).map((id) => id.split('?')[0])
220
+ const files = [...used, ...extraFiles.map((f) => resolve(root, f))]
221
+ let doc
222
+ try { doc = await buildCanvasConfig(root, entry, { files }) } catch (e) { this.error(e.message) }
223
+ this.emitFile({ type: 'asset', fileName, source: JSON.stringify(doc, null, 2) + '\n' })
224
+ }
225
+ }
226
+ }
227
+
228
+ export default canvasConfig