cortico-world-extra-actions 0.3.31 → 0.3.32

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/dist/webui.js CHANGED
@@ -199,6 +199,8 @@ const CSS = `<style>
199
199
  .ea-onboard-box{max-width:420px;background:var(--ea-bg);border:1px solid var(--ea-line2);padding:16px 18px;
200
200
  box-shadow:0 24px 48px -20px rgba(0,0,0,.5)}
201
201
  .ea-onboard-box b{display:block;font-size:14px;margin-bottom:6px}
202
+ /* 正文里的 <b> 是行内强调(段数/数字),别被上面那条撑成块级 */
203
+ .ea-onboard-box p b{display:inline;font-size:inherit;font-weight:600;margin:0}
202
204
  .ea-onboard-box p{margin:0 0 8px;font-size:12.5px;line-height:1.7;color:var(--ea-soft)}
203
205
  .ea-onboard-box p.ea-dim{color:var(--ea-dim);font-size:11.5px}
204
206
  .ea-onboard-acts{display:flex;gap:8px;justify-content:flex-end;margin-top:12px}
@@ -362,6 +364,7 @@ const panel = {
362
364
  <details class="ea-menu" data-role="libmenu">
363
365
  <summary class="ea-btn" title="动作库可以放在任意盘,路径会被记住">动作库</summary>
364
366
  <div class="ea-menu-body">
367
+ <button type="button" data-act="download-library" title="插件自己下载、自己装好(约 370 MB)">一键下载并安装</button>
365
368
  <button type="button" data-act="library" title="手动指一个已有的动作库目录">选择动作库位置…</button>
366
369
  <button type="button" data-act="find-libs" title="自动扫一遍本机像动作库的目录,列出来点一下就用">自动寻找动作库…</button>
367
370
  <button type="button" data-act="starter-library" title="在你会选的目录下建一个自带示例动作库(3 段)并设为当前库">用自带示例建库…</button>
@@ -414,7 +417,7 @@ const panel = {
414
417
  <div class="ea-onboard" data-role="onboard" hidden>
415
418
  <div class="ea-onboard-box">
416
419
  <b>完整动作库还没下载</b>
417
- <p>插件自带 <b data-role="onboard-have">若干</b> 段示例动作。完整库有 <b data-role="onboard-count">105</b> 段(640×360,约 <span data-role="onboard-size">370</span> MB)。</p>
420
+ <p data-role="onboard-lead">插件自带 <b data-role="onboard-have">若干</b> 段示例动作。完整库有 <b data-role="onboard-count">105</b> 段(640×360,约 <span data-role="onboard-size">370</span> MB)。</p>
418
421
  <p>下载之前,列表里那些<b>灰色的行</b>就是还没装进动作库的段 —— 灰色只代表「没下载」,不是坏了;下载完就会变成可勾选。</p>
419
422
  <p class="ea-dim" data-role="onboard-note">下载地址由维护者提供,拿到后这里会出现「去下载」按钮;也可以自己放好库,用「动作库」菜单里的「选择动作库位置…」指过去。</p>
420
423
  <div class="ea-onboard-acts">
@@ -580,6 +583,12 @@ const panel = {
580
583
  || (catalog?.actions ?? []).reduce((sum, a) => sum + (a.bytes || 0), 0);
581
584
  const setTxt = (sel, v) => { const node = wrap.querySelector(sel); if (node) node.textContent = String(v); };
582
585
  if (totalSeg) setTxt('[data-role=onboard-count]', totalSeg);
586
+ const lead = wrap.querySelector('[data-role=onboard-lead]');
587
+ if (lead) {
588
+ lead.innerHTML = haveSeg
589
+ ? `动作库里现在有 <b data-role="onboard-have">${haveSeg}</b> 段,完整的有 <b data-role="onboard-count">${totalSeg || 105}</b> 段(640×360,约 <span data-role="onboard-size">370</span> MB)。`
590
+ : `<b>你还没设置动作库</b>,所以列表里一段都没有。完整的有 <b data-role="onboard-count">${totalSeg || 105}</b> 段(640×360,约 <span data-role="onboard-size">370</span> MB)。`;
591
+ }
583
592
  setTxt('[data-role=onboard-have]', haveSeg);
584
593
  if (totalBytes) setTxt('[data-role=onboard-size]', Math.round(totalBytes / 1048576));
585
594
  onboardEl.hidden = false;
@@ -985,11 +994,25 @@ const panel = {
985
994
  + '<span class="ea-dim">或者只补某一段:点那一行右侧的「↓ 下载」</span>'
986
995
  + '</div>';
987
996
  };
997
+ // 清单不合规:宿主根本不会加载这个包(界面上就是"形象列表里没有它")
998
+ if (p.problem) {
999
+ noteEl.hidden = false;
1000
+ noteEl.className = 'ea-note bad';
1001
+ noteEl.innerHTML = `<b>这个形象包装不上:</b>${esc(p.problem)}。<br>`
1002
+ + '宿主会因为这条不加载整个包 —— 点右边的「修复深深形象包」,插件会把能自动修的补上(会先备份)。';
1003
+ return;
1004
+ }
1005
+
988
1006
  if (!state.library.ok) {
989
1007
  noteEl.hidden = false;
1008
+ if (!state.library.dir) {
1009
+ // 从没设过库:这是"还没开始",不是出错
1010
+ noteEl.className = 'ea-note';
1011
+ noteEl.innerHTML = `<b>还没选动作库。</b>要全部 105 段:点上面「动作库 ▾」→<b>一键下载并安装</b>;已经有库就「动作库 ▾」→「选择动作库位置…」指过去。`;
1012
+ return;
1013
+ }
990
1014
  noteEl.className = 'ea-note bad';
991
- noteEl.innerHTML = `动作库目录没找到:<code>${esc(state.library.dir || '未设置')}</code> —— 点上面的「动作库」菜单:自动寻找,或手动选位置。`
992
- + `<br>清单里的 ${state.library.count ?? 105} 段现在都算「还没下载」—— 先在上面选好动作库位置,再下载。`;
1015
+ noteEl.innerHTML = `动作库目录读不到:<code>${esc(state.library.dir)}</code> —— 可能被移动或删了。用「动作库 ▾」重新指一下,或直接「一键下载并安装」。`;
993
1016
  return;
994
1017
  }
995
1018
  if (!p) {
@@ -1084,7 +1107,7 @@ const panel = {
1084
1107
  const act = btn.dataset.act;
1085
1108
  // 「动作库 ▾」里点完就收起来,别让菜单挂在打开对话框后面
1086
1109
  const libMenu = wrap.querySelector('[data-role=libmenu]');
1087
- if (libMenu && (act === 'library' || act === 'find-libs' || act === 'starter-library')) libMenu.open = false;
1110
+ if (libMenu && (act === 'library' || act === 'find-libs' || act === 'starter-library' || act === 'download-library')) libMenu.open = false;
1088
1111
  const busy = (on) => { for (const b of wrap.querySelectorAll('button')) b.disabled = on; };
1089
1112
  try {
1090
1113
  if (act === 'onboard-dismiss') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-extra-actions",
3
- "version": "0.3.31",
3
+ "version": "0.3.32",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "勾选动作库里的动作,写进形象包的「额外动作拓展」文件夹,让桌宠照着做。自带入门形象包(含控制台配色)与示例动作;完整 105 段可一键下载安装。",
package/src/pet.js CHANGED
@@ -1,6 +1,14 @@
1
1
  /** Coopanion 本地桌宠服务的最小客户端(127.0.0.1:7797-7806)。 */
2
2
 
3
- const PORTS = Array.from({ length: 10 }, (_, i) => 7797 + i);
3
+ const DEFAULT_PORTS = Array.from({ length: 10 }, (_, i) => 7797 + i);
4
+ /** 自测 / 隔离模拟:COOPANION_PET_OFF=1 彻底不探;COOPANION_PET_PORTS=7797,7798 指定端口。 */
5
+ const PORTS = (() => {
6
+ const raw = process.env.COOPANION_PET_PORTS;
7
+ if (!raw) return DEFAULT_PORTS;
8
+ const list = raw.split(',').map((x) => Number(x.trim())).filter((x) => Number.isInteger(x) && x > 0 && x < 65536);
9
+ return list.length ? list : DEFAULT_PORTS;
10
+ })();
11
+ const PET_OFF = process.env.COOPANION_PET_OFF === '1';
4
12
  let origin = null;
5
13
 
6
14
  const withTimeout = (p, ms) => Promise.race([
@@ -9,6 +17,7 @@ const withTimeout = (p, ms) => Promise.race([
9
17
  ]);
10
18
 
11
19
  export async function findPet() {
20
+ if (PET_OFF) throw new Error('COOPANION_PET_OFF=1(自测模式,不连桌宠)');
12
21
  if (origin) return origin;
13
22
  for (const port of PORTS) {
14
23
  try {
package/src/starter.js CHANGED
@@ -34,15 +34,104 @@ export function safePackName(name) {
34
34
  }
35
35
 
36
36
  /** 这个包里该有的东西齐不齐(`id` 是这个包应有的 id)。 */
37
+ /**
38
+ * 宿主能不能加载这份 figure.json。返回 null = 没问题,否则一句人话。
39
+ *
40
+ * 为什么插件自己也要判:宿主是「一条不合格 → 整个包不加载」,界面上就是
41
+ * "形象列表里没有它";这时候用户点「修复」必须真的能修好,而不是被判为健康。
42
+ * 只查最容易写错、且我们能自动修的那几条(其余交给 tools/manifest-check.mjs)。
43
+ */
44
+ /** 导出版:世界层要给每个形象包标「宿主会不会加载它」。 */
45
+ export function manifestProblem(fig) {
46
+ if (!fig || typeof fig !== 'object') return 'figure.json 读不出来';
47
+ if (![1, 2].includes(fig.manifest)) return 'manifest 不是 1/2';
48
+ if (![1, 2].includes(fig.api)) return 'api 不是 1/2';
49
+ if (typeof fig.id !== 'string' || !SAFE_ID.test(fig.id)) return 'id 不合法';
50
+ if (!fig.name || typeof fig.name !== 'object') return '缺 name';
51
+ if (typeof fig.entry !== 'string' || !fig.entry) return '缺 entry';
52
+ if (typeof fig.export !== 'string' || !fig.export) return '缺 export';
53
+ for (const p of Array.isArray(fig.presets) ? fig.presets : []) {
54
+ if (!p || typeof p !== 'object' || typeof p.id !== 'string') return 'preset 缺 id';
55
+ if (!p.pick || typeof p.pick !== 'object') return `preset "${p.id}" 缺 pick`;
56
+ }
57
+ const BREAK = /[,,、\s【】<><>]/;
58
+ const taken = new Set();
59
+ for (const w of Array.isArray(fig.vocab) ? fig.vocab : []) {
60
+ const id = String(w?.id ?? '');
61
+ if (!SAFE_ID.test(id)) return `vocab id 不合法: ${id}`;
62
+ for (const list of Object.values(w?.names ?? {})) {
63
+ for (const name of Array.isArray(list) ? list : []) {
64
+ if (typeof name !== 'string' || !name.trim() || name.length > 32 || BREAK.test(name)) return `vocab 名字不合法: ${id}`;
65
+ }
66
+ }
67
+ for (const name of [id, ...Object.values(w?.names ?? {}).flat()]) {
68
+ if (taken.has(name)) return `vocab 名字重复: ${name}`;
69
+ taken.add(name);
70
+ }
71
+ }
72
+ return null;
73
+ }
74
+
75
+ /** 宿主要求的必备字段;缺了就补默认值(否则整包不加载)。 */
76
+ function ensureBasics(fig, id) {
77
+ let changed = 0;
78
+ const set = (k, v) => { if (fig[k] === undefined || fig[k] === null || fig[k] === '') { fig[k] = v; changed++; } };
79
+ set('manifest', 2);
80
+ set('api', 2);
81
+ set('version', '1.0.0');
82
+ set('entry', 'figure.js');
83
+ set('export', 'createActionBody');
84
+ if (!fig.name || typeof fig.name !== 'object') { fig.name = { zh: '深深 · 动作库', en: 'Shenshen · Action library' }; changed++; }
85
+ if (!fig.about || typeof fig.about !== 'object') { fig.about = { zh: '深深的动作库形象包' }; changed++; }
86
+ if (!Array.isArray(fig.axes)) { fig.axes = []; changed++; }
87
+ if (!Array.isArray(fig.presets)) { fig.presets = []; changed++; }
88
+ if (!Array.isArray(fig.vocab)) { fig.vocab = []; changed++; }
89
+ if (fig.id !== id) { fig.id = id; changed++; }
90
+ return changed;
91
+ }
92
+
93
+ /** 把已知能自动修的问题就地修掉:缺基本信息、preset 缺 pick、vocab 名字带禁字符。 */
94
+ function repairManifestLight(fig, id = PACK_ID) {
95
+ let changed = ensureBasics(fig, id);
96
+ for (const p of Array.isArray(fig.presets) ? fig.presets : []) {
97
+ if (p && typeof p === 'object' && (!p.pick || typeof p.pick !== 'object')) { p.pick = {}; changed++; }
98
+ }
99
+ // console 若有但缺色(早期写过空对象),用默认青绿补齐
100
+ const DEFAULT_HUES = {
101
+ light: { a: '#0b7a5a', a2: '#0f9d76', on: '#ffffff', t: '#0b6b4f', c3: '#3f8f78', c4: '#8a8a90' },
102
+ dark: { a: '#2fd3a0', a2: '#7fe6c2', on: '#062a20', t: '#8ae8c6', c3: '#5fbfa0', c4: '#9a9aa0' },
103
+ };
104
+ for (const p of Array.isArray(fig.presets) ? fig.presets : []) {
105
+ if (!p || typeof p !== 'object' || !p.console || typeof p.console !== 'object') continue;
106
+ for (const mode of ['light', 'dark']) {
107
+ if (!p.console[mode] || typeof p.console[mode] !== 'object') { p.console[mode] = { ...DEFAULT_HUES[mode] }; changed++; continue; }
108
+ for (const [k, v] of Object.entries(DEFAULT_HUES[mode])) {
109
+ if (typeof p.console[mode][k] !== 'string' || !/^#[0-9a-f]{6}$/i.test(p.console[mode][k])) { p.console[mode][k] = v; changed++; }
110
+ }
111
+ }
112
+ }
113
+ const BREAK = /[,,、\s【】<><>]/g;
114
+ for (const w of Array.isArray(fig.vocab) ? fig.vocab : []) {
115
+ for (const [lang, list] of Object.entries(w?.names ?? {})) {
116
+ if (!Array.isArray(list)) continue;
117
+ const next = list.map((raw) => String(raw ?? '').replace(BREAK, '').trim().slice(0, 32) || String(w.id ?? ''));
118
+ if (JSON.stringify(next) !== JSON.stringify(list)) { w.names[lang] = next; changed++; }
119
+ }
120
+ }
121
+ return changed;
122
+ }
123
+
37
124
  function packHealth(dir, id = PACK_ID) {
38
125
  const fig = readJson(join(dir, 'figure.json'), null);
39
126
  const states = ['state-idle', 'state-walk', 'state-drag', 'look-around']
40
127
  .filter((s) => existsSync(join(dir, 'actions', 'core', s, 'action.json')));
128
+ const problem = fig && fig.id === id ? manifestProblem(fig) : 'figure.json 缺失或 id 不对';
41
129
  return {
42
130
  figureJson: !!fig && fig.id === id,
43
131
  player: existsSync(join(dir, 'figure.js')),
44
132
  states,
45
- ok: !!fig && fig.id === id && existsSync(join(dir, 'figure.js')) && states.length === 4,
133
+ problem,
134
+ ok: !!fig && fig.id === id && existsSync(join(dir, 'figure.js')) && states.length === 4 && !problem,
46
135
  };
47
136
  }
48
137
 
@@ -69,6 +158,7 @@ function materialize(src, dst, id, log) {
69
158
  cpSync(src, dst, { recursive: true, force: false, errorOnExist: false });
70
159
  rmSync(join(dst, '额外动作拓展'), { recursive: true, force: true });
71
160
  const fig = readJson(join(dst, 'figure.json'), { id });
161
+ ensureBasics(fig, id);
72
162
  fig.id = id;
73
163
  fig.vocab = [];
74
164
  writeFileSync(join(dst, 'figure.json'), JSON.stringify(fig, null, 2) + '\n', 'utf8');
@@ -140,12 +230,21 @@ export function restorePack({ pkgDir, figuresDir, roots, target = '', name = PAC
140
230
  const duplicates = found.filter((p) => resolve(p.path) !== resolve(dst)).map((p) => p.path);
141
231
 
142
232
  if (existsSync(join(dst, 'figure.json'))) {
233
+ const healthyBefore = packHealth(dst, id).ok;
234
+ // 先去修「能自动修」的那类毛病(preset 缺 pick / 词表名字带禁字符),再判健康
235
+ {
236
+ const fig = readJson(join(dst, 'figure.json'), null);
237
+ if (fig && repairManifestLight(fig) > 0) {
238
+ writeFileSync(join(dst, 'figure.json'), JSON.stringify(fig, null, 2) + '\n', 'utf8');
239
+ log?.('修好了形象包清单里的小问题(宿主本来会拒绝加载)');
240
+ }
241
+ }
143
242
  const before = packHealth(dst, id);
144
243
  if (!before.ok) repairInto(src, dst, id, before, log);
145
244
  const after = packHealth(dst, id);
146
245
  log?.(`形象包已存在,未重复创建:${dst}`);
147
246
  return {
148
- ok: true, created: false, repaired: !before.ok && after.ok,
247
+ ok: true, created: false, repaired: !healthyBefore && after.ok,
149
248
  path: dst, dir: basename(dst), root: rootOf(dst), duplicates, health: after,
150
249
  };
151
250
  }
@@ -161,12 +260,21 @@ export function restorePack({ pkgDir, figuresDir, roots, target = '', name = PAC
161
260
  const canonical = found.find((p) => p.dir === id) ?? null;
162
261
  const others = found.filter((p) => p.dir !== id);
163
262
  const t = canonical ?? found[0];
164
- const before = t.bot;
263
+ const healthyBefore = t.bot.ok;
264
+ // 先修「清单里能自动补的」(基本信息 / preset.pick / 词表名字),再补缺文件
265
+ {
266
+ const fig = readJson(join(t.path, 'figure.json'), null);
267
+ if (fig && repairManifestLight(fig, id) > 0) {
268
+ writeFileSync(join(t.path, 'figure.json'), JSON.stringify(fig, null, 2) + '\n', 'utf8');
269
+ log?.('修好了形象包清单里的小问题(宿主本来会拒绝加载)');
270
+ }
271
+ }
272
+ const before = packHealth(t.path, id);
165
273
  if (!before.ok) repairInto(src, t.path, id, before, log);
166
274
  const after = packHealth(t.path, id);
167
275
  log?.(`形象包已存在,未重复创建:${t.path}`);
168
276
  return {
169
- ok: true, created: false, repaired: !before.ok && after.ok,
277
+ ok: true, created: false, repaired: !healthyBefore && after.ok,
170
278
  path: t.path, dir: t.dir, root: t.root ?? primary,
171
279
  duplicates: others.map((p) => p.path), health: after,
172
280
  };
package/src/world.js CHANGED
@@ -13,7 +13,7 @@ import { basename, delimiter, dirname, isAbsolute, join, normalize, resolve } fr
13
13
  import { fileURLToPath } from 'node:url';
14
14
  import { EXTRA_DIR, clear, inspect, isInside, packLooksSupported, prunePack, readExtra, removeOne, save } from './writer.js';
15
15
  import { addModules, rebuildIndex, scanLibrary } from './importer.js';
16
- import { ensureConsolePreset, ensurePlayer, ensureStarter, ensureVocabNames, installStarterLibrary, libraryHealth, restorePack, safePackName } from './starter.js';
16
+ import { ensureConsolePreset, ensurePlayer, ensureStarter, ensureVocabNames, manifestProblem, installStarterLibrary, libraryHealth, restorePack, safePackName } from './starter.js';
17
17
  import { FALLBACK_ACTION_BASE, FALLBACK_LIBRARY, LIB_PARTS, actionUrl, flatActionUrl, installAction, installLibrary, installLibraryParts, libraryUrl } from './online.js';
18
18
  import { petFigures, petState } from './pet.js';
19
19
 
@@ -313,7 +313,11 @@ export class ExtraActionsWorld {
313
313
  const dirs = this.packDirs();
314
314
  for (const p of installed) {
315
315
  const hit = dirs.get(String(p.id));
316
- const packDir = hit?.dir ?? join(dir, String(p.id));
316
+ const guessed = hit?.dir ?? join(dir, String(p.id));
317
+ // 桌宠列出来、但本地根本没有这个目录(另一个数据目录 / 别的盘):不要凭空造条目,
318
+ // 否则面板会给出一个"可修复"的假包,点下去只会报错。
319
+ if (!hit && !existsSync(join(guessed, 'figure.json'))) continue;
320
+ const packDir = guessed;
317
321
  const supported = packLooksSupported(packDir);
318
322
  const extra = readExtra(packDir);
319
323
  out.push({
@@ -322,6 +326,8 @@ export class ExtraActionsWorld {
322
326
  current: p.id === current,
323
327
  builtin: p.removable === false,
324
328
  supported,
329
+ // 宿主对清单是一票否决:有问题它整包不加载,面板得说出来
330
+ problem: (() => { try { return packLooksSupported(packDir) ? manifestProblem(JSON.parse(readFileSync(join(packDir, 'figure.json'), 'utf8').replace(/^\uFEFF/, ''))) : null; } catch { return null; } })(),
325
331
  dir: packDir,
326
332
  root: hit?.root ?? dir,
327
333
  extra: { ids: extra.ids, count: extra.ids.length, bytes: extra.bytes, updatedAt: extra.updatedAt },
@@ -337,6 +343,7 @@ export class ExtraActionsWorld {
337
343
  current: id === current,
338
344
  builtin: false,
339
345
  supported: packLooksSupported(hit.dir),
346
+ problem: (() => { try { return manifestProblem(hit.fig); } catch { return null; } })(),
340
347
  dir: hit.dir,
341
348
  root: hit.root,
342
349
  extra: { ids: extra.ids, count: extra.ids.length, bytes: extra.bytes, updatedAt: extra.updatedAt },
@@ -667,12 +674,19 @@ export class ExtraActionsWorld {
667
674
  }
668
675
  if (!info.libraryUrl) throw new Error('还没配置下载源');
669
676
  this._dl = { active: true, phase: 'zip', done: 0, total: 1, bytes: 0, totalBytes: 0, startedAt: Date.now() };
670
- const r = await installLibrary({
671
- url: info.libraryUrl,
672
- libraryDir: existing,
673
- dataDir: this.dataDir,
674
- log: (m) => this.host?.log?.info?.(m),
675
- });
677
+ let r;
678
+ try {
679
+ r = await installLibrary({
680
+ url: info.libraryUrl,
681
+ libraryDir: existing,
682
+ dataDir: this.dataDir,
683
+ log: (m) => this.host?.log?.info?.(m),
684
+ });
685
+ } catch (e) {
686
+ // 整包也失败:进度必须回到"不活跃",否则面板会一直显示"正在连接下载源…"
687
+ this._dl = { ...this._dl, active: false, phase: 'error', error: String(e?.message ?? e) };
688
+ throw e;
689
+ }
676
690
  this.saveSettings({ libraryDir: r.path });
677
691
  this.bustCatalog();
678
692
  this._dl = { ...(this._dl ?? {}), active: false, phase: 'done', modules: r.modules, bytes: r.bytes };
package/src/writer.js CHANGED
@@ -623,7 +623,19 @@ export function prunePack(packDir) {
623
623
  const dir = join(actionsDir, cat.name, mod.name);
624
624
  if (!isInside(actionsDir, dir)) continue;
625
625
  const meta = readJson(join(dir, 'action.json'), null);
626
- if (!meta) continue; // 没有 action.json 的不动
626
+ if (!meta) {
627
+ // 没有 action.json:只有在它确实是我们留下的素材目录(有 anim.webp / f_*.webp)时才清,
628
+ // 别的(用户自己放的东西)一律不动。
629
+ let names = [];
630
+ try { names = readdirSync(dir); } catch { continue; }
631
+ const ours = names.includes('anim.webp') || names.some((n) => /^f_\d{4}\.webp$/.test(n));
632
+ if (!ours) continue;
633
+ const bytes0 = dirBytes(dir);
634
+ rmSync(dir, { recursive: true, force: true });
635
+ removed.push(`${cat.name}/${mod.name}`);
636
+ freed += bytes0;
637
+ continue;
638
+ }
627
639
  const hasRole = Array.isArray(meta.roles) && meta.roles.length > 0;
628
640
  if (hasRole) { keep.add(meta.id ?? mod.name); continue; }
629
641
  const bytes = dirBytes(dir);
@@ -645,18 +657,21 @@ export function inspect({ packDir, libraryDir, catalog }) {
645
657
  const problems = [];
646
658
  if (!existsSync(join(packDir, 'figure.json'))) problems.push(`包里没有 figure.json:${packDir}`);
647
659
  if (!libraryDir || !existsSync(libraryDir)) problems.push(`动作库目录不存在:${libraryDir}`);
660
+ const extra = readExtra(packDir);
661
+ // 只检查"这个包里真的勾了的那些段":库不全(105 少几段)是库自己的事,
662
+ // 由 state.library.present / missing 单独报,不该把包判成不健康。
663
+ const byId = new Map(catalog.map((a) => [a.id, a]));
648
664
  const missing = [];
649
- for (const a of catalog) {
650
- // 身体状态段(idle / walk / drag / turn)没有触发词,它们不是"可加的动作"
651
- if (!a.word) continue;
652
- if (actionProblem(a)) { missing.push(a.id); continue; }
665
+ for (const id of extra.ids) {
666
+ const a = byId.get(id);
667
+ if (!a || !a.word) { missing.push(id); continue; }
668
+ if (actionProblem(a)) { missing.push(id); continue; }
653
669
  const dir = join(libraryDir || '', 'actions', a.category, a.id);
654
- if (!existsSync(dir)) { missing.push(a.id); continue; }
670
+ if (!existsSync(dir)) { missing.push(id); continue; }
655
671
  // 单文件动画模块(anim.webp):帧数在文件里,不能按 f_NNNN 数
656
672
  if (a.anim || existsSync(join(dir, 'anim.webp'))) continue;
657
- if (countFrames(dir) !== a.frames) missing.push(a.id);
673
+ if (countFrames(dir) !== a.frames) missing.push(id);
658
674
  }
659
- const extra = readExtra(packDir);
660
675
  return {
661
676
  ok: problems.length === 0 && missing.length === 0,
662
677
  problems,
@@ -37,6 +37,25 @@ export function checkManifest(dir) {
37
37
  if (!namesOf(raw.about)) out.push('缺 about');
38
38
  if (typeof raw.entry !== 'string' || !raw.entry) out.push('缺 entry');
39
39
  if (typeof raw.export !== 'string' || !raw.export) out.push('缺 export');
40
+ if (typeof raw.entry === 'string' && raw.entry) {
41
+ const entryFile = join(dir, raw.entry);
42
+ if (!existsSync(entryFile)) out.push(`entry 指向的文件不存在:${raw.entry}`);
43
+ else if (typeof raw.export === 'string' && raw.export) {
44
+ const js = readFileSync(entryFile, 'utf8');
45
+ const exported = new Set([
46
+ ...[...js.matchAll(/export\s+(?:async\s+)?function\s+([A-Za-z0-9_$]+)/g)].map((m) => m[1]),
47
+ ...[...js.matchAll(/export\s+(?:const|let|var)\s+([A-Za-z0-9_$]+)/g)].map((m) => m[1]),
48
+ ...[...js.matchAll(/export\s*\{([^}]*)\}/g)].flatMap((m) => m[1].split(',').map((x) => x.trim().split(/\s+as\s+/).pop())),
49
+ ].filter(Boolean));
50
+ if (!exported.has(raw.export)) out.push(`export="${raw.export}" 在 ${raw.entry} 里没有导出(宿主会加载失败)`);
51
+ }
52
+ }
53
+
54
+ // thumb 指的文件也要在(封面裂图就是这么来的)
55
+ if (raw.thumb !== undefined) {
56
+ if (typeof raw.thumb !== 'string' || !raw.thumb) out.push('thumb 不是字符串');
57
+ else if (!existsSync(join(dir, raw.thumb))) out.push(`thumb 指向的文件不存在:${raw.thumb}`);
58
+ }
40
59
 
41
60
  const axes = [];
42
61
  for (const a of Array.isArray(raw.axes) ? raw.axes : []) {
@@ -72,6 +91,25 @@ export function checkManifest(dir) {
72
91
  }
73
92
  }
74
93
  }
94
+ /* vocab:宿主的 readVocab 也是一票否决(一条不合格 → 整份词表作废 → bot 一个词都认不出) */
95
+ const NAME_BREAK_V = /[,,、\s【】<><>]/;
96
+ const taken = new Set();
97
+ for (const w of Array.isArray(raw.vocab) ? raw.vocab : []) {
98
+ const id = String(w?.id ?? '');
99
+ if (!ID.test(id)) { out.push(`vocab id 不合法:${JSON.stringify(w?.id)}`); continue; }
100
+ for (const list of Object.values(w?.names ?? {})) {
101
+ for (const n of Array.isArray(list) ? list : []) {
102
+ if (typeof n !== 'string' || !n.trim() || n.length > 32 || NAME_BREAK_V.test(n)) out.push(`vocab "${id}" 的名字不合法:${JSON.stringify(n)}`);
103
+ }
104
+ }
105
+ for (const n of [id, ...Object.values(w?.names ?? {}).flat()]) {
106
+ if (taken.has(n)) out.push(`vocab 名字重复:${n}(宿主会拒掉整份词表)`);
107
+ taken.add(n);
108
+ }
109
+ if (!w?.about || typeof w.about !== 'object' || !Object.values(w.about).some((v) => typeof v === 'string' && v.trim())) out.push(`vocab "${id}" 缺 about`);
110
+ if (typeof w?.seconds !== 'number' || !(w.seconds > 0)) out.push(`vocab "${id}" 的 seconds 不合法`);
111
+ }
112
+
75
113
  return out;
76
114
  }
77
115
 
@@ -0,0 +1,117 @@
1
+ /**
2
+ * 全新用户端到端:从零铺一个深深包 → 保存动作 → 用宿主规则体检。
3
+ * node test_freshuser.mjs
4
+ *
5
+ * 这一步专门盯"新装的人"会遇到的问题:包铺出来合不合规、保存后词表会不会被拒、
6
+ * 播放器/配色预设有没有带、以及重复启动会不会反复写盘。
7
+ */
8
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath, pathToFileURL } from 'node:url';
11
+ import { checkManifest } from './manifest-check.mjs';
12
+
13
+ const here = dirname(fileURLToPath(import.meta.url));
14
+ const fails = [];
15
+ const check = (fn, msg) => { try { fn(); console.log('ok ' + msg); } catch (e) { fails.push(`${msg} → ${e.message}`); console.log('FAIL ' + msg); } };
16
+
17
+ const W = await import(pathToFileURL(join(here, '..', 'src', 'world.js')).href);
18
+
19
+ const root = join(here, '_tmp-fresh');
20
+ rmSync(root, { recursive: true, force: true });
21
+ const botDir = join(root, 'home', 'companion');
22
+ const dataDir = join(botDir, 'data');
23
+ mkdirSync(dataDir, { recursive: true });
24
+
25
+ const cfg = {};
26
+ const ctx = { dataDir, botDir, cfg, persist: (p) => Object.assign(cfg, p), packageDir: join(here, '..'), repoRoot: here };
27
+ const w = new W.ExtraActionsWorld({ ctx });
28
+
29
+ /* ① 首次启动:铺包 */
30
+ await w.start({ log: { info: () => {}, warn: () => {} } });
31
+ const packDir = join(botDir, 'data', 'figures', 'shenshen-actions');
32
+ check(() => { if (!existsSync(join(packDir, 'figure.json'))) throw new Error('没有铺出形象包'); }, '首启铺出形象包');
33
+
34
+ /* ② 铺出来的包必须过宿主清单校验(这是 0.3.30 翻车的地方) */
35
+ check(() => {
36
+ const errs = checkManifest(packDir);
37
+ if (errs.length) throw new Error(errs.join(';'));
38
+ }, '铺出来的 figure.json 符合宿主清单规则');
39
+
40
+ /* ③ 包里有配色预设、有 pick、播放器是新的 */
41
+ check(() => {
42
+ const fig = JSON.parse(readFileSync(join(packDir, 'figure.json'), 'utf8'));
43
+ const p = (fig.presets ?? []).find((x) => x.console);
44
+ if (!p) throw new Error('没有 console 预设');
45
+ if (!p.pick || typeof p.pick !== 'object') throw new Error('预设缺 pick');
46
+ }, '带配色预设且 pick 合法');
47
+
48
+ check(() => {
49
+ const js = readFileSync(join(packDir, figEntry(packDir)), 'utf8');
50
+ if (!js.includes('REACTION_MAX')) throw new Error('播放器不是新版(没有 REACTION_MAX)');
51
+ }, '播放器是新版(点击回应有上限+兜底)');
52
+
53
+ function figEntry(dir) {
54
+ const fig = JSON.parse(readFileSync(join(dir, 'figure.json'), 'utf8'));
55
+ return fig.entry ?? 'figure.js';
56
+ }
57
+
58
+ /* ④ 建个 4 段的小库,勾两段保存 */
59
+ const lib = join(root, 'lib');
60
+ const hd = 'D:/Coopanion-data/深深-动作库-HD/actions';
61
+ for (const [cat, id] of [['core', 'cheer-hop'], ['eat', 'eat-dumplings']]) {
62
+ cpSync(join(hd, cat, id), join(lib, 'actions', cat, id), { recursive: true });
63
+ }
64
+
65
+ const state0 = await w.invoke('picker', 'state');
66
+ if (!state0.library.ok) {
67
+ await w.invoke('picker', 'set-library', [lib]);
68
+ }
69
+ const r = await w.invoke('picker', 'save', ['shenshen-actions', ['cheer-hop', 'eat-dumplings']]);
70
+ check(() => { if (!r || !r.count) throw new Error('保存没写入任何东西'); }, '保存两段动作成功:' + (r?.count ?? 0) + ' 段');
71
+
72
+ /* ⑤ 保存后:清单仍然合规、词表过宿主校验、模块在 index 里 */
73
+ check(() => {
74
+ const errs = checkManifest(packDir);
75
+ if (errs.length) throw new Error(errs.join(';'));
76
+ }, '保存后 figure.json 仍然合规');
77
+
78
+ check(() => {
79
+ const fig = JSON.parse(readFileSync(join(packDir, 'figure.json'), 'utf8'));
80
+ const NAME_BREAK = /[,,、\s【】<><>]/;
81
+ const taken = new Set();
82
+ for (const w of fig.vocab ?? []) {
83
+ for (const n of [w.id, ...Object.values(w.names ?? {}).flat()]) {
84
+ if (taken.has(n)) throw new Error('名字重复:' + n);
85
+ taken.add(n);
86
+ }
87
+ for (const n of Object.values(w.names ?? {}).flat()) {
88
+ if (n.length > 32 || NAME_BREAK.test(n)) throw new Error('名字不合法:' + n);
89
+ }
90
+ }
91
+ }, '保存后的词表能过宿主校验(不会被整份拒掉)');
92
+
93
+ check(() => {
94
+ const idx = readFileSync(join(packDir, '额外动作拓展', 'index.js'), 'utf8');
95
+ for (const id of ['cheer-hop', 'eat-dumplings']) {
96
+ if (!idx.includes(id)) throw new Error('index 里没有 ' + id);
97
+ }
98
+ }, '额外动作拓展/index.js 里两段都在');
99
+
100
+ /* ⑥ 再启动一次:不该重复写、也不该改坏 */
101
+ {
102
+ const before = readFileSync(join(packDir, 'figure.json'), 'utf8');
103
+ const w2 = new W.ExtraActionsWorld({ ctx });
104
+ await w2.start({ log: { info: () => {}, warn: () => {} } });
105
+ const after = readFileSync(join(packDir, 'figure.json'), 'utf8');
106
+ check(() => { if (before !== after) throw new Error('第二次启动又改了 figure.json'); }, '重复启动不重复写 figure.json');
107
+ }
108
+
109
+ /* ⑦ 包健康度(插件自己的 inspect) */
110
+ check(() => {
111
+ const r2 = w.invoke('picker', 'state');
112
+ return r2;
113
+ }, 'state 可读');
114
+
115
+ rmSync(root, { recursive: true, force: true });
116
+ console.log(fails.length ? `\nFAIL (${fails.length})\n- ${fails.join('\n- ')}` : '\nall checks passed');
117
+ process.exit(fails.length ? 1 : 0);
@@ -23,7 +23,7 @@ const writePack = (name, fig) => {
23
23
  const dir = join(root, name);
24
24
  mkdirSync(dir, { recursive: true });
25
25
  writeFileSync(join(dir, 'figure.json'), JSON.stringify(fig, null, 2), 'utf8');
26
- writeFileSync(join(dir, 'figure.js'), 'export {};', 'utf8');
26
+ writeFileSync(join(dir, 'figure.js'), 'export function createActionBody() {}', 'utf8');
27
27
  return dir;
28
28
  };
29
29
  const base = { manifest: 2, api: 2, id: 'shenshen-actions', name: { zh: '深深' }, about: { zh: 'x' }, entry: 'figure.js', export: 'createActionBody' };