@realnation/content-config 0.3.0 → 0.4.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
@@ -34,6 +34,37 @@ AI 与团队建活动 skill 的读法:先从模块目录接口 `GET /partner/p
34
34
  } satisfies ContentConfigSpec;
35
35
  ```
36
36
 
37
+ ## 动态出口(0.4.0 起)
38
+
39
+ 有的模块的出口不在模块目录里,而是配置页按内容配置算出来、保存时经宿主 `setAccessDynamicPorts` 推给 Builder 的
40
+ (Dial Pad 每个号码一个,Access Time / Access Device 每个放行规则组一个,Access URL 首次、再次、用完)。
41
+ 这类模块在说明里再导出 `dynamicExits`:用数据把配置页那段算法原样写出来,建活动 skill 拿保存后读回的请求体照着算出同样的出口,
42
+ 补进节点并接线,不执行模块代码,也不用打开配置页。出口全在模块目录里的模块不写。
43
+
44
+ ```ts
45
+ export default {
46
+ endpoint: 'common',
47
+ defaultBody: () => ({ configId: 0, detail: createEmptyDetail() }),
48
+ schema: { /* ... */ },
49
+ dynamicExits: [
50
+ // 列表里每一项一个出口:each 是请求体里列表的路径,where 里的字段都相等的项才算
51
+ { each: 'detail.numbers', id: '{key}', event: `${DIAL_EVENT_PREFIX}{key}`, name: ['{exitName}', '{number}'] },
52
+ // 固定出口:when 里的路径都等于给的值才有
53
+ { id: 'exhausted', event: 'access_url_exhausted', name: 'Exhausted', when: { 'detail.exhaustedAllow': true } }
54
+ ]
55
+ } satisfies ContentConfigSpec;
56
+ ```
57
+
58
+ - `id`、`event`、`name` 是模板:`{字段}` 换成这一项的字段值(去掉首尾空白),`{index}` 是这一项在整个列表里的序号,
59
+ `{n}` 是在通过 `where` 的项里的序号(都从 1 起)。有一处换成空串整个模板就算空;`name` 给数组时取第一个不空的。
60
+ 固定出口的模板只能写原文。
61
+ - 出口的顺序、id、事件名、名字都要和配置页推给宿主的那一份**一模一样**:照配置页的代码写,事件名前缀引用代码里的同一个常量。
62
+ id 为空、事件名为空、id 重复的会被跳过,与 Builder 收到出口时的做法相同。
63
+ - 构建时核对:路径与字段在字段说明里找得到、固定出口没用字段、拿出厂请求体算出的出口 id 里没有横杠
64
+ (连线的键按「源-模块-端口-目标」用横杠拆,有横杠会拆错)。不过关构建就失败。
65
+ - 出口规则算法在 `@realnation/content-config/exits`(`computeExits`、`checkExitRules`),模块构建与建活动 skill 用同一份。
66
+ - 产物 `content-config.json` 多一个可选的 `dynamicExits` 键,`format` 仍是 1:读取方不认识就当没有。
67
+
37
68
  ## 写字段说明的规矩
38
69
 
39
70
  - **默认值与范围引用代码里的同一份常量**(默认值函数、LIMITS、枚举表),不照抄数字;改代码说明自动跟上。
@@ -67,4 +98,5 @@ AI 与团队建活动 skill 的读法:先从模块目录接口 `GET /partner/p
67
98
 
68
99
  ## 发版
69
100
 
70
- `npm publish`(在本目录;账号要两步验证,由 PF 在自己的终端里发)。改了产物格式就把 `FORMAT` 加一,并同步改读取方。
101
+ `npm publish`(在本目录;账号要两步验证,由 PF 在自己的终端里发)。改了产物格式就把 `FORMAT` 加一,并同步改读取方;
102
+ 只加读取方可以不认识的可选键(如 0.4.0 的 `dynamicExits`)不算改格式。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@realnation/content-config",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "qiksense 模块内容配置的机器可读说明:构建时导出 content-config.json,并用字段说明校验默认请求体",
5
5
  "type": "module",
6
6
  "exports": {
@@ -11,6 +11,10 @@
11
11
  "./validate": {
12
12
  "types": "./src/validate.d.ts",
13
13
  "import": "./src/validate.mjs"
14
+ },
15
+ "./exits": {
16
+ "types": "./src/exits.d.ts",
17
+ "import": "./src/exits.mjs"
14
18
  }
15
19
  },
16
20
  "files": [
package/src/exits.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { JsonSchema } from './validate';
2
+
3
+ type Scalar = string | number | boolean | null;
4
+
5
+ /** 固定出口:when 里的路径(点号分隔,从请求体算起)都等于给的值才有这个出口;模板只能写原文 */
6
+ export interface FixedExitRule {
7
+ id: string;
8
+ event: string;
9
+ name: string | readonly string[];
10
+ when?: Record<string, Scalar>;
11
+ }
12
+
13
+ /**
14
+ * 列表里每一项一个出口。each 是请求体里列表的路径(如 'detail.numbers'),where 里的字段都相等的项才算。
15
+ * id、event、name 是模板:{字段} 换成这一项的字段值(去掉首尾空白),{index} 是在整个列表里的序号,{n} 是在通过 where 的项里的序号(从 1 起);
16
+ * 有一处换成空串整个模板就算空,name 给数组时取第一个不空的。
17
+ */
18
+ export interface EachExitRule {
19
+ each: string;
20
+ where?: Record<string, Scalar>;
21
+ id: string;
22
+ event: string;
23
+ name: string | readonly string[];
24
+ }
25
+
26
+ export type DynamicExitRule = FixedExitRule | EachExitRule;
27
+
28
+ /** 算出来的一个出口,对应配置页推给宿主 setAccessDynamicPorts 的 { key, event, name } */
29
+ export interface DynamicExit {
30
+ id: string;
31
+ event: string;
32
+ name: string;
33
+ }
34
+
35
+ /** 按规则从(保存后读回的)请求体算出口;id 为空、event 为空、id 重复的跳过,与 Builder 相同 */
36
+ export declare function computeExits(rules: readonly DynamicExitRule[] | undefined, body: unknown): DynamicExit[];
37
+ /** 检查规则写法;给了字段说明与出厂请求体时再核对路径、字段与算出的出口 id。返回问题清单,空数组 = 通过 */
38
+ export declare function checkExitRules(rules: unknown, options?: { schema?: JsonSchema; body?: unknown }): string[];
package/src/exits.mjs ADDED
@@ -0,0 +1,129 @@
1
+ // 动态出口规则(0.4.0 起):有的模块的出口不是写死在模块目录里的,而是配置页按内容配置算出来、
2
+ // 保存时经宿主 setAccessDynamicPorts 推给 Builder 的(Dial Pad 每个号码一个、Access Time 每个放行规则组一个……)。
3
+ // 模块在 content-config.ts 里用数据把同一套算法写出来(dynamicExits),建活动 skill 拿保存后读回的请求体照着算,
4
+ // 不执行模块代码,也就不用打开配置页。
5
+ //
6
+ // 一条规则是下面两种之一:
7
+ // { id, event, name, when? } 固定出口。when 是 { 请求体里的路径: 值 },这些路径上的值都等于给的值才有这个出口
8
+ // { each, where?, id, event, name } 列表里每一项一个出口。each 是请求体里列表的路径(点号分隔,如 detail.numbers);
9
+ // where 是 { 项里的字段: 值 },都相等的项才算
10
+ // id、event、name 都是模板:{字段} 换成这一项里那个字段的值(转成字符串、去掉首尾空白),{index} 是这一项在整个列表里的
11
+ // 序号,{n} 是它在通过 where 的项里的序号(都从 1 起)。固定出口的模板只能写原文。模板里只要有一处换成了空串,
12
+ // 整个模板就算空;name 可以给数组,按顺序取第一个不空的。
13
+ // 出口按规则的顺序、列表的顺序排;id 为空、event 为空、id 与前面重复的跳过(与 Builder 收到出口时的做法相同,
14
+ // qik-sense-partner src/views/flow-items/content-config.vue 的 normalizeAccessDynamicPorts)。
15
+
16
+ const PLACEHOLDER = /\{([^{}]+)\}/g
17
+ const RULE_KEYS = new Set(['each', 'where', 'when', 'id', 'event', 'name'])
18
+
19
+ function at(obj, path) {
20
+ let cur = obj
21
+ for (const seg of path.split('.')) {
22
+ if (cur === null || typeof cur !== 'object') return undefined
23
+ cur = cur[seg]
24
+ }
25
+ return cur
26
+ }
27
+
28
+ const matches = (obj, cond, get) => Object.entries(cond ?? {}).every(([k, v]) => get(obj, k) === v)
29
+
30
+ function fill(template, item, index, n) {
31
+ let empty = false
32
+ const out = template.replace(PLACEHOLDER, (_, field) => {
33
+ const v = field === 'index' ? index : field === 'n' ? n : item?.[field]
34
+ const s = v === undefined || v === null ? '' : String(v).trim()
35
+ if (!s) empty = true
36
+ return s
37
+ })
38
+ return empty ? '' : out.trim()
39
+ }
40
+
41
+ const firstFilled = (names, item, index, n) => {
42
+ for (const t of Array.isArray(names) ? names : [names]) {
43
+ const s = fill(t, item, index, n)
44
+ if (s) return s
45
+ }
46
+ return ''
47
+ }
48
+
49
+ // 按规则算出口:[{ id, event, name }],与配置页推给 Builder 的 key、event、name 一一对应
50
+ export function computeExits(rules, body) {
51
+ const out = []
52
+ const seen = new Set()
53
+ const push = (id, event, name) => {
54
+ if (!id || !event || seen.has(id)) return
55
+ seen.add(id)
56
+ out.push({ id, event, name: name || event })
57
+ }
58
+ for (const rule of rules ?? []) {
59
+ if (rule.each === undefined) {
60
+ if (matches(body, rule.when, at)) push(fill(rule.id), fill(rule.event), firstFilled(rule.name))
61
+ continue
62
+ }
63
+ const list = at(body, rule.each)
64
+ if (!Array.isArray(list)) continue
65
+ let n = 0
66
+ list.forEach((item, i) => {
67
+ if (!matches(item, rule.where, (o, k) => o?.[k])) return
68
+ n += 1
69
+ push(fill(rule.id, item, i + 1, n), fill(rule.event, item, i + 1, n), firstFilled(rule.name, item, i + 1, n))
70
+ })
71
+ }
72
+ return out
73
+ }
74
+
75
+ // 字段说明里某个路径(点号分隔)对应的子说明;走不下去时给 undefined
76
+ function schemaAt(schema, path) {
77
+ let cur = schema
78
+ for (const seg of path.split('.')) {
79
+ cur = cur?.properties?.[seg]
80
+ if (!cur) return undefined
81
+ }
82
+ return cur
83
+ }
84
+
85
+ // 检查规则的写法;给了字段说明与出厂请求体,再核对路径与字段都对得上、出厂请求体能算出合法的出口。返回问题清单
86
+ export function checkExitRules(rules, { schema, body } = {}) {
87
+ const errors = []
88
+ if (!Array.isArray(rules)) return ['dynamicExits 要写成数组']
89
+ rules.forEach((rule, i) => {
90
+ const at$ = `dynamicExits[${i}]`
91
+ if (!rule || typeof rule !== 'object' || Array.isArray(rule)) return errors.push(`${at$} 要写成对象`)
92
+ for (const k of Object.keys(rule)) if (!RULE_KEYS.has(k)) errors.push(`${at$} 有不认识的键 ${k}`)
93
+ const isEach = rule.each !== undefined
94
+ if (isEach && typeof rule.each !== 'string') errors.push(`${at$}.each 要写列表的路径(字符串)`)
95
+ if (isEach && rule.when !== undefined) errors.push(`${at$} 按列表出的出口用 where,不用 when`)
96
+ if (!isEach && rule.where !== undefined) errors.push(`${at$} 固定出口用 when,不用 where`)
97
+ for (const k of ['where', 'when']) {
98
+ const c = rule[k]
99
+ if (c === undefined) continue
100
+ if (!c || typeof c !== 'object' || Array.isArray(c)) { errors.push(`${at$}.${k} 要写成 { 字段: 值 }`); continue }
101
+ for (const [f, v] of Object.entries(c)) if (v !== null && typeof v === 'object') errors.push(`${at$}.${k}.${f} 的值只能是字符串、数字、布尔或 null`)
102
+ }
103
+ const names = Array.isArray(rule.name) ? rule.name : [rule.name]
104
+ const templates = [['id', rule.id], ['event', rule.event], ...names.map((t, j) => [Array.isArray(rule.name) ? `name[${j}]` : 'name', t])]
105
+ if (!names.length) errors.push(`${at$}.name 不能是空数组`)
106
+ for (const [k, t] of templates) {
107
+ if (typeof t !== 'string' || !t.trim()) { errors.push(`${at$}.${k} 要写成非空字符串`); continue }
108
+ const fields = [...t.matchAll(PLACEHOLDER)].map((m) => m[1])
109
+ if (!isEach && fields.length) errors.push(`${at$}.${k} 是固定出口,不能用 {${fields[0]}}`)
110
+ if (isEach && schema && typeof rule.each === 'string') {
111
+ const props = schemaAt(schema, rule.each)?.items?.properties
112
+ for (const f of fields) if (props && f !== 'index' && f !== 'n' && !props[f]) errors.push(`${at$}.${k} 里的 {${f}} 不是 ${rule.each} 列表项的字段`)
113
+ }
114
+ }
115
+ if (isEach && schema && typeof rule.each === 'string') {
116
+ const list = schemaAt(schema, rule.each)
117
+ if (!list) errors.push(`${at$}.each:字段说明里没有 ${rule.each}`)
118
+ else if (!list.items) errors.push(`${at$}.each:${rule.each} 在字段说明里不是列表`)
119
+ const props = list?.items?.properties
120
+ for (const f of Object.keys(rule.where ?? {})) if (props && !props[f]) errors.push(`${at$}.where 里的 ${f} 不是 ${rule.each} 列表项的字段`)
121
+ }
122
+ if (!isEach && schema) for (const p of Object.keys(rule.when ?? {})) if (!schemaAt(schema, p)) errors.push(`${at$}.when:字段说明里没有 ${p}`)
123
+ })
124
+ if (!errors.length && body !== undefined) {
125
+ // 连线的键按「源-模块-端口-目标」用横杠拆开(Builder 与后端都这样读),所以出口 id 里不能有横杠
126
+ for (const e of computeExits(rules, body)) if (e.id.includes('-')) errors.push(`出厂请求体算出的出口 id「${e.id}」里有横杠,连线的键会拆错`)
127
+ }
128
+ return errors
129
+ }
package/src/index.d.ts CHANGED
@@ -1,8 +1,11 @@
1
1
  import type { Plugin } from 'vite';
2
2
  import type { JsonSchema } from './validate';
3
+ import type { DynamicExitRule } from './exits';
3
4
 
4
5
  export type { JsonSchema } from './validate';
5
6
  export { validate, SUPPORTED_KEYWORDS } from './validate';
7
+ export type { DynamicExitRule, FixedExitRule, EachExitRule, DynamicExit } from './exits';
8
+ export { computeExits, checkExitRules } from './exits';
6
9
 
7
10
  /** 模块 src/content-config.ts 默认导出的形状 */
8
11
  export interface ContentConfigSpec<Body = unknown> {
@@ -12,6 +15,8 @@ export interface ContentConfigSpec<Body = unknown> {
12
15
  defaultBody: Body | (() => Body | Promise<Body>);
13
16
  /** 请求体的字段说明 */
14
17
  schema: JsonSchema;
18
+ /** 配置页按内容配置算出、保存时推给宿主 setAccessDynamicPorts 的出口,用数据写成的同一套算法(0.4.0 起);出口全在模块目录里的模块不写 */
19
+ dynamicExits?: readonly DynamicExitRule[];
15
20
  }
16
21
 
17
22
  /** 构建产物 content-config.json 的形状 */
@@ -20,6 +25,8 @@ export interface ContentConfigFile<Body = unknown> {
20
25
  endpoint: string;
21
26
  defaultBody: Body;
22
27
  schema: JsonSchema;
28
+ /** 模块写了 dynamicExits 才有 */
29
+ dynamicExits?: readonly DynamicExitRule[];
23
30
  }
24
31
 
25
32
  export interface ContentConfigPluginOptions {
package/src/index.mjs CHANGED
@@ -1,2 +1,3 @@
1
- export { default, buildContentConfig, loadSpec, checkLabels, collectLabels, FORMAT } from './vite-plugin.mjs'
2
- export { validate, SUPPORTED_KEYWORDS } from './validate.mjs'
1
+ export { default, buildContentConfig, loadSpec, checkLabels, collectLabels, FORMAT } from './vite-plugin.mjs'
2
+ export { validate, SUPPORTED_KEYWORDS } from './validate.mjs'
3
+ export { computeExits, checkExitRules } from './exits.mjs'
package/src/labels.mjs CHANGED
@@ -1,110 +1,110 @@
1
- // 核对字段名:配置页不动,说明自己写 x-label(PF 2026-09-29)。为防配置页改了名字说明没跟上,
2
- // 每个 x-label 按「 · 」拆开后,每一段都要在模块源码里原样出现过(说明文件本身不算)。
3
- // 0.3.0 起去掉注释再核对;vite 插件只拿构建实际用到的源码来核对,旧名字只留在注释或没人引用的文件里时不再漏检。
4
-
5
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
6
- import { extname, join, resolve, sep } from 'node:path'
7
-
8
- const SOURCE_EXTENSIONS = new Set(['.vue', '.ts', '.tsx', '.js', '.jsx', '.mjs'])
9
-
10
- const isSubSchema = (s) => typeof s === 'object' && s !== null && !Array.isArray(s)
11
-
12
- // 字段说明里所有的 x-label,连同它在说明里的位置
13
- export function collectLabels(schema, path = '$') {
14
- const found = []
15
- if (!schema || typeof schema !== 'object') return found
16
- if (typeof schema['x-label'] === 'string') found.push({ path, label: schema['x-label'] })
17
- for (const [key, sub] of Object.entries(schema.properties ?? {})) found.push(...collectLabels(sub, `${path}.${key}`))
18
- if (isSubSchema(schema.additionalProperties)) found.push(...collectLabels(schema.additionalProperties, `${path}.*`))
19
- if (schema.items) found.push(...collectLabels(schema.items, `${path}[]`))
20
- for (const sub of schema.anyOf ?? []) found.push(...collectLabels(sub, path))
21
- return found
22
- }
23
-
24
- function* sourceFiles(dir) {
25
- for (const name of readdirSync(dir)) {
26
- const p = join(dir, name)
27
- if (statSync(p).isDirectory()) yield* sourceFiles(p)
28
- else if (SOURCE_EXTENSIONS.has(extname(name))) yield p
29
- }
30
- }
31
-
32
- // 去掉脚本里的 // 与 /* */ 注释。字符串与模板字符串里的照留(如网址);不认正则字面量,
33
- // 但 '、" 字符串不跨行,认错时最多影响那一行
34
- export function stripScriptComments(code) {
35
- let out = ''
36
- let quote = null
37
- for (let i = 0; i < code.length; i++) {
38
- const c = code[i]
39
- if (quote) {
40
- out += c
41
- if (c === '\\' && i + 1 < code.length) out += code[++i]
42
- else if (c === quote || (c === '\n' && quote !== '`')) quote = null
43
- continue
44
- }
45
- if (c === '/' && code[i + 1] === '/') {
46
- while (i + 1 < code.length && code[i + 1] !== '\n') i++
47
- continue
48
- }
49
- if (c === '/' && code[i + 1] === '*') {
50
- const end = code.indexOf('*/', i + 2)
51
- i = end < 0 ? code.length : end + 1
52
- out += ' '
53
- continue
54
- }
55
- if (c === '"' || c === "'" || c === '`') quote = c
56
- out += c
57
- }
58
- return out
59
- }
60
-
61
- // .vue 文件:去掉 <!-- --> 注释,<script> 里按脚本去注释;模板正文里的 // 是文字(如网址),不动
62
- export function stripComments(text, ext) {
63
- if (ext !== '.vue') return stripScriptComments(text)
64
- return text
65
- .replace(/<!--[\s\S]*?-->/g, ' ')
66
- .replace(/(<script\b[^>]*>)([\s\S]*?)(<\/script>)/g, (_, open, body, close) => open + stripScriptComments(body) + close)
67
- }
68
-
69
- // 模板里的文字常写成 HTML 转义(如 Playlists &amp; Tracks),页面上显示的是转义前的样子;
70
- // x-label 写页面上看到的,所以核对时两种写法都认
71
- const decodeEntities = (s) =>
72
- s
73
- .replace(/&amp;/g, '&')
74
- .replace(/&lt;/g, '<')
75
- .replace(/&gt;/g, '>')
76
- .replace(/&quot;/g, '"')
77
- .replace(/&#39;|&apos;/g, "'")
78
- .replace(/&nbsp;/g, ' ')
79
-
80
- // Windows 上路径不分大小写
81
- const pathKey = (p) => (process.platform === 'win32' ? resolve(p).toLowerCase() : resolve(p))
82
-
83
- // files:构建实际用到的源码(vite 插件从模块图里取)。只留 dirs 下、扩展名对得上、确实存在的文件;
84
- // 不传就照旧扫 dirs 下全部源码(不经 vite 直接调用时)
85
- function filesToCheck(root, dirs, files) {
86
- if (!files) return dirs.flatMap((dir) => [...sourceFiles(resolve(root, dir))])
87
- const bases = dirs.map((dir) => pathKey(resolve(root, dir)) + sep)
88
- const seen = new Map()
89
- for (const f of files) {
90
- const k = pathKey(f)
91
- if (SOURCE_EXTENSIONS.has(extname(f)) && bases.some((b) => k.startsWith(b)) && existsSync(f)) seen.set(k, resolve(f))
92
- }
93
- return [...seen.values()]
94
- }
95
-
96
- export function checkLabels(schema, root, { dirs = ['src'], exclude = [], files } = {}) {
97
- const excluded = new Set(exclude.map((f) => pathKey(resolve(root, f))))
98
- let text = ''
99
- for (const file of filesToCheck(root, dirs, files)) {
100
- if (!excluded.has(pathKey(file))) text += stripComments(readFileSync(file, 'utf8'), extname(file)) + '\n'
101
- }
102
- text += '\n' + decodeEntities(text)
103
- const problems = []
104
- for (const { path, label } of collectLabels(schema)) {
105
- for (const part of label.split(' · ')) {
106
- if (!text.includes(part)) problems.push(`${path}:x-label「${label}」里的「${part}」在配置页源码里找不到`)
107
- }
108
- }
109
- return problems
110
- }
1
+ // 核对字段名:配置页不动,说明自己写 x-label(PF 2026-09-29)。为防配置页改了名字说明没跟上,
2
+ // 每个 x-label 按「 · 」拆开后,每一段都要在模块源码里原样出现过(说明文件本身不算)。
3
+ // 0.3.0 起去掉注释再核对;vite 插件只拿构建实际用到的源码来核对,旧名字只留在注释或没人引用的文件里时不再漏检。
4
+
5
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
6
+ import { extname, join, resolve, sep } from 'node:path'
7
+
8
+ const SOURCE_EXTENSIONS = new Set(['.vue', '.ts', '.tsx', '.js', '.jsx', '.mjs'])
9
+
10
+ const isSubSchema = (s) => typeof s === 'object' && s !== null && !Array.isArray(s)
11
+
12
+ // 字段说明里所有的 x-label,连同它在说明里的位置
13
+ export function collectLabels(schema, path = '$') {
14
+ const found = []
15
+ if (!schema || typeof schema !== 'object') return found
16
+ if (typeof schema['x-label'] === 'string') found.push({ path, label: schema['x-label'] })
17
+ for (const [key, sub] of Object.entries(schema.properties ?? {})) found.push(...collectLabels(sub, `${path}.${key}`))
18
+ if (isSubSchema(schema.additionalProperties)) found.push(...collectLabels(schema.additionalProperties, `${path}.*`))
19
+ if (schema.items) found.push(...collectLabels(schema.items, `${path}[]`))
20
+ for (const sub of schema.anyOf ?? []) found.push(...collectLabels(sub, path))
21
+ return found
22
+ }
23
+
24
+ function* sourceFiles(dir) {
25
+ for (const name of readdirSync(dir)) {
26
+ const p = join(dir, name)
27
+ if (statSync(p).isDirectory()) yield* sourceFiles(p)
28
+ else if (SOURCE_EXTENSIONS.has(extname(name))) yield p
29
+ }
30
+ }
31
+
32
+ // 去掉脚本里的 // 与 /* */ 注释。字符串与模板字符串里的照留(如网址);不认正则字面量,
33
+ // 但 '、" 字符串不跨行,认错时最多影响那一行
34
+ export function stripScriptComments(code) {
35
+ let out = ''
36
+ let quote = null
37
+ for (let i = 0; i < code.length; i++) {
38
+ const c = code[i]
39
+ if (quote) {
40
+ out += c
41
+ if (c === '\\' && i + 1 < code.length) out += code[++i]
42
+ else if (c === quote || (c === '\n' && quote !== '`')) quote = null
43
+ continue
44
+ }
45
+ if (c === '/' && code[i + 1] === '/') {
46
+ while (i + 1 < code.length && code[i + 1] !== '\n') i++
47
+ continue
48
+ }
49
+ if (c === '/' && code[i + 1] === '*') {
50
+ const end = code.indexOf('*/', i + 2)
51
+ i = end < 0 ? code.length : end + 1
52
+ out += ' '
53
+ continue
54
+ }
55
+ if (c === '"' || c === "'" || c === '`') quote = c
56
+ out += c
57
+ }
58
+ return out
59
+ }
60
+
61
+ // .vue 文件:去掉 <!-- --> 注释,<script> 里按脚本去注释;模板正文里的 // 是文字(如网址),不动
62
+ export function stripComments(text, ext) {
63
+ if (ext !== '.vue') return stripScriptComments(text)
64
+ return text
65
+ .replace(/<!--[\s\S]*?-->/g, ' ')
66
+ .replace(/(<script\b[^>]*>)([\s\S]*?)(<\/script>)/g, (_, open, body, close) => open + stripScriptComments(body) + close)
67
+ }
68
+
69
+ // 模板里的文字常写成 HTML 转义(如 Playlists &amp; Tracks),页面上显示的是转义前的样子;
70
+ // x-label 写页面上看到的,所以核对时两种写法都认
71
+ const decodeEntities = (s) =>
72
+ s
73
+ .replace(/&amp;/g, '&')
74
+ .replace(/&lt;/g, '<')
75
+ .replace(/&gt;/g, '>')
76
+ .replace(/&quot;/g, '"')
77
+ .replace(/&#39;|&apos;/g, "'")
78
+ .replace(/&nbsp;/g, ' ')
79
+
80
+ // Windows 上路径不分大小写
81
+ const pathKey = (p) => (process.platform === 'win32' ? resolve(p).toLowerCase() : resolve(p))
82
+
83
+ // files:构建实际用到的源码(vite 插件从模块图里取)。只留 dirs 下、扩展名对得上、确实存在的文件;
84
+ // 不传就照旧扫 dirs 下全部源码(不经 vite 直接调用时)
85
+ function filesToCheck(root, dirs, files) {
86
+ if (!files) return dirs.flatMap((dir) => [...sourceFiles(resolve(root, dir))])
87
+ const bases = dirs.map((dir) => pathKey(resolve(root, dir)) + sep)
88
+ const seen = new Map()
89
+ for (const f of files) {
90
+ const k = pathKey(f)
91
+ if (SOURCE_EXTENSIONS.has(extname(f)) && bases.some((b) => k.startsWith(b)) && existsSync(f)) seen.set(k, resolve(f))
92
+ }
93
+ return [...seen.values()]
94
+ }
95
+
96
+ export function checkLabels(schema, root, { dirs = ['src'], exclude = [], files } = {}) {
97
+ const excluded = new Set(exclude.map((f) => pathKey(resolve(root, f))))
98
+ let text = ''
99
+ for (const file of filesToCheck(root, dirs, files)) {
100
+ if (!excluded.has(pathKey(file))) text += stripComments(readFileSync(file, 'utf8'), extname(file)) + '\n'
101
+ }
102
+ text += '\n' + decodeEntities(text)
103
+ const problems = []
104
+ for (const { path, label } of collectLabels(schema)) {
105
+ for (const part of label.split(' · ')) {
106
+ if (!text.includes(part)) problems.push(`${path}:x-label「${label}」里的「${part}」在配置页源码里找不到`)
107
+ }
108
+ }
109
+ return problems
110
+ }
@@ -7,6 +7,7 @@ import { join, resolve } from 'node:path'
7
7
  import { pathToFileURL } from 'node:url'
8
8
  import { validate } from './validate.mjs'
9
9
  import { checkLabels } from './labels.mjs'
10
+ import { checkExitRules } from './exits.mjs'
10
11
 
11
12
  export { checkLabels, collectLabels } from './labels.mjs'
12
13
 
@@ -52,16 +53,20 @@ export async function loadSpec(root, entry) {
52
53
  export async function buildContentConfig(root, entry = 'src/content-config.ts', { labelDirs = ['src'], labelFiles } = {}) {
53
54
  const spec = await loadSpec(root, entry)
54
55
  if (!spec || typeof spec.endpoint !== 'string' || !spec.endpoint || !spec.schema || spec.defaultBody === undefined) {
55
- throw new Error(`content-config:${entry} 要默认导出 { endpoint, defaultBody, schema }`)
56
+ throw new Error(`content-config:${entry} 要默认导出 { endpoint, defaultBody, schema }(有动态出口的再加 dynamicExits)`)
56
57
  }
57
58
  const defaultBody = typeof spec.defaultBody === 'function' ? await spec.defaultBody() : spec.defaultBody
58
59
  // 出厂默认可以留空「保存前必须填」的字段(x-fill-before-save),其余照常校验
59
60
  const errors = validate(spec.schema, defaultBody, '$', { allowUnfilled: true })
60
61
  if (labelDirs.length) errors.push(...checkLabels(spec.schema, root, { dirs: labelDirs, exclude: [entry], files: labelFiles }))
62
+ if (spec.dynamicExits !== undefined) errors.push(...checkExitRules(spec.dynamicExits, { schema: spec.schema, body: defaultBody }))
61
63
  if (errors.length) {
62
64
  throw new Error(`content-config:字段说明没通过检查(${errors.length} 处)\n ${errors.join('\n ')}`)
63
65
  }
64
- return { format: FORMAT, endpoint: spec.endpoint, defaultBody, schema: spec.schema }
66
+ // dynamicExits 是 0.4.0 加的可选键,格式号不变:读取方不认识就当没有(建活动 skill 读到才补出口)
67
+ const doc = { format: FORMAT, endpoint: spec.endpoint, defaultBody, schema: spec.schema }
68
+ if (spec.dynamicExits !== undefined) doc.dynamicExits = spec.dynamicExits
69
+ return doc
65
70
  }
66
71
 
67
72
  export default function contentConfig({ entry = 'src/content-config.ts', fileName = 'assets/content-config.json', labelDirs = ['src'] } = {}) {