@taptap/maker 0.0.36 → 0.0.37-beta.10

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.
@@ -0,0 +1,109 @@
1
+ # NanoVG 提取与回放
2
+
3
+ NanoVG 是即时绘制 API,原 Lua 函数没有可直接序列化的控件树。
4
+ 编辑器用 NanoVG 节点保存命名图层内的绘制指令,保留原始坐标、曲线、渐变和绘制顺序。
5
+ 这是视觉数据,不是 Lua 程序,不会自动提取业务热区或动画。
6
+
7
+ ## 文档格式
8
+
9
+ ```json
10
+ {
11
+ "type": "NanoVG",
12
+ "id": "border",
13
+ "position": "absolute",
14
+ "left": 20,
15
+ "top": 30,
16
+ "width": 240,
17
+ "height": 160,
18
+ "viewBox": [0, 0, 240, 160],
19
+ "commands": [
20
+ ["beginPath"],
21
+ ["roundedRect", 2, 2, 236, 156, 12],
22
+ ["fillPaint", { "kind": "linearGradient", "args": [0, 0, 240, 160, "#164e63", "#22a899"] }],
23
+ ["fill"],
24
+ ["strokeColor", "#a7f3d0"],
25
+ ["strokeWidth", 2],
26
+ ["stroke"]
27
+ ]
28
+ }
29
+ ```
30
+
31
+ 节点可与 Panel、Label、Button 混用。viewBox 定义局部坐标;改节点尺寸会整体缩放,
32
+ 不重算原绘图函数。背景样式写在指令中;通用节点属性控制布局、透明度、变换。
33
+ 节点树中的 NanoVG 类型名使用青色区分,不添加重复后缀,也不改文档 ID。
34
+ 属性面板点击「应用」后一次进入撤销历史;CLI ui patch 用 set 修改 commands/viewBox,
35
+ 沿用 revision 冲突保护和原子保存。
36
+
37
+ ui capabilities --json 列出完整指令签名。每条指令为数组,第一项是去掉 nvg 前缀的 API 名,
38
+ 其余参数去掉 context。颜色是 0..255 RGBA 数组或 #RRGGBB / #RRGGBBAA。
39
+ paint 使用 {kind,args},支持 linearGradient、radialGradient、imagePattern;
40
+ 图片画刷的第六个参数是 assets 相对资源路径,不保存原生 image handle。
41
+ 单层最多 20000 条指令,save/restore 必须配对且最多嵌套 32 层;调用方仍须为外围 UI 保留原生栈空间。
42
+
43
+ ## 从 Lua 提取
44
+
45
+ 1. 读取活动页面及绘图函数,确认设计尺寸。按已有面板、装饰、标题等函数划分命名图层,
46
+ 保留稳定 ID;不要将整个游戏压成不可分选的截图。
47
+ 2. 使用 [MakerNanoVG.lua](../runtime/MakerNanoVG.lua),或通过 ui nanovg-adapter 取得同一源码。
48
+ 默认先在受控测试入口验证,不覆盖已有同名脚本。
49
+ 3. 在已创建字体/资源、已开始的 NanoVG 帧内,对审阅过的同步函数调用 capture。
50
+ 它临时包装全局 nvg 函数,结束或异常时恢复,不能跨协程、跨帧或嵌套执行。
51
+
52
+ ```lua
53
+ local Vector = require("ui.MakerNanoVG")
54
+ local layer = Vector.capture(vg, {
55
+ id = "gothic_panel", width = 760, height = 460, left = 120, top = 100,
56
+ images = { [nativeImage] = "image/panel.png" }, -- 仅用到已有图片时提供
57
+ fonts = { [fontId] = "sans" }, -- 仅用到 FontFaceId 时提供
58
+ }, function()
59
+ Theme.DrawPanel(vg, 12, 12, 730, 420, 0.9)
60
+ end)
61
+ -- 用项目已有 cjson/资源写入方式输出 layer 或装入页面 children。
62
+ ```
63
+
64
+ capture 从默认绘图状态和局部坐标开始,结束恢复原状态。回调内应设置颜色、画刷、字号,
65
+ 不能依赖外层 transform、scissor 或隐含样式。已有图片/字体句柄须提供映射;
66
+ 颜色和画刷在回调内创建。资源创建、销毁、未知 API 或无法映射的句柄会导致捕获失败。
67
+ 可分离资源初始化与绘图后再提取,不能自动改写游戏业务逻辑来强行通过。
68
+
69
+ 用 ui create --input-file 将结果写到新文件,检查后显式生成 meta。已有文档沿用 revision 比较,
70
+ 不重新生成覆盖编辑结果。逐层检查缩放、文字、裁剪,说明捕获的动态状态,不推断其他状态已覆盖。
71
+ 捕获前核对真实入场参数与动画终态,避免把尚未淡入的透明层误当作空页面。
72
+ 若只提取某个初态,在文档中记录 `exportState`;多阶段页面按实际子状态分别检查。
73
+ 存档数据区保持真实空态,另保留模板与绑定边界;不要伪造玩家数据填满页面。
74
+ 拆分捕获结果时保留绘制顺序和进入每层时的颜色、字体、变换、裁剪状态,不能在未配对的 save/restore 中间切层。
75
+
76
+ ## 引擎接入
77
+
78
+ 仅提取时保留游戏入口。明确接入时才替换原绘制调用,不能新旧重复绘制。
79
+ 原始 NanoVG 项目在现有 NanoVGRender / BeginFrame / EndFrame 中回放已解析节点:
80
+
81
+ ```lua
82
+ -- resolveImage(path, ctx) 复用项目图片缓存,返回原生句柄。
83
+ Vector.draw(vg, layer, layer.left, layer.top, layer.width, layer.height, resolveImage)
84
+ ```
85
+
86
+ draw 只画一个图层,不遍历普通 UI 节点,不管理帧、字体、资源、事件或存档。
87
+ 直接调用时由游戏负责显隐、动画、外围变换及热区,不能让图层移位后热区仍留在旧坐标。
88
+
89
+ 使用 urhox-libs/UI 时,在项目原 UI.LoadJSON 流程之前注册一次:
90
+
91
+ ```lua
92
+ local UI = require("urhox-libs/UI")
93
+ local Vector = require("ui.MakerNanoVG")
94
+ Vector.register(UI, resolveImage)
95
+ ```
96
+
97
+ 注册复用 Widget 的布局、变换与树遍历;仍须绑定交互。新增 JSON 不证明引擎已接入。
98
+ 字体名称由项目在当前 context 中创建,不能把浏览器兜底字体当原生字体。
99
+
100
+ ## 限制与验收
101
+
102
+ 支持路径、圆角/圆/椭圆/弧、贝塞尔曲线、描边、线性/径向渐变、图片画刷、单行及 textBox 多行文字、变换及裁剪。
103
+ textBox 指令为 `["textBox", x, y, width, text]`,宽度大于 0;浏览器按字体度量换行,保留显式换行,原生回放调用 nvgTextBox。
104
+ 未列入白名单的调用(箱形渐变、pathWinding 孔洞、混合、fontBlur、reset 系列等)
105
+ 会报错;不能删指令、用矩形或截图来掩盖差异。
106
+ Canvas 2D 与 NanoVG 的字体度量、抗锯齿、非等比描边、旋转裁剪可能不同。
107
+ 浏览器图片画刷暂按重复采样预览,原生图片边缘/重复模式由项目 image flags 决定。
108
+ 分别报告静态检查、浏览器视觉、Lua 调用测试和真实引擎视觉/交互验收。
109
+ 模拟 nvg 函数的捕获/回放测试不能代替真实引擎验收。
@@ -0,0 +1,289 @@
1
+ -- Maker NanoVG data adapter. No Lua source is stored in UI documents.
2
+ -- capture() is an explicit, synchronous development operation; hooks never survive it.
3
+ local M = {}
4
+ local unpack = table.unpack or unpack
5
+ local active = false
6
+ local signatures = {
7
+ save = "", restore = "", beginPath = "", closePath = "", fill = "", stroke = "",
8
+ moveTo = "nn", lineTo = "nn", bezierTo = "nnnnnn", quadTo = "nnnn", arcTo = "nnnnn",
9
+ rect = "nnnn", roundedRect = "nnnnn", roundedRectVarying = "nnnnnnnn",
10
+ circle = "nnn", ellipse = "nnnn", arc = "nnnnnn",
11
+ translate = "nn", scale = "nn", rotate = "n", skewX = "n", skewY = "n", transform = "nnnnnn",
12
+ scissor = "nnnn", intersectScissor = "nnnn",
13
+ fillColor = "c", strokeColor = "c", fillPaint = "p", strokePaint = "p",
14
+ strokeWidth = "n", miterLimit = "n", lineCap = "n", lineJoin = "n", globalAlpha = "n",
15
+ fontSize = "n", fontFace = "s", textAlign = "n", textLetterSpacing = "n", text = "nns", textBox = "nnns",
16
+ }
17
+ local paints = { linearGradient = "nnnncc", radialGradient = "nnnncc", imagePattern = "nnnnnsn" }
18
+
19
+ local function finite(n) return type(n) == "number" and n == n and math.abs(n) < math.huge end
20
+ local function color(value)
21
+ if type(value) == "string" then
22
+ assert((#value == 7 or #value == 9) and value:match("^#%x+$"), "Invalid NanoVG color")
23
+ return { tonumber(value:sub(2, 3), 16), tonumber(value:sub(4, 5), 16),
24
+ tonumber(value:sub(6, 7), 16), #value == 9 and tonumber(value:sub(8, 9), 16) or 255 }
25
+ end
26
+ assert(type(value) == "table" and #value == 4, "Expected RGBA color")
27
+ for i = 1, 4 do assert(finite(value[i]) and value[i] >= 0 and value[i] <= 255, "Invalid color channel") end
28
+ return value
29
+ end
30
+
31
+ local function validateArgs(args, sig)
32
+ assert(type(args) == "table" and #args == #sig, "Invalid NanoVG argument count")
33
+ for i = 1, #sig do
34
+ local kind, value = sig:sub(i, i), args[i]
35
+ if kind == "n" then assert(finite(value), "Expected finite NanoVG number")
36
+ elseif kind == "s" then assert(type(value) == "string", "Expected NanoVG string")
37
+ elseif kind == "c" then color(value)
38
+ else
39
+ assert(type(value) == "table" and paints[value.kind], "Unsupported NanoVG paint")
40
+ validateArgs(value.args, paints[value.kind])
41
+ end
42
+ end
43
+ end
44
+
45
+ local function validate(node)
46
+ assert(type(node) == "table" and node.type == "NanoVG", "Expected NanoVG node")
47
+ validateArgs(node.viewBox, "nnnn")
48
+ assert(node.viewBox[3] > 0 and node.viewBox[4] > 0, "Invalid NanoVG viewBox")
49
+ assert(type(node.commands) == "table" and #node.commands <= 20000, "Too many NanoVG commands")
50
+ local depth = 0
51
+ for _, cmd in ipairs(node.commands) do
52
+ assert(type(cmd) == "table" and signatures[cmd[1]], "Unsupported NanoVG command: " .. tostring(cmd[1]))
53
+ local args = {}; for i = 2, #cmd do args[#args + 1] = cmd[i] end
54
+ validateArgs(args, signatures[cmd[1]])
55
+ if cmd[1] == "textBox" then assert(args[3] > 0, "Text box width must be positive") end
56
+ if cmd[1] == "save" then depth = depth + 1 end
57
+ if cmd[1] == "restore" then depth = depth - 1 end
58
+ assert(depth >= 0 and depth <= 32, "Unbalanced NanoVG state stack (layer limit: 32)")
59
+ end
60
+ assert(depth == 0, "Unbalanced NanoVG state stack")
61
+ end
62
+ M.validate = validate
63
+
64
+ -- opts.images maps existing native image handles to assets-relative resource paths.
65
+ -- opts.fonts maps existing font IDs to names. Unknown APIs/opaque paints fail capture.
66
+ function M.capture(ctx, opts, draw)
67
+ assert(not active, "Nested NanoVG capture is not supported; capture separate named layers")
68
+ assert(type(opts) == "table" and type(draw) == "function", "capture requires options and a draw function")
69
+ local node = { type = "NanoVG", id = opts.id, position = "absolute", left = opts.left or 0,
70
+ top = opts.top or 0, width = opts.width, height = opts.height,
71
+ viewBox = opts.viewBox or { 0, 0, opts.width, opts.height }, commands = {} }
72
+ local originals, colors, paintValues = {}, {}, {}
73
+ local images, fonts = opts.images or {}, opts.fonts or {}
74
+ local depth, failure = 0, nil
75
+ local function remember(op, args)
76
+ assert(#node.commands < 20000, "NanoVG command limit exceeded")
77
+ local cmd = { op }; for _, value in ipairs(args) do cmd[#cmd + 1] = value end
78
+ node.commands[#node.commands + 1] = cmd
79
+ end
80
+ local function capturedColor(value)
81
+ assert(colors[value], "Color was created outside capture; create it inside the draw callback")
82
+ return colors[value]
83
+ end
84
+ local function wrap(name, fn)
85
+ if originals[name] then
86
+ _G[name] = function(...)
87
+ local result = { pcall(fn, ...) }
88
+ if not result[1] then failure = tostring(result[2]); error(failure) end
89
+ return unpack(result, 2)
90
+ end
91
+ end
92
+ end
93
+ for name, fn in pairs(_G) do
94
+ if type(fn) == "function" and name:match("^nvg[A-Z]") then originals[name] = fn end
95
+ end
96
+ assert(originals.nvgSave and originals.nvgRestore and originals.nvgReset, "NanoVG context is unavailable")
97
+ originals.nvgSave(ctx)
98
+ active = true
99
+ -- Refuse unrecorded drawing instead of returning a visually incomplete success.
100
+ for name in pairs(originals) do
101
+ local api = name
102
+ _G[api] = function()
103
+ failure = "Unsupported NanoVG capture API: " .. api
104
+ error(failure)
105
+ end
106
+ end
107
+ for op, sig in pairs(signatures) do
108
+ local operation, signature = op, sig
109
+ local name = "nvg" .. op:sub(1, 1):upper() .. op:sub(2)
110
+ wrap(name, function(vg, ...)
111
+ assert(vg == ctx, "A capture may only use its own NanoVG context")
112
+ local args = { ... }
113
+ for i = 1, #signature do
114
+ local kind = signature:sub(i, i)
115
+ if kind == "c" then args[i] = capturedColor(args[i])
116
+ elseif kind == "p" then
117
+ assert(paintValues[args[i]], "Paint was created outside capture")
118
+ args[i] = paintValues[args[i]]
119
+ end
120
+ end
121
+ validateArgs(args, signature)
122
+ if operation == "save" then assert(depth < 32, "NanoVG stack limit") end
123
+ if operation == "restore" then assert(depth > 0, "Unbalanced NanoVG restore") end
124
+ remember(operation, args)
125
+ local result = originals[name](vg, ...)
126
+ if operation == "save" then depth = depth + 1 end
127
+ if operation == "restore" then depth = depth - 1 end
128
+ return result
129
+ end)
130
+ end
131
+ for _, name in ipairs({ "nvgRGB", "nvgRGBA", "nvgRGBf", "nvgRGBAf" }) do
132
+ local api = name
133
+ wrap(api, function(...)
134
+ local a = { ... }; local factor = api:sub(-1) == "f" and 255 or 1
135
+ local rgba = { a[1] * factor, a[2] * factor, a[3] * factor, a[4] and a[4] * factor or 255 }
136
+ color(rgba)
137
+ local result = originals[api](...); colors[result] = rgba; return result
138
+ end)
139
+ end
140
+ for kind, sig in pairs(paints) do
141
+ local paintKind, signature = kind, sig
142
+ local name = "nvg" .. kind:sub(1, 1):upper() .. kind:sub(2)
143
+ wrap(name, function(vg, ...)
144
+ assert(vg == ctx, "NanoVG context mismatch")
145
+ local args = { ... }
146
+ if paintKind == "imagePattern" then
147
+ assert(images[args[6]], "Image handle requires opts.images mapping")
148
+ args[6] = images[args[6]]
149
+ else args[5] = capturedColor(args[5]); args[6] = capturedColor(args[6]) end
150
+ validateArgs(args, signature)
151
+ local result = originals[name](vg, ...)
152
+ paintValues[result] = { kind = paintKind, args = args }
153
+ return result
154
+ end)
155
+ end
156
+ wrap("nvgFontFaceId", function(vg, id)
157
+ assert(vg == ctx and fonts[id], "Font ID requires opts.fonts mapping")
158
+ remember("fontFace", { fonts[id] }); return originals.nvgFontFaceId(vg, id)
159
+ end)
160
+ for _, name in ipairs({ "nvgImageSize", "nvgTextBounds", "nvgTextMetrics" }) do
161
+ if originals[name] then _G[name] = originals[name] end
162
+ end
163
+ local ok, err = xpcall(function()
164
+ originals.nvgReset(ctx)
165
+ originals.nvgBeginPath(ctx)
166
+ draw()
167
+ assert(not failure, failure)
168
+ validate(node)
169
+ end, function(e) return tostring(e) end)
170
+ for name, fn in pairs(originals) do _G[name] = fn end
171
+ for _ = 1, depth do originals.nvgRestore(ctx) end
172
+ originals.nvgRestore(ctx)
173
+ active = false
174
+ if not ok then error(err) end
175
+ return node
176
+ end
177
+
178
+ local function nativeColor(value) return nvgRGBA(unpack(color(value))) end
179
+ local function multiply(a, b)
180
+ return { a[1]*b[1]+a[3]*b[2], a[2]*b[1]+a[4]*b[2], a[1]*b[3]+a[3]*b[4],
181
+ a[2]*b[3]+a[4]*b[4], a[1]*b[5]+a[3]*b[6]+a[5], a[2]*b[5]+a[4]*b[6]+a[6] }
182
+ end
183
+ local function inverse(m)
184
+ local d = m[1]*m[4]-m[2]*m[3]
185
+ if math.abs(d) < 1e-12 then return nil end
186
+ return { m[4]/d, -m[2]/d, -m[3]/d, m[1]/d,
187
+ (m[3]*m[6]-m[4]*m[5])/d, (m[2]*m[5]-m[1]*m[6])/d }
188
+ end
189
+
190
+ -- Draw a leaf inside the caller's active NanoVG frame. Layout belongs to the caller.
191
+ -- resolveImage(path, ctx) returns a cached native handle; this module owns no resources.
192
+ function M.draw(ctx, node, x, y, width, height, resolveImage, opacity)
193
+ validate(node)
194
+ local view, depth = node.viewBox, 0
195
+ local matrix, clips, stack = { 1, 0, 0, 1, 0, 0 }, {}, {}
196
+ nvgSave(ctx)
197
+ local ok, err = xpcall(function()
198
+ nvgTranslate(ctx, x or node.left or 0, y or node.top or 0)
199
+ nvgScale(ctx, (width or node.width or view[3]) / view[3], (height or node.height or view[4]) / view[4])
200
+ nvgTranslate(ctx, -view[1], -view[2])
201
+ nvgFillColor(ctx, nvgRGBA(255, 255, 255, 255)); nvgStrokeColor(ctx, nvgRGBA(0, 0, 0, 255))
202
+ nvgStrokeWidth(ctx, 1); nvgMiterLimit(ctx, 10); nvgLineCap(ctx, 0); nvgLineJoin(ctx, 4)
203
+ nvgFontSize(ctx, 16); nvgFontFace(ctx, "sans"); nvgTextAlign(ctx, 65)
204
+ nvgTextLetterSpacing(ctx, 0)
205
+ if opacity then nvgGlobalAlpha(ctx, opacity) end
206
+ nvgBeginPath(ctx)
207
+ local function clipped(fn, args)
208
+ if #clips == 0 then fn(ctx, unpack(args)); return end
209
+ local inv = inverse(matrix)
210
+ if not inv then return end
211
+ -- Apply layer scissors at paint time so replacing a local scissor cannot
212
+ -- discard an enclosing Widget/ScrollView clip.
213
+ nvgSave(ctx)
214
+ local painted, problem = pcall(function()
215
+ nvgTransform(ctx, unpack(inv))
216
+ for _, clip in ipairs(clips) do
217
+ local back = inverse(clip.matrix)
218
+ if not back then return end
219
+ nvgTransform(ctx, unpack(clip.matrix))
220
+ nvgIntersectScissor(ctx, unpack(clip.args))
221
+ nvgTransform(ctx, unpack(back))
222
+ end
223
+ nvgTransform(ctx, unpack(matrix))
224
+ fn(ctx, unpack(args))
225
+ end)
226
+ nvgRestore(ctx)
227
+ if not painted then error(problem) end
228
+ end
229
+ for _, cmd in ipairs(node.commands) do
230
+ local op, args = cmd[1], {}
231
+ for i = 2, #cmd do args[#args + 1] = cmd[i] end
232
+ if op == "fillColor" or op == "strokeColor" then args[1] = nativeColor(args[1]) end
233
+ if op == "globalAlpha" then args[1] = args[1] * (opacity or 1) end
234
+ if op == "fillPaint" or op == "strokePaint" then
235
+ local p, a = args[1], {}; for i, value in ipairs(args[1].args) do a[i] = value end
236
+ if p.kind == "imagePattern" then
237
+ assert(resolveImage, "Image paint requires resolveImage(path, ctx)")
238
+ a[6] = resolveImage(a[6], ctx)
239
+ assert(type(a[6]) == "number" and a[6] > 0, "NanoVG image could not be resolved")
240
+ else a[5] = nativeColor(a[5]); a[6] = nativeColor(a[6]) end
241
+ args[1] = _G["nvg" .. p.kind:sub(1, 1):upper() .. p.kind:sub(2)](ctx, unpack(a))
242
+ end
243
+ local fn = _G["nvg" .. op:sub(1, 1):upper() .. op:sub(2)]
244
+ assert(type(fn) == "function", "NanoVG runtime API missing: " .. op)
245
+ if op == "scissor" or op == "intersectScissor" then
246
+ local nextClips = {}
247
+ if op == "intersectScissor" then for i, clip in ipairs(clips) do nextClips[i] = clip end end
248
+ nextClips[#nextClips + 1] = { matrix = matrix, args = args }; clips = nextClips
249
+ elseif op == "fill" or op == "stroke" or op == "text" or op == "textBox" then clipped(fn, args)
250
+ else fn(ctx, unpack(args)) end
251
+ if op == "save" then depth = depth + 1; stack[depth] = { matrix = matrix, clips = clips } end
252
+ if op == "restore" then matrix = stack[depth].matrix; clips = stack[depth].clips; stack[depth] = nil; depth = depth - 1 end
253
+ local t
254
+ if op == "transform" then t = args
255
+ elseif op == "translate" then t = { 1, 0, 0, 1, args[1], args[2] }
256
+ elseif op == "scale" then t = { args[1], 0, 0, args[2], 0, 0 }
257
+ elseif op == "rotate" then
258
+ local c, s = math.cos(args[1]), math.sin(args[1]); t = { c, s, -s, c, 0, 0 }
259
+ elseif op == "skewX" then t = { 1, 0, math.tan(args[1]), 1, 0, 0 }
260
+ elseif op == "skewY" then t = { 1, math.tan(args[1]), 0, 1, 0, 0 } end
261
+ if t then matrix = multiply(matrix, t) end
262
+ end
263
+ end, function(e) return tostring(e) end)
264
+ for _ = 1, depth do nvgRestore(ctx) end
265
+ nvgRestore(ctx)
266
+ if not ok then error(err) end
267
+ end
268
+
269
+ -- Register the node before UI.LoadJSON; reuse the engine's layout, input and transforms.
270
+ function M.register(UI, resolveImage)
271
+ assert(not UI.NanoVG, "UI.NanoVG is already registered")
272
+ local Widget = require("urhox-libs/UI/Core/Widget")
273
+ local Vector = Widget:Extend("NanoVG")
274
+ function Vector:Render(ctx)
275
+ local layout = self:GetAbsoluteLayout()
276
+ local data = { type = "NanoVG", commands = self.props.commands, viewBox = self.props.viewBox }
277
+ local opacity, widget = 1, self
278
+ while widget do
279
+ local a = widget.renderProps_ and widget.renderProps_.opacity or widget.props.opacity or 1
280
+ opacity = opacity * math.max(0, math.min(1, a))
281
+ widget = widget.parent
282
+ end
283
+ M.draw(ctx, data, layout.x, layout.y, layout.w, layout.h, resolveImage, opacity)
284
+ end
285
+ UI.NanoVG = Vector
286
+ return Vector
287
+ end
288
+
289
+ return M
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { checkDocument } = require("./ui-json-check.cjs");
6
+
7
+ function inside(root, file) {
8
+ const rel = path.relative(root, file);
9
+ return rel === "" || (!rel.startsWith(".." + path.sep) && rel !== ".." && !path.isAbsolute(rel));
10
+ }
11
+ function readProjectConfig(root) {
12
+ const source = ".project/project.json";
13
+ const file = path.join(root, source);
14
+ try {
15
+ const raw = JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
16
+ const publish = raw && typeof raw.taptap_publish === "object" ? raw.taptap_publish : raw;
17
+ const orientation = publish && (publish.screen_orientation || publish.orientation);
18
+ return { orientation: orientation === "landscape" || orientation === "portrait" ? orientation : null, source };
19
+ } catch (error) {
20
+ if (error.code === "ENOENT") return { orientation: null, source, missing: true };
21
+ return { orientation: null, source, error: error.message };
22
+ }
23
+ }
24
+ function checkExportManifest(root, assets, files, diagnostics) {
25
+ const relative = "assets/ui/ui-export-manifest.ui.json";
26
+ const file = path.join(assets, "ui", "ui-export-manifest.ui.json");
27
+ if (!fs.existsSync(file)) return;
28
+ let manifest;
29
+ try {
30
+ manifest = JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
31
+ } catch (error) {
32
+ diagnostics.push({ code: "UI_MANIFEST_PARSE", severity: "error", file: relative, pointer: "",
33
+ message: error.message });
34
+ return;
35
+ }
36
+ const categories = ["pages", "components", "templates"];
37
+ const actual = new Set(files.map(item => path.relative(assets, item).split(path.sep).join("/")));
38
+ categories.forEach(kind => {
39
+ const listed = Array.isArray(manifest[kind]) ? manifest[kind].filter(item => typeof item === "string") : [];
40
+ const listedSet = new Set(listed);
41
+ const actualFiles = [...actual].filter(item => item.startsWith("ui/" + kind + "/"));
42
+ const missing = listed.filter(item => !actual.has(item));
43
+ const unlisted = actualFiles.filter(item => !listedSet.has(item));
44
+ if (missing.length) diagnostics.push({ code: "UI_MANIFEST_MISSING_FILE", severity: "error",
45
+ file: relative, pointer: "/" + kind, message: "导出清单登记了不存在的文件:" + missing.join(", ") });
46
+ if (unlisted.length) diagnostics.push({ code: "UI_MANIFEST_STALE", severity: "warning",
47
+ file: relative, pointer: "/" + kind, message: "目录中有 " + unlisted.length +
48
+ " 个 " + kind + " 文件未登记,清单可能来自旧导出:" + unlisted.slice(0, 5).join(", ") +
49
+ (unlisted.length > 5 ? " …" : "") });
50
+ });
51
+ }
52
+ function main(argv) {
53
+ if (argv.includes("--help")) {
54
+ console.log("node check-ui.cjs --project <game-root> [--file assets/ui/page.ui.json] [--format json|text]");
55
+ return 0;
56
+ }
57
+ const args = {};
58
+ for (let i = 0; i < argv.length; i += 2) {
59
+ if (!["--project", "--file", "--format"].includes(argv[i]) || !argv[i + 1] || argv[i + 1].startsWith("--")) {
60
+ throw new Error("Unknown or incomplete argument: " + argv[i]);
61
+ }
62
+ args[argv[i]] = argv[i + 1];
63
+ }
64
+ if (!args["--project"]) throw new Error("--project is required");
65
+ const format = args["--format"] || "text";
66
+ if (!["json", "text"].includes(format)) throw new Error("--format must be json or text");
67
+ const root = fs.realpathSync(args["--project"]);
68
+ const assets = fs.realpathSync(path.join(root, "assets"));
69
+ if (!inside(root, assets)) throw new Error("assets must be inside the project");
70
+ const files = [], scanDiagnostics = [];
71
+ function scan(dir) {
72
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
73
+ if ([".git", "node_modules"].includes(entry.name)) continue;
74
+ const file = path.join(dir, entry.name);
75
+ if (entry.isSymbolicLink()) {
76
+ scanDiagnostics.push({ code: "UI_SCAN_SYMLINK", severity: "warning",
77
+ file: path.relative(root, file), pointer: "", message: "未递归扫描符号链接,请检查其目标。" });
78
+ } else if (entry.isDirectory()) scan(file);
79
+ else if (/\.ui\.json$/i.test(entry.name)) files.push(file);
80
+ }
81
+ }
82
+ if (args["--file"]) {
83
+ const target = path.resolve(root, args["--file"]);
84
+ if (!inside(assets, target) || !/\.ui\.json$/i.test(target)) throw new Error("--file must be a .ui.json inside assets");
85
+ const real = fs.realpathSync(target);
86
+ if (!inside(assets, real)) throw new Error("--file symlink escapes assets");
87
+ files.push(real);
88
+ } else scan(assets);
89
+ const projectConfig = readProjectConfig(root);
90
+ const report = { version: 1, files: files.length, errors: 0, warnings: 0,
91
+ projectConfig,
92
+ diagnostics: scanDiagnostics, skipped: [] };
93
+ checkExportManifest(root, assets, files, report.diagnostics);
94
+ if (projectConfig.error) report.diagnostics.push({ code: "UI_PROJECT_CONFIG_PARSE", severity: "error",
95
+ file: projectConfig.source, pointer: "", message: projectConfig.error });
96
+ else if (projectConfig.missing) report.diagnostics.push({ code: "UI_PROJECT_CONFIG_MISSING", severity: "warning",
97
+ file: projectConfig.source, pointer: "", message: "未找到项目屏幕方向配置;页面预览可能使用错误的横竖屏设备。" });
98
+ const skipped = new Set();
99
+ function resourceExists(ref) {
100
+ const file = path.resolve(assets, ref);
101
+ if (!inside(assets, file)) return false;
102
+ try {
103
+ const real = fs.realpathSync(file);
104
+ if (!inside(assets, real)) return false;
105
+ fs.accessSync(real, fs.constants.R_OK);
106
+ return fs.statSync(real).isFile();
107
+ } catch (_) { return false; }
108
+ }
109
+ for (const file of files) {
110
+ const relative = path.relative(root, file).split(path.sep).join("/");
111
+ let tree;
112
+ try {
113
+ if (fs.statSync(file).size > 4 * 1024 * 1024) throw new Error("File exceeds 4 MiB");
114
+ tree = JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
115
+ } catch (error) {
116
+ report.diagnostics.push({ code: "UI_JSON_PARSE", severity: "error",
117
+ file: relative, pointer: "", message: error.message });
118
+ continue;
119
+ }
120
+ const result = checkDocument({ file: relative, tree, resourceExists });
121
+ report.diagnostics.push(...result.diagnostics);
122
+ if (projectConfig.orientation && /assets\/ui\/pages\//i.test(relative) &&
123
+ typeof tree.width === "number" && typeof tree.height === "number") {
124
+ const landscape = tree.width >= tree.height;
125
+ if ((projectConfig.orientation === "landscape") !== landscape) {
126
+ report.diagnostics.push({ code: "UI_DESIGN_ORIENTATION", severity: "error", file: relative,
127
+ pointer: "/width", message: "页面根尺寸 " + tree.width + "×" + tree.height +
128
+ " 与项目配置的 " + projectConfig.orientation + " 方向不一致。" });
129
+ }
130
+ }
131
+ result.skipped.forEach(item => skipped.add(item));
132
+ }
133
+ if (!files.length) report.diagnostics.push({ code: "UI_NO_FILES", severity: "error",
134
+ file: "assets", pointer: "", message: "未找到 .ui.json;先确认项目根目录,或使用 lua-ui-to-json 提取。" });
135
+ report.errors = report.diagnostics.filter(d => d.severity === "error").length;
136
+ report.warnings = report.diagnostics.filter(d => d.severity === "warning").length;
137
+ report.skipped = [...skipped];
138
+ if (format === "json") console.log(JSON.stringify(report, null, 2));
139
+ else {
140
+ console.log(`${report.files} files, ${report.errors} errors, ${report.warnings} warnings`);
141
+ for (const d of report.diagnostics) console.log(`[${d.severity}] ${d.code} ${d.file}${d.pointer}: ${d.message}`);
142
+ console.log("Not verified: " + (report.skipped.join(", ") || "No documents checked"));
143
+ console.log("Static checks do not prove runtime or visual equivalence.");
144
+ }
145
+ return report.errors ? 1 : 0;
146
+ }
147
+ try { process.exitCode = main(process.argv.slice(2)); }
148
+ catch (error) { console.error(error.message); process.exitCode = 2; }