poi-plugin-brainoff 1.0.0 → 1.0.1

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.
@@ -1,733 +1,733 @@
1
- 'use strict';
2
-
3
- // Phase A (Wave 26): fixed roster (--fix-fleet / --ships / fixedRosterIds), exclusion (--exclude) and quest-style fleet
4
- // constraints (--min-ships / --max-ships / --require-stype / --require-group / --require-flag-ship), shared by both optimizers,
5
- // cli.js and server.js. Everything here is plain data in / plain data out (no optimizer imports, so no require cycle).
6
- // Errors carry statusCode 400 (bad input / conflicting options); "the port cannot satisfy it" (422) is decided by the optimizers.
7
- const { STYPE, STYPE_ZH } = require('../engine/constants');
8
- const { matchesShipQuery, shipIdentityKey, normName, loadShipMaster } = require('../data/portLoader');
9
- const { getRemodelRootId } = require('../data/equipBonuses');
10
-
11
- const STYPE_BY_CODE = {
12
- DE: STYPE.DE, DD: STYPE.DD, CL: STYPE.CL, CLT: STYPE.CLT, CA: STYPE.CA, CAV: STYPE.CAV,
13
- CVL: STYPE.CVL, BB: STYPE.BB, FBB: STYPE.FBB, BBV: STYPE.BBV, CV: STYPE.CV, CVB: STYPE.CVB,
14
- SS: STYPE.SS, SSV: STYPE.SSV, AV: STYPE.AV, LHA: STYPE.LHA, AR: STYPE.AR, AS: STYPE.AS, CT: STYPE.CT, AO: STYPE.AO,
15
- };
16
- // Names follow maps.js routing sums (c.CVAll / c.CVBig / c.BBAll); DDE = DD + DE
17
- const STYPE_ALIASES = {
18
- CVALL: [STYPE.CV, STYPE.CVL, STYPE.CVB],
19
- CVBIG: [STYPE.CV, STYPE.CVB],
20
- BBALL: [STYPE.FBB, STYPE.BB, STYPE.BBV],
21
- DDE: [STYPE.DD, STYPE.DE],
22
- };
23
- const CODE_BY_STYPE = Object.fromEntries(Object.entries(STYPE_BY_CODE).map(([k, v]) => [v, k]));
24
- // Constraint-aware skeleton DP: maximum number of counter states (mixed radix); beyond it the optimizer falls back to filtering
25
- const DP_STATE_CAP = 1024;
26
-
27
- function fcError(message, statusCode = 400, code = 'BAD_FLEET_CONSTRAINT', details) {
28
- const err = new Error(message);
29
- err.statusCode = statusCode;
30
- err.code = code;
31
- if (details !== undefined) err.details = details;
32
- return err;
33
- }
34
- const isUnset = (v) => v === undefined || v === null || v === '';
35
- const nonEmptyList = (v) => Array.isArray(v) ? v.length > 0 : !isUnset(v);
36
- const opOk = (op, v, n) => (op === '>=' ? v >= n : op === '<=' ? v <= n : v === n);
37
- const normOp = (op) => (op === '≥' ? '>=' : op === '≤' ? '<=' : op === '==' ? '=' : op);
38
- // Full-width / unicode comparison operators -> ASCII before parsing (>= <= = ≥ ≤)
39
- const normOpText = (t) => String(t).replace(/>/g, '>').replace(/</g, '<').replace(/=/g, '=').replace(/≥/g, '>=').replace(/≤/g, '<=');
40
-
41
- // ---- Ship-name resolution (Wave 26 review P1/P2) ---------------------------------------------------------------------------
42
- // A name means a ship IDENTITY (remodel chain, shipIdentityKey), not a substring: "潮" must not match 朝潮 / 黑潮.
43
- // 1) exact normName match against the port ships' current names AND every master name of a remodel chain (start2 api_name,
44
- // wctf ja_jp / zh_cn / en_us), so 响 / Верный / 信赖, 雪风 / 丹阳, 大鲸 / 龙凤, 春日丸 / 大鹰, U-511 / 吕500, Italia / Littorio
45
- // all resolve to their chain; 2) substring match on the port ship names only when nothing matches exactly.
46
- // Only identities the port owns count; more than one owned identity = ambiguous (callers answer 400 with the candidates).
47
- let masterNameIndex = null;
48
- function getMasterNameIndex() {
49
- if (masterNameIndex) return masterNameIndex;
50
- const idx = new Map();
51
- const add = (name, id) => {
52
- const k = normName(name);
53
- if (!k) return;
54
- const key = `root:${getRemodelRootId(id) || id}`;
55
- if (!idx.has(k)) idx.set(k, new Set());
56
- idx.get(k).add(key);
57
- };
58
- try {
59
- const m = loadShipMaster();
60
- for (const [id, sh] of m.s2ById) add(sh.api_name, id);
61
- for (const [id, w] of m.wById) if (w && w.name) { add(w.name.ja_jp, id); add(w.name.zh_cn, id); add(w.name.en_us, id); }
62
- } catch (_) { /* no master data: port names only */ }
63
- masterNameIndex = idx;
64
- return idx;
65
- }
66
- const copyRank = (s) => (s.inExpedition ? 2 : s.inDock ? 1 : 0);
67
- // all port copies of an identity, best first: idle, then docked, then on expedition, then higher Lv
68
- const sortCopies = (list) => list.slice().sort((a, b) => copyRank(a) - copyRank(b) || (b.lv || 0) - (a.lv || 0) || a.rosterId - b.rosterId);
69
- function resolveNameIdentities(port, q) {
70
- const nq = normName(q);
71
- const exact = new Set();
72
- for (const sh of port.ships) if (normName(sh.name) === nq) exact.add(shipIdentityKey(sh));
73
- const mset = getMasterNameIndex().get(nq);
74
- if (mset) for (const k of mset) exact.add(k);
75
- const mode = exact.size ? 'exact' : 'substring';
76
- const keys = exact.size ? exact : new Set(port.ships.filter((sh) => matchesShipQuery(sh, q)).map((sh) => shipIdentityKey(sh)));
77
- const byKey = new Map();
78
- for (const sh of port.ships) {
79
- const k = shipIdentityKey(sh);
80
- if (!keys.has(k)) continue;
81
- if (!byKey.has(k)) byKey.set(k, []);
82
- byKey.get(k).push(sh);
83
- }
84
- const owned = [...byKey.entries()].map(([key, list]) => ({ key, copies: sortCopies(list) }));
85
- return { query: q, mode, owned };
86
- }
87
- const ambiguousError = (q, owned) => {
88
- const names = owned.map((o) => o.copies[0].name);
89
- return fcError(`舰名 "${q}" 匹配多艘不同舰娘(${names.slice(0, 5).join('、')}${names.length > 5 ? '…' : ''}),请写全名`, 400, 'SHIP_NAME_AMBIGUOUS', { candidates: names });
90
- };
91
- // exactly one owned identity, or null (not owned); throws 400 when ambiguous
92
- function resolveUniqueIdentity(port, q) {
93
- const r = resolveNameIdentities(port, q);
94
- if (r.owned.length > 1) throw ambiguousError(q, r.owned);
95
- return r.owned[0] || null;
96
- }
97
- function strictInt(v) {
98
- if (typeof v === 'number') return Number.isInteger(v) ? v : NaN;
99
- if (typeof v === 'string' && /^\s*\d+\s*$/.test(v)) return Number(v);
100
- return NaN;
101
- }
102
-
103
- const ALL_STYPE_CODES = [...Object.keys(STYPE_BY_CODE), ...Object.keys(STYPE_ALIASES)];
104
-
105
- // "DD>=4,BBV=2,CV/CVL<=1" / "DD+DE>=4" (string, or array of strings / {stypes:[codes], op, n}) ->
106
- // [{ codes, stypes, op, n, label }]. '/' and '+' both mean "sum over the listed stypes".
107
- function parseStypeExpr(input) {
108
- const bad = (t) => fcError(`无效 --require-stype 条件 "${t}"(舰种代码可选: ${ALL_STYPE_CODES.join(', ')};格式如 DD>=4,BBV=2)`, 400, 'BAD_TASK_CONSTRAINT');
109
- let terms = [];
110
- if (Array.isArray(input)) {
111
- for (const it of input) {
112
- if (typeof it === 'string') terms.push(...it.split(/[,,]/));
113
- else if (it && typeof it === 'object') {
114
- const codes = Array.isArray(it.stypes) ? it.stypes : (typeof it.stypes === 'string' ? [it.stypes] : null);
115
- const n = strictInt(it.n);
116
- if (!codes || !codes.length || codes.some((x) => typeof x !== 'string') || !Number.isInteger(n) || typeof it.op !== 'string') throw bad(JSON.stringify(it));
117
- terms.push(`${codes.join('/')}${it.op}${n}`);
118
- } else throw bad(String(it));
119
- }
120
- } else if (typeof input === 'string') {
121
- terms = input.split(/[,,]/);
122
- } else {
123
- throw bad(String(input));
124
- }
125
- terms = terms.map((t) => normOpText(t).trim()).filter(Boolean);
126
- if (!terms.length) throw bad(Array.isArray(input) ? '' : String(input));
127
- const out = [];
128
- for (const t of terms) {
129
- const m = /^([A-Za-z]+(?:\s*[/+]\s*[A-Za-z]+)*)\s*(>=|<=|==|=)\s*(\d+)$/.exec(t);
130
- if (!m) throw bad(t);
131
- const op = normOp(m[2]);
132
- const n = Number(m[3]);
133
- if (!Number.isInteger(n) || n < 0 || n > 6) throw bad(t);
134
- const codes = m[1].split(/[/+]/).map((c) => c.trim().toUpperCase());
135
- const stypes = [];
136
- for (const c of codes) {
137
- const sts = STYPE_ALIASES[c] || (STYPE_BY_CODE[c] != null ? [STYPE_BY_CODE[c]] : null);
138
- if (!sts) throw bad(t);
139
- for (const st of sts) if (!stypes.includes(st)) stypes.push(st);
140
- }
141
- out.push({ codes, stypes, op, n, label: `${m[1].replace(/\s+/g, '').toUpperCase()}${op}${n}` });
142
- }
143
- // Contradictory bounds on the same stype set (e.g. DD>=4 with DD<=2)
144
- const byKey = new Map();
145
- for (const t of out) {
146
- const key = t.stypes.slice().sort((a, b) => a - b).join(',');
147
- if (!byKey.has(key)) byKey.set(key, []);
148
- byKey.get(key).push(t);
149
- }
150
- for (const list of byKey.values()) {
151
- let lo = null, hi = null;
152
- for (const t of list) {
153
- if (t.op !== '<=' && (!lo || t.n > lo.n)) lo = t;
154
- if (t.op !== '>=' && (!hi || t.n < hi.n)) hi = t;
155
- }
156
- if (lo && hi && lo.n > hi.n) throw fcError(`舰种约束自相矛盾: ${lo.label} 与 ${hi.label}`, 400, 'BAD_TASK_CONSTRAINT');
157
- }
158
- // Cheap cross-set checks: a lower bound on a subset above an upper bound on its superset (DD>=4 with DDE<=3), and
159
- // lower bounds on pairwise disjoint sets that add up to more than 6 ships (DD>=4,CV>=3)
160
- const isSub = (a, b) => a.stypes.every((x) => b.stypes.includes(x));
161
- for (const a of out) {
162
- if (a.op === '<=') continue;
163
- for (const b of out) {
164
- if (b === a || b.op === '>=') continue;
165
- if (isSub(a, b) && a.n > b.n) throw fcError(`舰种约束自相矛盾: ${a.label} 与 ${b.label}`, 400, 'BAD_TASK_CONSTRAINT');
166
- }
167
- }
168
- const lows = out.filter((t) => t.op !== '<=' && t.n > 0).sort((a, b) => b.n - a.n);
169
- const disjoint = [];
170
- for (const t of lows) if (disjoint.every((d) => !d.stypes.some((x) => t.stypes.includes(x)))) disjoint.push(t);
171
- const sumLo = disjoint.reduce((acc, t) => acc + t.n, 0);
172
- if (sumLo > 6) throw fcError(`舰种约束自相矛盾: ${disjoint.map((t) => t.label).join(' + ')} 合计至少 ${sumLo} 艘,超过 6 艘`, 400, 'BAD_TASK_CONSTRAINT');
173
- return out;
174
- }
175
-
176
- // "阳炎|不知火|黑潮>=2" (or {names:[...], op, n}) -> { names, op, n, label }
177
- function parseGroupExpr(input) {
178
- const bad = (t) => fcError(`无效 --require-group 条件 "${t}"(格式如 "阳炎|不知火|黑潮>=2":舰名用 | 分隔,>= 时 N 为 1~6,<= / = 时为 0~6)`, 400, 'BAD_TASK_CONSTRAINT');
179
- let names, op, n, text;
180
- if (input && typeof input === 'object' && !Array.isArray(input)) {
181
- text = JSON.stringify(input);
182
- if (!Array.isArray(input.names) || input.names.some((x) => typeof x !== 'string')) throw bad(text);
183
- names = input.names.map((x) => x.trim()).filter(Boolean);
184
- op = typeof input.op === 'string' ? normOp(normOpText(input.op).trim()) : null;
185
- n = strictInt(input.n);
186
- } else if (typeof input === 'string') {
187
- text = input.trim();
188
- const m = /^(.*?)\s*(>=|<=|==|=)\s*(\d+)$/.exec(normOpText(text));
189
- if (!m || /[<>=]/.test(m[1])) throw bad(text);
190
- names = m[1].split(/[||]/).map((x) => x.trim()).filter(Boolean);
191
- op = normOp(m[2]);
192
- n = Number(m[3]);
193
- } else {
194
- throw bad(String(input));
195
- }
196
- if (!names.length || !['>=', '<=', '='].includes(op) || !Number.isInteger(n) || n < 0 || n > 6 || (op === '>=' && n < 1)) throw bad(text);
197
- names = names.filter((x, i) => names.indexOf(x) === i);
198
- return { names, op, n, label: `${names.join('|')}${op}${n}` };
199
- }
200
-
201
- function hasTaskConstraints(c = {}) {
202
- return !isUnset(c.minShips) || !isUnset(c.maxShips) || nonEmptyList(c.requireStype)
203
- || (Array.isArray(c.requireGroups) && c.requireGroups.length > 0)
204
- || (Array.isArray(c.requireFlagShip) && c.requireFlagShip.length > 0);
205
- }
206
-
207
- function flagLimitText(flagTypes = [], flagNames = []) {
208
- const parts = [];
209
- if (flagTypes.length) parts.push(flagTypes.map((t) => CODE_BY_STYPE[t] || STYPE_ZH[t] || t).join('/'));
210
- if (flagNames.length) parts.push(flagNames.join('/'));
211
- return `[${parts.join(';')}]`;
212
- }
213
-
214
- // Combined flagship predicate (flagshipTypes AND requireFlagShip); null when neither is set.
215
- // With a port, requireFlagShip names resolve to ship identities (see resolveNameIdentities); without one, substring match.
216
- function makeFlagPred(flagTypes = [], flagNames = [], port = null) {
217
- if (!flagTypes.length && !flagNames.length) return null;
218
- let nameOk = () => true;
219
- if (flagNames.length) {
220
- if (port && Array.isArray(port.ships)) {
221
- const keys = new Set();
222
- for (const q of flagNames) { const o = resolveUniqueIdentity(port, q); if (o) keys.add(o.key); }
223
- nameOk = (s) => keys.has(shipIdentityKey(s));
224
- } else {
225
- nameOk = (s) => flagNames.some((q) => matchesShipQuery(s, q));
226
- }
227
- }
228
- return (s) => !!s && (!flagTypes.length || flagTypes.includes(s.stype)) && nameOk(s);
229
- }
230
-
231
- // null when no Phase A task constraint is set (then the optimizers run exactly the pre-Wave-26 code paths).
232
- // counters: stype / group counts; flagPred: flagship predicate (flagshipTypes AND requireFlagShip).
233
- function compileTaskConstraints(c = {}, port = null) {
234
- if (!hasTaskConstraints(c)) return null;
235
- const minShips = isUnset(c.minShips) ? null : Number(c.minShips);
236
- const maxShips = isUnset(c.maxShips) ? null : Number(c.maxShips);
237
- const counters = [];
238
- const warnings = [];
239
- const stypeTerms = nonEmptyList(c.requireStype) ? parseStypeExpr(c.requireStype) : [];
240
- for (const t of stypeTerms) {
241
- const set = new Set(t.stypes);
242
- counters.push({ label: t.label, kind: 'stype', stypes: t.stypes, codes: t.codes, match: (s) => set.has(s.stype), op: t.op, n: t.n });
243
- }
244
- const groupTerms = (Array.isArray(c.requireGroups) ? c.requireGroups : []).map(parseGroupExpr);
245
- for (const t of groupTerms) {
246
- const names = t.names;
247
- let match;
248
- if (port && Array.isArray(port.ships)) {
249
- // group members are ship identities (remodel chains), never substrings of other names
250
- const keys = new Set();
251
- const unknown = [];
252
- for (const q of names) {
253
- const o = resolveUniqueIdentity(port, q);
254
- if (o) keys.add(o.key); else unknown.push(q);
255
- }
256
- if (unknown.length) warnings.push(`--require-group "${t.label}" 中的 ${unknown.join('、')} 在港区中不存在(按未持有处理)`);
257
- match = (s) => keys.has(shipIdentityKey(s));
258
- } else {
259
- match = (s) => names.some((q) => matchesShipQuery(s, q));
260
- }
261
- counters.push({ label: t.label, kind: 'group', names, match, op: t.op, n: t.n });
262
- }
263
- const flagNames = (Array.isArray(c.requireFlagShip) ? c.requireFlagShip : []).map((x) => String(x).trim()).filter(Boolean);
264
- const flagTypes = (c.flagshipTypes || []).map(Number);
265
- const flagPred = makeFlagPred(flagTypes, flagNames, port);
266
- const raw = {
267
- minShips, maxShips,
268
- requireStype: stypeTerms.map((t) => t.label),
269
- requireGroups: groupTerms.map((t) => t.label),
270
- requireFlagShip: flagNames,
271
- flagshipTypes: flagTypes,
272
- };
273
- const compiled = { minShips, maxShips, counters, flagPred, flagNames, flagTypes, raw, warnings };
274
- compiled.text = describeTaskConstraints(compiled);
275
- return compiled;
276
- }
277
-
278
- function describeTaskConstraints(compiled) {
279
- if (!compiled) return '';
280
- const parts = compiled.counters.map((ct) => ct.label);
281
- const { minShips: lo, maxShips: hi } = compiled;
282
- if (lo != null && hi != null) parts.push(lo === hi ? `${lo} 艘` : `${lo}~${hi} 艘`);
283
- else if (hi != null) parts.push(`≤${hi} 艘`);
284
- else if (lo != null) parts.push(`≥${lo} 艘`);
285
- if (compiled.flagNames && compiled.flagNames.length) parts.push(`旗舰∈${flagLimitText(compiled.flagTypes, compiled.flagNames)}`);
286
- return parts.join(', ');
287
- }
288
-
289
- // Final guard used everywhere: { ok, reasons }. checkFlag: ships[0] must satisfy the flagship predicate.
290
- function fleetSatisfies(ships, compiled, { checkFlag = true } = {}) {
291
- const reasons = [];
292
- if (!compiled) return { ok: true, reasons };
293
- const n = ships.length;
294
- if (compiled.minShips != null && n < compiled.minShips) reasons.push(`舰数 ${n} 低于 --min-ships ${compiled.minShips}`);
295
- if (compiled.maxShips != null && n > compiled.maxShips) reasons.push(`舰数 ${n} 超出 --max-ships ${compiled.maxShips}`);
296
- for (const ct of compiled.counters) {
297
- const v = ships.filter(ct.match).length;
298
- if (!opOk(ct.op, v, ct.n)) reasons.push(`${ct.label}(实际 ${v})`);
299
- }
300
- if (checkFlag && compiled.flagPred && n && !compiled.flagPred(ships[0])) {
301
- reasons.push(`旗舰 ${ships[0].name} 不满足旗舰限制 ${flagLimitText(compiled.flagTypes, compiled.flagNames)}`);
302
- }
303
- return { ok: reasons.length === 0, reasons };
304
- }
305
-
306
- const shipById = (port, id) => (port.shipByRosterId ? port.shipByRosterId.get(id) : null) || (port.ships || []).find((s) => s.rosterId === id) || null;
307
-
308
- // Fixed-roster name resolution: an exact normName match beats a substring match; a name matching several distinct identities
309
- // is ambiguous (400); among copies of one identity: idle, then docked, then on expedition, then higher Lv.
310
- function resolveFixedShipName(port, q) {
311
- const o = resolveUniqueIdentity(port, q);
312
- if (!o) throw fcError(`未在港区中找到固定阵容舰娘 "${q}"`, 400, 'FIXED_SHIP_NOT_FOUND');
313
- // every copy of the identity (e.g. 神通 Lv1 and 神通改二 Lv63) competes: idle, docked, expedition, then higher Lv
314
- return o.copies[0];
315
- }
316
-
317
- const FORM_FLAG = { fixFleet: '--fix-fleet', fixedShipNames: '--ships', fixedRosterIds: 'fixedRosterIds', fixedShips: 'fixedShips' };
318
- function fixedRosterForms(c = {}) {
319
- const forms = [];
320
- if (!isUnset(c.fixFleet)) forms.push('fixFleet');
321
- if (Array.isArray(c.fixedShipNames) ? c.fixedShipNames.length > 0 : !isUnset(c.fixedShipNames)) forms.push('fixedShipNames');
322
- if (Array.isArray(c.fixedRosterIds) ? c.fixedRosterIds.length > 0 : !isUnset(c.fixedRosterIds)) forms.push('fixedRosterIds');
323
- return forms;
324
- }
325
-
326
- // Ships of a fixed roster that bypass minLv / excludeExpedition / excludeDock / onlyHealthy (each bypass is reported)
327
- function computeExemptions(ships, c = {}) {
328
- const minLv = isUnset(c.minLv) ? 10 : Number(c.minLv);
329
- const exExp = c.excludeExpedition !== false;
330
- const exDock = c.excludeDock !== false;
331
- const out = [];
332
- for (const s of ships) {
333
- if (!(s.lv >= minLv)) out.push(`固定阵容豁免:${s.name} Lv${s.lv} 低于 minLv=${minLv}`);
334
- if (s.inExpedition && (exExp || c.onlyHealthy)) out.push(`固定阵容豁免:${s.name} 远征中(出击前需召回)`);
335
- if (s.inDock && (exDock || c.onlyHealthy)) out.push(`固定阵容豁免:${s.name} 入渠中`);
336
- if (c.onlyHealthy && s.maxHp > 0 && s.hp / s.maxHp <= 0.5) out.push(`固定阵容豁免:${s.name} 中破以下 (--healthy)`);
337
- }
338
- return out;
339
- }
340
-
341
- // null | { ships, source:'fleet'|'ships'|'rosterIds', fleetNo, lockOrder, rosterIds, exemptions }
342
- // The library-internal constraints.fixedShips (ship objects) is NOT handled here (kept unchanged for back-compat).
343
- function resolveFixedRoster(port, c = {}) {
344
- const forms = fixedRosterForms(c);
345
- if (!forms.length) return null;
346
- const legacy = Array.isArray(c.fixedShips) && c.fixedShips.length > 0;
347
- if (forms.length > 1 || legacy) {
348
- throw fcError(`冲突选项: ${[...forms, ...(legacy ? ['fixedShips'] : [])].map((f) => FORM_FLAG[f]).join(' 与 ')} 只能指定其一`, 400, 'FIXED_ROSTER_CONFLICT');
349
- }
350
- let ships;
351
- let source;
352
- let fleetNo = null;
353
- if (forms[0] === 'fixFleet') {
354
- const nFleets = Array.isArray(port.fleets) ? port.fleets.length : 0;
355
- if (!nFleets) throw fcError('港区快照中没有舰队 (fleets) 信息,无法固定阵容。请在 poi 中返回母港刷新快照。', 400, 'NO_FLEETS');
356
- const num = strictInt(c.fixFleet);
357
- if (!Number.isInteger(num) || num < 1 || num > nFleets) throw fcError(`无效舰队编号 ${String(c.fixFleet)}(当前港区可用舰队: 1~${nFleets})`, 400, 'BAD_FLEET_NO');
358
- ships = (port.fleets[num - 1].shipRosterIds || []).map((id) => shipById(port, id)).filter(Boolean);
359
- if (!ships.length) throw fcError(`第 ${num} 舰队为空,无法固定阵容`, 400, 'EMPTY_FLEET');
360
- source = 'fleet';
361
- fleetNo = num;
362
- } else if (forms[0] === 'fixedShipNames') {
363
- const names = c.fixedShipNames;
364
- if (!Array.isArray(names) || names.some((x) => typeof x !== 'string' || !x.trim())) {
365
- throw fcError(`参数 fixedShipNames 非法: ${JSON.stringify(names)}(应为 1~6 个舰名字符串)`, 400);
366
- }
367
- if (names.length > 6) throw fcError(`固定阵容最多 6 艘(收到 ${names.length} 艘)`, 400, 'FIXED_ROSTER_TOO_LONG');
368
- ships = names.map((q) => resolveFixedShipName(port, q.trim()));
369
- source = 'ships';
370
- } else {
371
- const ids = c.fixedRosterIds;
372
- if (!Array.isArray(ids)) throw fcError(`参数 fixedRosterIds 非法: ${JSON.stringify(ids)}(应为 1~6 个 rosterId 整数)`, 400);
373
- if (ids.length > 6) throw fcError(`固定阵容最多 6 艘(收到 ${ids.length} 艘)`, 400, 'FIXED_ROSTER_TOO_LONG');
374
- ships = ids.map((raw) => {
375
- const id = strictInt(raw);
376
- if (!Number.isInteger(id) || id < 1) throw fcError(`参数 fixedRosterIds 非法: ${JSON.stringify(raw)}(应为正整数 rosterId)`, 400);
377
- const s = shipById(port, id);
378
- if (!s) throw fcError(`未找到 rosterId=${id} 的舰娘`, 400, 'FIXED_SHIP_NOT_FOUND');
379
- return s;
380
- });
381
- source = 'rosterIds';
382
- }
383
- if (ships.length > 6) throw fcError(`固定阵容最多 6 艘(收到 ${ships.length} 艘)`, 400, 'FIXED_ROSTER_TOO_LONG');
384
- const seenK = new Set();
385
- const seenR = new Set();
386
- for (const s of ships) {
387
- const k = shipIdentityKey(s);
388
- if (seenK.has(k) || seenR.has(s.rosterId)) throw fcError(`固定阵容包含重复舰娘: ${s.name}`, 400, 'FIXED_ROSTER_DUPLICATE');
389
- seenK.add(k);
390
- seenR.add(s.rosterId);
391
- }
392
- return {
393
- ships,
394
- source,
395
- fleetNo,
396
- lockOrder: c.lockOrder === true,
397
- rosterIds: ships.map((s) => s.rosterId),
398
- exemptions: computeExemptions(ships, c),
399
- };
400
- }
401
-
402
- // Rotate the first ship satisfying flagPred to the front (no lock), or check ships[0] (lockOrder). Returns
403
- // { ships, rotated } or { error } (422 text).
404
- function applyFixedFlagship(ships, flagPred, lockOrder, flagTypes = [], flagNames = []) {
405
- if (!flagPred) return { ships: ships.slice(), rotated: false };
406
- const lim = flagLimitText(flagTypes, flagNames);
407
- if (lockOrder) {
408
- if (!flagPred(ships[0])) return { error: `--lock-order 锁定的旗舰 ${ships[0].name} 不满足旗舰限制 ${lim}` };
409
- return { ships: ships.slice(), rotated: false };
410
- }
411
- const idx = ships.findIndex(flagPred);
412
- if (idx < 0) return { error: `固定阵容中没有满足旗舰限制 ${lim} 的舰` };
413
- const out = ships.slice();
414
- if (idx > 0) { const [f] = out.splice(idx, 1); out.unshift(f); }
415
- return { ships: out, rotated: idx > 0 };
416
- }
417
-
418
- // Expedition ships whose gear stays in the pool for a mustInclude query: when every port ship matching the query is on
419
- // expedition, the optimizers must take an expedition copy, so that copy keeps its own gear (both optimizers use this helper,
420
- // so their warehouses stay index-identical). With onlyHealthy expedition ships are never usable -> nothing kept.
421
- function mustIncludeKeepIds(port, c = {}) {
422
- const keep = new Set();
423
- if (c.excludeExpedition === false || c.onlyHealthy) return keep;
424
- for (const q of (Array.isArray(c.mustInclude) ? c.mustInclude : [])) {
425
- const m = port.ships.filter((s) => matchesShipQuery(s, q));
426
- if (!m.length || m.some((s) => !s.inExpedition)) continue;
427
- for (const s of m) keep.add(s.rosterId);
428
- }
429
- return keep;
430
- }
431
-
432
- // Active warehouse: allWarehouse minus the gear of expedition ships that are NOT kept (fixed roster / mustInclude expedition
433
- // ships keep their own gear). Same subtraction loop as portLoader; an empty keep-set returns port.warehouse itself, so default
434
- // runs are bit-identical. excludeExpedition=false (recall mode) uses allWarehouse as before.
435
- // Phase L (design_lbas §5.2): includeLbasHeld (constraints.lbas.release) appends port.lbasItems (planes held by land bases,
436
- // never in warehouse / allWarehouse) at the END with _lbasHeld: true and _lbasUid (index into port.lbasItems), so warehouse
437
- // indices stay unchanged. heldFilter (optional predicate, e.g. NOT --ban-equip) drops held items the ships may not use
438
- // (review P2-1; the LBAS planner maps uids through _lbasUid). Absent -> as before.
439
- function buildActiveWarehouse(port, opts = {}) {
440
- const base = buildActiveWarehouseCore(port, opts);
441
- if (!opts.includeLbasHeld || !port || !Array.isArray(port.lbasItems) || !port.lbasItems.length) return base;
442
- const held = port.lbasItems.map((e, uid) => ({ ...e, _lbasHeld: true, _lbasUid: uid }));
443
- return base.concat(opts.heldFilter ? held.filter((e) => opts.heldFilter(e)) : held);
444
- }
445
- function buildActiveWarehouseCore(port, { excludeExpedition = true, keepRosterIds = null } = {}) {
446
- if (!excludeExpedition) return port.allWarehouse || port.warehouse;
447
- if (!keepRosterIds || !keepRosterIds.size || !port.allWarehouse) return port.warehouse;
448
- const warehouse = port.allWarehouse.slice();
449
- for (const s of port.ships) {
450
- if (!s.inExpedition || keepRosterIds.has(s.rosterId)) continue;
451
- const locked = s.exEquip ? [...(s.equips || []), s.exEquip] : (s.equips || []);
452
- for (const eq of locked) {
453
- if (!eq || !eq.id) continue;
454
- let idx = warehouse.findIndex((w) => w.id === eq.id && (w.lv || 0) === (eq.lv || 0) && (w.alv || 0) === (eq.alv || 0));
455
- if (idx < 0) idx = warehouse.findIndex((w) => w.id === eq.id && (w.lv || 0) === (eq.lv || 0));
456
- if (idx < 0) idx = warehouse.findIndex((w) => w.id === eq.id);
457
- if (idx >= 0) warehouse.splice(idx, 1);
458
- }
459
- }
460
- return warehouse;
461
- }
462
-
463
- // Phase L (design_lbas §5.5, addendum L4 P3): the map's sortie restrictions (mapDef.fleetLimits, e.g. 6-4 BB / CV <= 2) as a
464
- // fleet predicate for the skeleton enumeration, the ship-swap operators, race merges and the template rosters, so no candidate
465
- // ever reaches routeKit.assertFleetLimits (runMonteCarlo would throw 400 FLEET_LIMIT, also inside the pool workers).
466
- // null when the map declares no limits (every caller then skips the check: unchanged behaviour).
467
- // `partial` (Wave 33, fleetLimits min): the ships are not a whole fleet (must-include ships) -> only the maxima apply.
468
- function mapFleetLimitPred(mapDef) {
469
- if (!mapDef || !Array.isArray(mapDef.fleetLimits) || !mapDef.fleetLimits.length) return null;
470
- const RK = require('../data/routeKit');
471
- return (ships, partial) => RK.checkFleetLimits(mapDef, ships, undefined, partial).length === 0;
472
- }
473
- // Readable violation text of a fleet (null when it is legal or the map has no limits), e.g. 「戦艦級 ≤ 2(当前 3)」
474
- function fleetLimitViolationText(mapDef, ships, partial) {
475
- if (!mapDef || !Array.isArray(mapDef.fleetLimits) || !mapDef.fleetLimits.length) return null;
476
- const RK = require('../data/routeKit');
477
- const bad = RK.checkFleetLimits(mapDef, ships, undefined, partial);
478
- return bad.length ? RK.fleetLimitText(bad) : null;
479
- }
480
-
481
- // --exclude removes whole identities (every copy of the named ship); without a port it falls back to substring matching
482
- const excludeMatcher = (c = {}, port = null) => {
483
- const ex = Array.isArray(c.mustExclude) ? c.mustExclude.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()) : [];
484
- if (!ex.length) return null;
485
- if (!port || !Array.isArray(port.ships)) return (s) => ex.some((q) => matchesShipQuery(s, q));
486
- const keys = new Set();
487
- for (const q of ex) { const o = resolveUniqueIdentity(port, q); if (o) keys.add(o.key); }
488
- return (s) => keys.has(shipIdentityKey(s));
489
- };
490
-
491
- // Input validation shared by validateOptimizerConstraints (library), cli.js and server.js: throws 400 with a Chinese reason.
492
- function validateTaskAndRosterInputs(port, c = {}) {
493
- const bad = (field, v, rule) => fcError(`参数 ${field} 非法: ${JSON.stringify(v)}(${rule})`, 400);
494
- const strList = (field) => {
495
- const v = c[field];
496
- if (isUnset(v)) return [];
497
- if (!Array.isArray(v) || v.some((x) => typeof x !== 'string' || !x.trim())) throw bad(field, v, '应为舰名字符串数组');
498
- return v.map((x) => x.trim());
499
- };
500
- const incl = Array.isArray(c.mustInclude) ? c.mustInclude.filter((x) => typeof x === 'string') : [];
501
- const excl = strList('mustExclude');
502
- const exclKey = new Map(); // exclude query -> identity key
503
- for (const q of excl) {
504
- const o = resolveUniqueIdentity(port, q);
505
- if (!o) throw fcError(`未在港区中找到要排除的舰娘 "${q}"`, 400, 'EXCLUDE_NOT_FOUND');
506
- exclKey.set(q, o.key);
507
- }
508
- if (excl.length && incl.length) {
509
- for (const s of port.ships) {
510
- const iq = incl.find((q) => matchesShipQuery(s, q));
511
- const eq = iq ? excl.find((q) => exclKey.get(q) === shipIdentityKey(s)) : null;
512
- if (iq && eq) throw fcError(`冲突选项: --include "${iq}" 与 --exclude "${eq}" 指向同一舰娘(${s.name}),不能同时使用`, 400, 'INCLUDE_EXCLUDE_CONFLICT');
513
- }
514
- }
515
- for (const f of ['minShips', 'maxShips']) {
516
- if (isUnset(c[f])) continue;
517
- const n = strictInt(c[f]);
518
- if (!Number.isInteger(n) || n < 1 || n > 6) throw bad(f, c[f], '应为 1~6 的整数');
519
- }
520
- if (!isUnset(c.minShips) && !isUnset(c.maxShips) && Number(c.minShips) > Number(c.maxShips)) {
521
- throw fcError(`--min-ships ${Number(c.minShips)} 大于 --max-ships ${Number(c.maxShips)}`, 400, 'BAD_TASK_CONSTRAINT');
522
- }
523
- if (nonEmptyList(c.requireStype)) parseStypeExpr(c.requireStype);
524
- if (!isUnset(c.requireGroups)) {
525
- if (!Array.isArray(c.requireGroups)) throw bad('requireGroups', c.requireGroups, '应为数组,如 ["阳炎|不知火>=2"]');
526
- for (const g of c.requireGroups) {
527
- const t = parseGroupExpr(g);
528
- const owned = t.names.map((q) => resolveUniqueIdentity(port, q)); // throws 400 on an ambiguous name
529
- if (!owned.some(Boolean)) {
530
- throw fcError(`--require-group "${t.label}" 中的舰娘在港区均不存在`, 400, 'GROUP_NOT_FOUND');
531
- }
532
- }
533
- }
534
- for (const q of strList('requireFlagShip')) {
535
- if (!resolveUniqueIdentity(port, q)) throw fcError(`未在港区中找到旗舰限制舰娘 "${q}"`, 400, 'FLAG_SHIP_NOT_FOUND');
536
- }
537
- if (!isUnset(c.lockOrder) && typeof c.lockOrder !== 'boolean') throw bad('lockOrder', c.lockOrder, '应为 true / false');
538
- if (!isUnset(c.stage3CrossSwap) && typeof c.stage3CrossSwap !== 'boolean') throw bad('stage3CrossSwap', c.stage3CrossSwap, '应为 true / false');
539
- const fixed = resolveFixedRoster(port, c);
540
- const legacyFixed = Array.isArray(c.fixedShips) && c.fixedShips.length > 0;
541
- // (the library-internal fixedShips objects have no lock-order support: rejected rather than silently ignored)
542
- if (c.lockOrder === true && !fixed) {
543
- throw fcError(legacyFixed ? '--lock-order 不支持库内部 fixedShips,请改用 fixedRosterIds / fixedShipNames' : '--lock-order 需配合 --fix-fleet 或 --ships 使用', 400, 'LOCK_ORDER_WITHOUT_FIXED');
544
- }
545
- if (fixed) {
546
- if (incl.length) throw fcError('冲突选项: 固定阵容 (--fix-fleet/--ships) 已确定全部舰娘,不能再用 --include', 400, 'FIXED_INCLUDE_CONFLICT');
547
- for (const q of excl) {
548
- const hit = fixed.ships.find((s) => exclKey.get(q) === shipIdentityKey(s));
549
- if (hit) throw fcError(`冲突选项: --exclude "${q}" 指向固定阵容中的舰娘(${hit.name})`, 400, 'FIXED_EXCLUDE_CONFLICT');
550
- }
551
- }
552
- return { fixed };
553
- }
554
-
555
- // Why a port ship is not in the usable pool (for 422 reasons); null = it is usable
556
- function filteredReason(s, c, minLv, exclHit) {
557
- if (exclHit && exclHit(s)) return '被 --exclude 排除';
558
- if (c.onlyHealthy && (s.inDock || s.inExpedition || s.hp / s.maxHp <= 0.5)) return '被 --healthy 排除';
559
- if (c.excludeExpedition !== false && s.inExpedition) return '远征中';
560
- if (c.excludeDock !== false && s.inDock) return '入渠中';
561
- if (!(s.lv >= minLv)) return `被 minLv=${minLv} 排除`;
562
- return null;
563
- }
564
-
565
- // "BBV=2:可用航战 0 艘" / "吹雪|白雪>=3:可用 2 艘(另有 深雪 Lv6、初雪 Lv1 被 minLv=10 排除)"
566
- function explainCounterShortfall(port, ct, available, usableShips, c = {}, minLv = 10) {
567
- const usableKeys = new Set(usableShips.map((s) => shipIdentityKey(s)));
568
- const exclHit = excludeMatcher(c, port);
569
- const groups = new Map();
570
- const seen = new Set();
571
- for (const s of port.ships) {
572
- if (!ct.match(s)) continue;
573
- const k = shipIdentityKey(s);
574
- if (usableKeys.has(k) || seen.has(k)) continue;
575
- const r = filteredReason(s, c, minLv, exclHit);
576
- if (!r) continue;
577
- seen.add(k);
578
- if (!groups.has(r)) groups.set(r, []);
579
- groups.get(r).push(`${s.name} Lv${s.lv}`);
580
- }
581
- const extra = [...groups.entries()].map(([r, list]) => `${list.slice(0, 6).join('、')}${list.length > 6 ? ` 等 ${list.length} 艘` : ''} ${r}`).join(';');
582
- const what = ct.kind === 'stype' ? `可用${ct.stypes.map((st) => STYPE_ZH[st] || st).join('/')} ${available} 艘` : `可用 ${available} 艘`;
583
- return { text: `${ct.label}:${what}${extra ? `(另有 ${extra})` : ''}`, minLvFiltered: [...groups.keys()].some((r) => r.startsWith('被 minLv')) };
584
- }
585
-
586
- // Constraint-aware skeleton DP (exact counts + deterministic unranking over per-bucket take counts).
587
- // bkSizes[b] = ships in bucket b; bkMatch[b][i] = bucket b counts toward counter i (uniform per bucket: stype + group/flag
588
- // mask are part of the bucket key); counters = [{op, n}] (>= saturates at n, <= / = drop transitions above n);
589
- // c0vals = counter values already contributed by locked ships. Mixed-radix state c; S = prod(n_i + 1) (null above stateCap).
590
- // dp[b][r][k][c] = number of ways to pick r ships from buckets b..B-1 using exactly k buckets, ending in a satisfied state.
591
- // With no counters (S = 1) the numbers and the unranking equal the unconstrained DP exactly.
592
- function createConstrainedEnumerator(bkSizes, bkMatch, rem, counters, c0vals = [], stateCap = DP_STATE_CAP) {
593
- const dims = counters.map((ct) => ct.n + 1);
594
- const radix = [];
595
- let S = 1;
596
- for (const d of dims) {
597
- radix.push(S);
598
- S *= d;
599
- if (S > stateCap) return null;
600
- }
601
- const B = bkSizes.length;
602
- const maxK = Math.min(B, rem);
603
- const K1 = maxK + 1;
604
- const at = (r, k, c) => (r * K1 + k) * S + c;
605
- let c0 = 0;
606
- let infeasible = false;
607
- counters.forEach((ct, i) => {
608
- let v = c0vals[i] || 0;
609
- if (ct.op === '>=') v = Math.min(v, ct.n);
610
- else if (v > ct.n) infeasible = true;
611
- c0 += Math.min(v, ct.n) * radix[i];
612
- });
613
- const sat = new Uint8Array(S);
614
- for (let c = 0; c < S; c++) {
615
- let ok = true;
616
- for (let i = 0; i < counters.length && ok; i++) {
617
- const v = Math.floor(c / radix[i]) % dims[i];
618
- if (counters[i].op === '>=' ? v < counters[i].n : counters[i].op === '=' ? v !== counters[i].n : false) ok = false;
619
- }
620
- sat[c] = ok ? 1 : 0;
621
- }
622
- const adv = new Array(B);
623
- for (let b = 0; b < B; b++) {
624
- const cap = Math.min(rem, bkSizes[b]);
625
- adv[b] = [null];
626
- for (let take = 1; take <= cap; take++) {
627
- const t = new Int32Array(S);
628
- for (let c = 0; c < S; c++) {
629
- let nc = c;
630
- let ok = true;
631
- for (let i = 0; i < counters.length; i++) {
632
- if (!bkMatch[b][i]) continue;
633
- const v = Math.floor(c / radix[i]) % dims[i];
634
- let nv = v + take;
635
- if (counters[i].op === '>=') nv = Math.min(nv, counters[i].n);
636
- else if (nv > counters[i].n) { ok = false; break; }
637
- nc += (nv - v) * radix[i];
638
- }
639
- t[c] = ok ? nc : -1;
640
- }
641
- adv[b].push(t);
642
- }
643
- }
644
- const size = (rem + 1) * K1 * S;
645
- const dp = new Array(B + 1);
646
- dp[B] = new Float64Array(size);
647
- for (let c = 0; c < S; c++) if (sat[c]) dp[B][at(0, 0, c)] = 1;
648
- for (let b = B - 1; b >= 0; b--) {
649
- const nx = dp[b + 1];
650
- const cur = new Float64Array(size);
651
- const cap = adv[b].length - 1;
652
- for (let r = 0; r <= rem; r++) {
653
- for (let k = 0; k <= maxK; k++) {
654
- for (let c = 0; c < S; c++) {
655
- let ways = nx[at(r, k, c)]; // take = 0
656
- if (k > 0) {
657
- const maxTake = Math.min(cap, r);
658
- for (let take = 1; take <= maxTake; take++) {
659
- const c2 = adv[b][take][c];
660
- if (c2 < 0) continue;
661
- ways += nx[at(r - take, k - 1, c2)];
662
- if (ways > 1e12) { ways = 1e12; break; }
663
- }
664
- }
665
- cur[at(r, k, c)] = ways;
666
- }
667
- }
668
- }
669
- dp[b] = cur;
670
- }
671
- const total = (k) => (infeasible || k < 1 || k > maxK ? 0 : dp[0][at(rem, k, c0)]);
672
- let totalAll = 0;
673
- for (let k = 1; k <= maxK; k++) totalAll += total(k);
674
- // rank-th combination (0-based) using exactly targetK buckets -> per-bucket take counts
675
- const unrank = (rank, targetK) => {
676
- const takes = new Array(B).fill(0);
677
- let idx = rank;
678
- let r = rem;
679
- let kRem = targetK;
680
- let c = c0;
681
- for (let b = 0; b < B && r > 0; b++) {
682
- const w0 = dp[b + 1][at(r, kRem, c)];
683
- if (idx < w0) continue;
684
- idx -= w0;
685
- const maxTake = Math.min(r, adv[b].length - 1);
686
- for (let take = 1; take <= maxTake; take++) {
687
- const c2 = adv[b][take][c];
688
- const w = (kRem > 0 && c2 >= 0) ? dp[b + 1][at(r - take, kRem - 1, c2)] : 0;
689
- if (idx < w) {
690
- takes[b] = take;
691
- r -= take;
692
- kRem -= 1;
693
- c = c2;
694
- break;
695
- }
696
- idx -= w;
697
- }
698
- }
699
- return takes;
700
- };
701
- return { S, maxK, total, totalAll, unrank, infeasible };
702
- }
703
-
704
- module.exports = {
705
- STYPE_BY_CODE,
706
- STYPE_ALIASES,
707
- CODE_BY_STYPE,
708
- DP_STATE_CAP,
709
- parseStypeExpr,
710
- parseGroupExpr,
711
- hasTaskConstraints,
712
- compileTaskConstraints,
713
- describeTaskConstraints,
714
- flagLimitText,
715
- makeFlagPred,
716
- fleetSatisfies,
717
- resolveFixedRoster,
718
- resolveFixedShipName,
719
- resolveNameIdentities,
720
- resolveUniqueIdentity,
721
- fixedRosterForms,
722
- computeExemptions,
723
- applyFixedFlagship,
724
- mustIncludeKeepIds,
725
- buildActiveWarehouse,
726
- mapFleetLimitPred,
727
- fleetLimitViolationText,
728
- excludeMatcher,
729
- validateTaskAndRosterInputs,
730
- explainCounterShortfall,
731
- createConstrainedEnumerator,
732
- opOk,
733
- };
1
+ 'use strict';
2
+
3
+ // Phase A (Wave 26): fixed roster (--fix-fleet / --ships / fixedRosterIds), exclusion (--exclude) and quest-style fleet
4
+ // constraints (--min-ships / --max-ships / --require-stype / --require-group / --require-flag-ship), shared by both optimizers,
5
+ // cli.js and server.js. Everything here is plain data in / plain data out (no optimizer imports, so no require cycle).
6
+ // Errors carry statusCode 400 (bad input / conflicting options); "the port cannot satisfy it" (422) is decided by the optimizers.
7
+ const { STYPE, STYPE_ZH } = require('../engine/constants');
8
+ const { matchesShipQuery, shipIdentityKey, normName, loadShipMaster } = require('../data/portLoader');
9
+ const { getRemodelRootId } = require('../data/equipBonuses');
10
+
11
+ const STYPE_BY_CODE = {
12
+ DE: STYPE.DE, DD: STYPE.DD, CL: STYPE.CL, CLT: STYPE.CLT, CA: STYPE.CA, CAV: STYPE.CAV,
13
+ CVL: STYPE.CVL, BB: STYPE.BB, FBB: STYPE.FBB, BBV: STYPE.BBV, CV: STYPE.CV, CVB: STYPE.CVB,
14
+ SS: STYPE.SS, SSV: STYPE.SSV, AV: STYPE.AV, LHA: STYPE.LHA, AR: STYPE.AR, AS: STYPE.AS, CT: STYPE.CT, AO: STYPE.AO,
15
+ };
16
+ // Names follow maps.js routing sums (c.CVAll / c.CVBig / c.BBAll); DDE = DD + DE
17
+ const STYPE_ALIASES = {
18
+ CVALL: [STYPE.CV, STYPE.CVL, STYPE.CVB],
19
+ CVBIG: [STYPE.CV, STYPE.CVB],
20
+ BBALL: [STYPE.FBB, STYPE.BB, STYPE.BBV],
21
+ DDE: [STYPE.DD, STYPE.DE],
22
+ };
23
+ const CODE_BY_STYPE = Object.fromEntries(Object.entries(STYPE_BY_CODE).map(([k, v]) => [v, k]));
24
+ // Constraint-aware skeleton DP: maximum number of counter states (mixed radix); beyond it the optimizer falls back to filtering
25
+ const DP_STATE_CAP = 1024;
26
+
27
+ function fcError(message, statusCode = 400, code = 'BAD_FLEET_CONSTRAINT', details) {
28
+ const err = new Error(message);
29
+ err.statusCode = statusCode;
30
+ err.code = code;
31
+ if (details !== undefined) err.details = details;
32
+ return err;
33
+ }
34
+ const isUnset = (v) => v === undefined || v === null || v === '';
35
+ const nonEmptyList = (v) => Array.isArray(v) ? v.length > 0 : !isUnset(v);
36
+ const opOk = (op, v, n) => (op === '>=' ? v >= n : op === '<=' ? v <= n : v === n);
37
+ const normOp = (op) => (op === '≥' ? '>=' : op === '≤' ? '<=' : op === '==' ? '=' : op);
38
+ // Full-width / unicode comparison operators -> ASCII before parsing (>= <= = ≥ ≤)
39
+ const normOpText = (t) => String(t).replace(/>/g, '>').replace(/</g, '<').replace(/=/g, '=').replace(/≥/g, '>=').replace(/≤/g, '<=');
40
+
41
+ // ---- Ship-name resolution (Wave 26 review P1/P2) ---------------------------------------------------------------------------
42
+ // A name means a ship IDENTITY (remodel chain, shipIdentityKey), not a substring: "潮" must not match 朝潮 / 黑潮.
43
+ // 1) exact normName match against the port ships' current names AND every master name of a remodel chain (start2 api_name,
44
+ // wctf ja_jp / zh_cn / en_us), so 响 / Верный / 信赖, 雪风 / 丹阳, 大鲸 / 龙凤, 春日丸 / 大鹰, U-511 / 吕500, Italia / Littorio
45
+ // all resolve to their chain; 2) substring match on the port ship names only when nothing matches exactly.
46
+ // Only identities the port owns count; more than one owned identity = ambiguous (callers answer 400 with the candidates).
47
+ let masterNameIndex = null;
48
+ function getMasterNameIndex() {
49
+ if (masterNameIndex) return masterNameIndex;
50
+ const idx = new Map();
51
+ const add = (name, id) => {
52
+ const k = normName(name);
53
+ if (!k) return;
54
+ const key = `root:${getRemodelRootId(id) || id}`;
55
+ if (!idx.has(k)) idx.set(k, new Set());
56
+ idx.get(k).add(key);
57
+ };
58
+ try {
59
+ const m = loadShipMaster();
60
+ for (const [id, sh] of m.s2ById) add(sh.api_name, id);
61
+ for (const [id, w] of m.wById) if (w && w.name) { add(w.name.ja_jp, id); add(w.name.zh_cn, id); add(w.name.en_us, id); }
62
+ } catch (_) { /* no master data: port names only */ }
63
+ masterNameIndex = idx;
64
+ return idx;
65
+ }
66
+ const copyRank = (s) => (s.inExpedition ? 2 : s.inDock ? 1 : 0);
67
+ // all port copies of an identity, best first: idle, then docked, then on expedition, then higher Lv
68
+ const sortCopies = (list) => list.slice().sort((a, b) => copyRank(a) - copyRank(b) || (b.lv || 0) - (a.lv || 0) || a.rosterId - b.rosterId);
69
+ function resolveNameIdentities(port, q) {
70
+ const nq = normName(q);
71
+ const exact = new Set();
72
+ for (const sh of port.ships) if (normName(sh.name) === nq) exact.add(shipIdentityKey(sh));
73
+ const mset = getMasterNameIndex().get(nq);
74
+ if (mset) for (const k of mset) exact.add(k);
75
+ const mode = exact.size ? 'exact' : 'substring';
76
+ const keys = exact.size ? exact : new Set(port.ships.filter((sh) => matchesShipQuery(sh, q)).map((sh) => shipIdentityKey(sh)));
77
+ const byKey = new Map();
78
+ for (const sh of port.ships) {
79
+ const k = shipIdentityKey(sh);
80
+ if (!keys.has(k)) continue;
81
+ if (!byKey.has(k)) byKey.set(k, []);
82
+ byKey.get(k).push(sh);
83
+ }
84
+ const owned = [...byKey.entries()].map(([key, list]) => ({ key, copies: sortCopies(list) }));
85
+ return { query: q, mode, owned };
86
+ }
87
+ const ambiguousError = (q, owned) => {
88
+ const names = owned.map((o) => o.copies[0].name);
89
+ return fcError(`舰名 "${q}" 匹配多艘不同舰娘(${names.slice(0, 5).join('、')}${names.length > 5 ? '…' : ''}),请写全名`, 400, 'SHIP_NAME_AMBIGUOUS', { candidates: names });
90
+ };
91
+ // exactly one owned identity, or null (not owned); throws 400 when ambiguous
92
+ function resolveUniqueIdentity(port, q) {
93
+ const r = resolveNameIdentities(port, q);
94
+ if (r.owned.length > 1) throw ambiguousError(q, r.owned);
95
+ return r.owned[0] || null;
96
+ }
97
+ function strictInt(v) {
98
+ if (typeof v === 'number') return Number.isInteger(v) ? v : NaN;
99
+ if (typeof v === 'string' && /^\s*\d+\s*$/.test(v)) return Number(v);
100
+ return NaN;
101
+ }
102
+
103
+ const ALL_STYPE_CODES = [...Object.keys(STYPE_BY_CODE), ...Object.keys(STYPE_ALIASES)];
104
+
105
+ // "DD>=4,BBV=2,CV/CVL<=1" / "DD+DE>=4" (string, or array of strings / {stypes:[codes], op, n}) ->
106
+ // [{ codes, stypes, op, n, label }]. '/' and '+' both mean "sum over the listed stypes".
107
+ function parseStypeExpr(input) {
108
+ const bad = (t) => fcError(`无效 --require-stype 条件 "${t}"(舰种代码可选: ${ALL_STYPE_CODES.join(', ')};格式如 DD>=4,BBV=2)`, 400, 'BAD_TASK_CONSTRAINT');
109
+ let terms = [];
110
+ if (Array.isArray(input)) {
111
+ for (const it of input) {
112
+ if (typeof it === 'string') terms.push(...it.split(/[,,]/));
113
+ else if (it && typeof it === 'object') {
114
+ const codes = Array.isArray(it.stypes) ? it.stypes : (typeof it.stypes === 'string' ? [it.stypes] : null);
115
+ const n = strictInt(it.n);
116
+ if (!codes || !codes.length || codes.some((x) => typeof x !== 'string') || !Number.isInteger(n) || typeof it.op !== 'string') throw bad(JSON.stringify(it));
117
+ terms.push(`${codes.join('/')}${it.op}${n}`);
118
+ } else throw bad(String(it));
119
+ }
120
+ } else if (typeof input === 'string') {
121
+ terms = input.split(/[,,]/);
122
+ } else {
123
+ throw bad(String(input));
124
+ }
125
+ terms = terms.map((t) => normOpText(t).trim()).filter(Boolean);
126
+ if (!terms.length) throw bad(Array.isArray(input) ? '' : String(input));
127
+ const out = [];
128
+ for (const t of terms) {
129
+ const m = /^([A-Za-z]+(?:\s*[/+]\s*[A-Za-z]+)*)\s*(>=|<=|==|=)\s*(\d+)$/.exec(t);
130
+ if (!m) throw bad(t);
131
+ const op = normOp(m[2]);
132
+ const n = Number(m[3]);
133
+ if (!Number.isInteger(n) || n < 0 || n > 6) throw bad(t);
134
+ const codes = m[1].split(/[/+]/).map((c) => c.trim().toUpperCase());
135
+ const stypes = [];
136
+ for (const c of codes) {
137
+ const sts = STYPE_ALIASES[c] || (STYPE_BY_CODE[c] != null ? [STYPE_BY_CODE[c]] : null);
138
+ if (!sts) throw bad(t);
139
+ for (const st of sts) if (!stypes.includes(st)) stypes.push(st);
140
+ }
141
+ out.push({ codes, stypes, op, n, label: `${m[1].replace(/\s+/g, '').toUpperCase()}${op}${n}` });
142
+ }
143
+ // Contradictory bounds on the same stype set (e.g. DD>=4 with DD<=2)
144
+ const byKey = new Map();
145
+ for (const t of out) {
146
+ const key = t.stypes.slice().sort((a, b) => a - b).join(',');
147
+ if (!byKey.has(key)) byKey.set(key, []);
148
+ byKey.get(key).push(t);
149
+ }
150
+ for (const list of byKey.values()) {
151
+ let lo = null, hi = null;
152
+ for (const t of list) {
153
+ if (t.op !== '<=' && (!lo || t.n > lo.n)) lo = t;
154
+ if (t.op !== '>=' && (!hi || t.n < hi.n)) hi = t;
155
+ }
156
+ if (lo && hi && lo.n > hi.n) throw fcError(`舰种约束自相矛盾: ${lo.label} 与 ${hi.label}`, 400, 'BAD_TASK_CONSTRAINT');
157
+ }
158
+ // Cheap cross-set checks: a lower bound on a subset above an upper bound on its superset (DD>=4 with DDE<=3), and
159
+ // lower bounds on pairwise disjoint sets that add up to more than 6 ships (DD>=4,CV>=3)
160
+ const isSub = (a, b) => a.stypes.every((x) => b.stypes.includes(x));
161
+ for (const a of out) {
162
+ if (a.op === '<=') continue;
163
+ for (const b of out) {
164
+ if (b === a || b.op === '>=') continue;
165
+ if (isSub(a, b) && a.n > b.n) throw fcError(`舰种约束自相矛盾: ${a.label} 与 ${b.label}`, 400, 'BAD_TASK_CONSTRAINT');
166
+ }
167
+ }
168
+ const lows = out.filter((t) => t.op !== '<=' && t.n > 0).sort((a, b) => b.n - a.n);
169
+ const disjoint = [];
170
+ for (const t of lows) if (disjoint.every((d) => !d.stypes.some((x) => t.stypes.includes(x)))) disjoint.push(t);
171
+ const sumLo = disjoint.reduce((acc, t) => acc + t.n, 0);
172
+ if (sumLo > 6) throw fcError(`舰种约束自相矛盾: ${disjoint.map((t) => t.label).join(' + ')} 合计至少 ${sumLo} 艘,超过 6 艘`, 400, 'BAD_TASK_CONSTRAINT');
173
+ return out;
174
+ }
175
+
176
+ // "阳炎|不知火|黑潮>=2" (or {names:[...], op, n}) -> { names, op, n, label }
177
+ function parseGroupExpr(input) {
178
+ const bad = (t) => fcError(`无效 --require-group 条件 "${t}"(格式如 "阳炎|不知火|黑潮>=2":舰名用 | 分隔,>= 时 N 为 1~6,<= / = 时为 0~6)`, 400, 'BAD_TASK_CONSTRAINT');
179
+ let names, op, n, text;
180
+ if (input && typeof input === 'object' && !Array.isArray(input)) {
181
+ text = JSON.stringify(input);
182
+ if (!Array.isArray(input.names) || input.names.some((x) => typeof x !== 'string')) throw bad(text);
183
+ names = input.names.map((x) => x.trim()).filter(Boolean);
184
+ op = typeof input.op === 'string' ? normOp(normOpText(input.op).trim()) : null;
185
+ n = strictInt(input.n);
186
+ } else if (typeof input === 'string') {
187
+ text = input.trim();
188
+ const m = /^(.*?)\s*(>=|<=|==|=)\s*(\d+)$/.exec(normOpText(text));
189
+ if (!m || /[<>=]/.test(m[1])) throw bad(text);
190
+ names = m[1].split(/[||]/).map((x) => x.trim()).filter(Boolean);
191
+ op = normOp(m[2]);
192
+ n = Number(m[3]);
193
+ } else {
194
+ throw bad(String(input));
195
+ }
196
+ if (!names.length || !['>=', '<=', '='].includes(op) || !Number.isInteger(n) || n < 0 || n > 6 || (op === '>=' && n < 1)) throw bad(text);
197
+ names = names.filter((x, i) => names.indexOf(x) === i);
198
+ return { names, op, n, label: `${names.join('|')}${op}${n}` };
199
+ }
200
+
201
+ function hasTaskConstraints(c = {}) {
202
+ return !isUnset(c.minShips) || !isUnset(c.maxShips) || nonEmptyList(c.requireStype)
203
+ || (Array.isArray(c.requireGroups) && c.requireGroups.length > 0)
204
+ || (Array.isArray(c.requireFlagShip) && c.requireFlagShip.length > 0);
205
+ }
206
+
207
+ function flagLimitText(flagTypes = [], flagNames = []) {
208
+ const parts = [];
209
+ if (flagTypes.length) parts.push(flagTypes.map((t) => CODE_BY_STYPE[t] || STYPE_ZH[t] || t).join('/'));
210
+ if (flagNames.length) parts.push(flagNames.join('/'));
211
+ return `[${parts.join(';')}]`;
212
+ }
213
+
214
+ // Combined flagship predicate (flagshipTypes AND requireFlagShip); null when neither is set.
215
+ // With a port, requireFlagShip names resolve to ship identities (see resolveNameIdentities); without one, substring match.
216
+ function makeFlagPred(flagTypes = [], flagNames = [], port = null) {
217
+ if (!flagTypes.length && !flagNames.length) return null;
218
+ let nameOk = () => true;
219
+ if (flagNames.length) {
220
+ if (port && Array.isArray(port.ships)) {
221
+ const keys = new Set();
222
+ for (const q of flagNames) { const o = resolveUniqueIdentity(port, q); if (o) keys.add(o.key); }
223
+ nameOk = (s) => keys.has(shipIdentityKey(s));
224
+ } else {
225
+ nameOk = (s) => flagNames.some((q) => matchesShipQuery(s, q));
226
+ }
227
+ }
228
+ return (s) => !!s && (!flagTypes.length || flagTypes.includes(s.stype)) && nameOk(s);
229
+ }
230
+
231
+ // null when no Phase A task constraint is set (then the optimizers run exactly the pre-Wave-26 code paths).
232
+ // counters: stype / group counts; flagPred: flagship predicate (flagshipTypes AND requireFlagShip).
233
+ function compileTaskConstraints(c = {}, port = null) {
234
+ if (!hasTaskConstraints(c)) return null;
235
+ const minShips = isUnset(c.minShips) ? null : Number(c.minShips);
236
+ const maxShips = isUnset(c.maxShips) ? null : Number(c.maxShips);
237
+ const counters = [];
238
+ const warnings = [];
239
+ const stypeTerms = nonEmptyList(c.requireStype) ? parseStypeExpr(c.requireStype) : [];
240
+ for (const t of stypeTerms) {
241
+ const set = new Set(t.stypes);
242
+ counters.push({ label: t.label, kind: 'stype', stypes: t.stypes, codes: t.codes, match: (s) => set.has(s.stype), op: t.op, n: t.n });
243
+ }
244
+ const groupTerms = (Array.isArray(c.requireGroups) ? c.requireGroups : []).map(parseGroupExpr);
245
+ for (const t of groupTerms) {
246
+ const names = t.names;
247
+ let match;
248
+ if (port && Array.isArray(port.ships)) {
249
+ // group members are ship identities (remodel chains), never substrings of other names
250
+ const keys = new Set();
251
+ const unknown = [];
252
+ for (const q of names) {
253
+ const o = resolveUniqueIdentity(port, q);
254
+ if (o) keys.add(o.key); else unknown.push(q);
255
+ }
256
+ if (unknown.length) warnings.push(`--require-group "${t.label}" 中的 ${unknown.join('、')} 在港区中不存在(按未持有处理)`);
257
+ match = (s) => keys.has(shipIdentityKey(s));
258
+ } else {
259
+ match = (s) => names.some((q) => matchesShipQuery(s, q));
260
+ }
261
+ counters.push({ label: t.label, kind: 'group', names, match, op: t.op, n: t.n });
262
+ }
263
+ const flagNames = (Array.isArray(c.requireFlagShip) ? c.requireFlagShip : []).map((x) => String(x).trim()).filter(Boolean);
264
+ const flagTypes = (c.flagshipTypes || []).map(Number);
265
+ const flagPred = makeFlagPred(flagTypes, flagNames, port);
266
+ const raw = {
267
+ minShips, maxShips,
268
+ requireStype: stypeTerms.map((t) => t.label),
269
+ requireGroups: groupTerms.map((t) => t.label),
270
+ requireFlagShip: flagNames,
271
+ flagshipTypes: flagTypes,
272
+ };
273
+ const compiled = { minShips, maxShips, counters, flagPred, flagNames, flagTypes, raw, warnings };
274
+ compiled.text = describeTaskConstraints(compiled);
275
+ return compiled;
276
+ }
277
+
278
+ function describeTaskConstraints(compiled) {
279
+ if (!compiled) return '';
280
+ const parts = compiled.counters.map((ct) => ct.label);
281
+ const { minShips: lo, maxShips: hi } = compiled;
282
+ if (lo != null && hi != null) parts.push(lo === hi ? `${lo} 艘` : `${lo}~${hi} 艘`);
283
+ else if (hi != null) parts.push(`≤${hi} 艘`);
284
+ else if (lo != null) parts.push(`≥${lo} 艘`);
285
+ if (compiled.flagNames && compiled.flagNames.length) parts.push(`旗舰∈${flagLimitText(compiled.flagTypes, compiled.flagNames)}`);
286
+ return parts.join(', ');
287
+ }
288
+
289
+ // Final guard used everywhere: { ok, reasons }. checkFlag: ships[0] must satisfy the flagship predicate.
290
+ function fleetSatisfies(ships, compiled, { checkFlag = true } = {}) {
291
+ const reasons = [];
292
+ if (!compiled) return { ok: true, reasons };
293
+ const n = ships.length;
294
+ if (compiled.minShips != null && n < compiled.minShips) reasons.push(`舰数 ${n} 低于 --min-ships ${compiled.minShips}`);
295
+ if (compiled.maxShips != null && n > compiled.maxShips) reasons.push(`舰数 ${n} 超出 --max-ships ${compiled.maxShips}`);
296
+ for (const ct of compiled.counters) {
297
+ const v = ships.filter(ct.match).length;
298
+ if (!opOk(ct.op, v, ct.n)) reasons.push(`${ct.label}(实际 ${v})`);
299
+ }
300
+ if (checkFlag && compiled.flagPred && n && !compiled.flagPred(ships[0])) {
301
+ reasons.push(`旗舰 ${ships[0].name} 不满足旗舰限制 ${flagLimitText(compiled.flagTypes, compiled.flagNames)}`);
302
+ }
303
+ return { ok: reasons.length === 0, reasons };
304
+ }
305
+
306
+ const shipById = (port, id) => (port.shipByRosterId ? port.shipByRosterId.get(id) : null) || (port.ships || []).find((s) => s.rosterId === id) || null;
307
+
308
+ // Fixed-roster name resolution: an exact normName match beats a substring match; a name matching several distinct identities
309
+ // is ambiguous (400); among copies of one identity: idle, then docked, then on expedition, then higher Lv.
310
+ function resolveFixedShipName(port, q) {
311
+ const o = resolveUniqueIdentity(port, q);
312
+ if (!o) throw fcError(`未在港区中找到固定阵容舰娘 "${q}"`, 400, 'FIXED_SHIP_NOT_FOUND');
313
+ // every copy of the identity (e.g. 神通 Lv1 and 神通改二 Lv63) competes: idle, docked, expedition, then higher Lv
314
+ return o.copies[0];
315
+ }
316
+
317
+ const FORM_FLAG = { fixFleet: '--fix-fleet', fixedShipNames: '--ships', fixedRosterIds: 'fixedRosterIds', fixedShips: 'fixedShips' };
318
+ function fixedRosterForms(c = {}) {
319
+ const forms = [];
320
+ if (!isUnset(c.fixFleet)) forms.push('fixFleet');
321
+ if (Array.isArray(c.fixedShipNames) ? c.fixedShipNames.length > 0 : !isUnset(c.fixedShipNames)) forms.push('fixedShipNames');
322
+ if (Array.isArray(c.fixedRosterIds) ? c.fixedRosterIds.length > 0 : !isUnset(c.fixedRosterIds)) forms.push('fixedRosterIds');
323
+ return forms;
324
+ }
325
+
326
+ // Ships of a fixed roster that bypass minLv / excludeExpedition / excludeDock / onlyHealthy (each bypass is reported)
327
+ function computeExemptions(ships, c = {}) {
328
+ const minLv = isUnset(c.minLv) ? 10 : Number(c.minLv);
329
+ const exExp = c.excludeExpedition !== false;
330
+ const exDock = c.excludeDock !== false;
331
+ const out = [];
332
+ for (const s of ships) {
333
+ if (!(s.lv >= minLv)) out.push(`固定阵容豁免:${s.name} Lv${s.lv} 低于 minLv=${minLv}`);
334
+ if (s.inExpedition && (exExp || c.onlyHealthy)) out.push(`固定阵容豁免:${s.name} 远征中(出击前需召回)`);
335
+ if (s.inDock && (exDock || c.onlyHealthy)) out.push(`固定阵容豁免:${s.name} 入渠中`);
336
+ if (c.onlyHealthy && s.maxHp > 0 && s.hp / s.maxHp <= 0.5) out.push(`固定阵容豁免:${s.name} 中破以下 (--healthy)`);
337
+ }
338
+ return out;
339
+ }
340
+
341
+ // null | { ships, source:'fleet'|'ships'|'rosterIds', fleetNo, lockOrder, rosterIds, exemptions }
342
+ // The library-internal constraints.fixedShips (ship objects) is NOT handled here (kept unchanged for back-compat).
343
+ function resolveFixedRoster(port, c = {}) {
344
+ const forms = fixedRosterForms(c);
345
+ if (!forms.length) return null;
346
+ const legacy = Array.isArray(c.fixedShips) && c.fixedShips.length > 0;
347
+ if (forms.length > 1 || legacy) {
348
+ throw fcError(`冲突选项: ${[...forms, ...(legacy ? ['fixedShips'] : [])].map((f) => FORM_FLAG[f]).join(' 与 ')} 只能指定其一`, 400, 'FIXED_ROSTER_CONFLICT');
349
+ }
350
+ let ships;
351
+ let source;
352
+ let fleetNo = null;
353
+ if (forms[0] === 'fixFleet') {
354
+ const nFleets = Array.isArray(port.fleets) ? port.fleets.length : 0;
355
+ if (!nFleets) throw fcError('港区快照中没有舰队 (fleets) 信息,无法固定阵容。请在 poi 中返回母港刷新快照。', 400, 'NO_FLEETS');
356
+ const num = strictInt(c.fixFleet);
357
+ if (!Number.isInteger(num) || num < 1 || num > nFleets) throw fcError(`无效舰队编号 ${String(c.fixFleet)}(当前港区可用舰队: 1~${nFleets})`, 400, 'BAD_FLEET_NO');
358
+ ships = (port.fleets[num - 1].shipRosterIds || []).map((id) => shipById(port, id)).filter(Boolean);
359
+ if (!ships.length) throw fcError(`第 ${num} 舰队为空,无法固定阵容`, 400, 'EMPTY_FLEET');
360
+ source = 'fleet';
361
+ fleetNo = num;
362
+ } else if (forms[0] === 'fixedShipNames') {
363
+ const names = c.fixedShipNames;
364
+ if (!Array.isArray(names) || names.some((x) => typeof x !== 'string' || !x.trim())) {
365
+ throw fcError(`参数 fixedShipNames 非法: ${JSON.stringify(names)}(应为 1~6 个舰名字符串)`, 400);
366
+ }
367
+ if (names.length > 6) throw fcError(`固定阵容最多 6 艘(收到 ${names.length} 艘)`, 400, 'FIXED_ROSTER_TOO_LONG');
368
+ ships = names.map((q) => resolveFixedShipName(port, q.trim()));
369
+ source = 'ships';
370
+ } else {
371
+ const ids = c.fixedRosterIds;
372
+ if (!Array.isArray(ids)) throw fcError(`参数 fixedRosterIds 非法: ${JSON.stringify(ids)}(应为 1~6 个 rosterId 整数)`, 400);
373
+ if (ids.length > 6) throw fcError(`固定阵容最多 6 艘(收到 ${ids.length} 艘)`, 400, 'FIXED_ROSTER_TOO_LONG');
374
+ ships = ids.map((raw) => {
375
+ const id = strictInt(raw);
376
+ if (!Number.isInteger(id) || id < 1) throw fcError(`参数 fixedRosterIds 非法: ${JSON.stringify(raw)}(应为正整数 rosterId)`, 400);
377
+ const s = shipById(port, id);
378
+ if (!s) throw fcError(`未找到 rosterId=${id} 的舰娘`, 400, 'FIXED_SHIP_NOT_FOUND');
379
+ return s;
380
+ });
381
+ source = 'rosterIds';
382
+ }
383
+ if (ships.length > 6) throw fcError(`固定阵容最多 6 艘(收到 ${ships.length} 艘)`, 400, 'FIXED_ROSTER_TOO_LONG');
384
+ const seenK = new Set();
385
+ const seenR = new Set();
386
+ for (const s of ships) {
387
+ const k = shipIdentityKey(s);
388
+ if (seenK.has(k) || seenR.has(s.rosterId)) throw fcError(`固定阵容包含重复舰娘: ${s.name}`, 400, 'FIXED_ROSTER_DUPLICATE');
389
+ seenK.add(k);
390
+ seenR.add(s.rosterId);
391
+ }
392
+ return {
393
+ ships,
394
+ source,
395
+ fleetNo,
396
+ lockOrder: c.lockOrder === true,
397
+ rosterIds: ships.map((s) => s.rosterId),
398
+ exemptions: computeExemptions(ships, c),
399
+ };
400
+ }
401
+
402
+ // Rotate the first ship satisfying flagPred to the front (no lock), or check ships[0] (lockOrder). Returns
403
+ // { ships, rotated } or { error } (422 text).
404
+ function applyFixedFlagship(ships, flagPred, lockOrder, flagTypes = [], flagNames = []) {
405
+ if (!flagPred) return { ships: ships.slice(), rotated: false };
406
+ const lim = flagLimitText(flagTypes, flagNames);
407
+ if (lockOrder) {
408
+ if (!flagPred(ships[0])) return { error: `--lock-order 锁定的旗舰 ${ships[0].name} 不满足旗舰限制 ${lim}` };
409
+ return { ships: ships.slice(), rotated: false };
410
+ }
411
+ const idx = ships.findIndex(flagPred);
412
+ if (idx < 0) return { error: `固定阵容中没有满足旗舰限制 ${lim} 的舰` };
413
+ const out = ships.slice();
414
+ if (idx > 0) { const [f] = out.splice(idx, 1); out.unshift(f); }
415
+ return { ships: out, rotated: idx > 0 };
416
+ }
417
+
418
+ // Expedition ships whose gear stays in the pool for a mustInclude query: when every port ship matching the query is on
419
+ // expedition, the optimizers must take an expedition copy, so that copy keeps its own gear (both optimizers use this helper,
420
+ // so their warehouses stay index-identical). With onlyHealthy expedition ships are never usable -> nothing kept.
421
+ function mustIncludeKeepIds(port, c = {}) {
422
+ const keep = new Set();
423
+ if (c.excludeExpedition === false || c.onlyHealthy) return keep;
424
+ for (const q of (Array.isArray(c.mustInclude) ? c.mustInclude : [])) {
425
+ const m = port.ships.filter((s) => matchesShipQuery(s, q));
426
+ if (!m.length || m.some((s) => !s.inExpedition)) continue;
427
+ for (const s of m) keep.add(s.rosterId);
428
+ }
429
+ return keep;
430
+ }
431
+
432
+ // Active warehouse: allWarehouse minus the gear of expedition ships that are NOT kept (fixed roster / mustInclude expedition
433
+ // ships keep their own gear). Same subtraction loop as portLoader; an empty keep-set returns port.warehouse itself, so default
434
+ // runs are bit-identical. excludeExpedition=false (recall mode) uses allWarehouse as before.
435
+ // Phase L (design_lbas §5.2): includeLbasHeld (constraints.lbas.release) appends port.lbasItems (planes held by land bases,
436
+ // never in warehouse / allWarehouse) at the END with _lbasHeld: true and _lbasUid (index into port.lbasItems), so warehouse
437
+ // indices stay unchanged. heldFilter (optional predicate, e.g. NOT --ban-equip) drops held items the ships may not use
438
+ // (review P2-1; the LBAS planner maps uids through _lbasUid). Absent -> as before.
439
+ function buildActiveWarehouse(port, opts = {}) {
440
+ const base = buildActiveWarehouseCore(port, opts);
441
+ if (!opts.includeLbasHeld || !port || !Array.isArray(port.lbasItems) || !port.lbasItems.length) return base;
442
+ const held = port.lbasItems.map((e, uid) => ({ ...e, _lbasHeld: true, _lbasUid: uid }));
443
+ return base.concat(opts.heldFilter ? held.filter((e) => opts.heldFilter(e)) : held);
444
+ }
445
+ function buildActiveWarehouseCore(port, { excludeExpedition = true, keepRosterIds = null } = {}) {
446
+ if (!excludeExpedition) return port.allWarehouse || port.warehouse;
447
+ if (!keepRosterIds || !keepRosterIds.size || !port.allWarehouse) return port.warehouse;
448
+ const warehouse = port.allWarehouse.slice();
449
+ for (const s of port.ships) {
450
+ if (!s.inExpedition || keepRosterIds.has(s.rosterId)) continue;
451
+ const locked = s.exEquip ? [...(s.equips || []), s.exEquip] : (s.equips || []);
452
+ for (const eq of locked) {
453
+ if (!eq || !eq.id) continue;
454
+ let idx = warehouse.findIndex((w) => w.id === eq.id && (w.lv || 0) === (eq.lv || 0) && (w.alv || 0) === (eq.alv || 0));
455
+ if (idx < 0) idx = warehouse.findIndex((w) => w.id === eq.id && (w.lv || 0) === (eq.lv || 0));
456
+ if (idx < 0) idx = warehouse.findIndex((w) => w.id === eq.id);
457
+ if (idx >= 0) warehouse.splice(idx, 1);
458
+ }
459
+ }
460
+ return warehouse;
461
+ }
462
+
463
+ // Phase L (design_lbas §5.5, addendum L4 P3): the map's sortie restrictions (mapDef.fleetLimits, e.g. 6-4 BB / CV <= 2) as a
464
+ // fleet predicate for the skeleton enumeration, the ship-swap operators, race merges and the template rosters, so no candidate
465
+ // ever reaches routeKit.assertFleetLimits (runMonteCarlo would throw 400 FLEET_LIMIT, also inside the pool workers).
466
+ // null when the map declares no limits (every caller then skips the check: unchanged behaviour).
467
+ // `partial` (Wave 33, fleetLimits min): the ships are not a whole fleet (must-include ships) -> only the maxima apply.
468
+ function mapFleetLimitPred(mapDef) {
469
+ if (!mapDef || !Array.isArray(mapDef.fleetLimits) || !mapDef.fleetLimits.length) return null;
470
+ const RK = require('../data/routeKit');
471
+ return (ships, partial) => RK.checkFleetLimits(mapDef, ships, undefined, partial).length === 0;
472
+ }
473
+ // Readable violation text of a fleet (null when it is legal or the map has no limits), e.g. 「戦艦級 ≤ 2(当前 3)」
474
+ function fleetLimitViolationText(mapDef, ships, partial) {
475
+ if (!mapDef || !Array.isArray(mapDef.fleetLimits) || !mapDef.fleetLimits.length) return null;
476
+ const RK = require('../data/routeKit');
477
+ const bad = RK.checkFleetLimits(mapDef, ships, undefined, partial);
478
+ return bad.length ? RK.fleetLimitText(bad) : null;
479
+ }
480
+
481
+ // --exclude removes whole identities (every copy of the named ship); without a port it falls back to substring matching
482
+ const excludeMatcher = (c = {}, port = null) => {
483
+ const ex = Array.isArray(c.mustExclude) ? c.mustExclude.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()) : [];
484
+ if (!ex.length) return null;
485
+ if (!port || !Array.isArray(port.ships)) return (s) => ex.some((q) => matchesShipQuery(s, q));
486
+ const keys = new Set();
487
+ for (const q of ex) { const o = resolveUniqueIdentity(port, q); if (o) keys.add(o.key); }
488
+ return (s) => keys.has(shipIdentityKey(s));
489
+ };
490
+
491
+ // Input validation shared by validateOptimizerConstraints (library), cli.js and server.js: throws 400 with a Chinese reason.
492
+ function validateTaskAndRosterInputs(port, c = {}) {
493
+ const bad = (field, v, rule) => fcError(`参数 ${field} 非法: ${JSON.stringify(v)}(${rule})`, 400);
494
+ const strList = (field) => {
495
+ const v = c[field];
496
+ if (isUnset(v)) return [];
497
+ if (!Array.isArray(v) || v.some((x) => typeof x !== 'string' || !x.trim())) throw bad(field, v, '应为舰名字符串数组');
498
+ return v.map((x) => x.trim());
499
+ };
500
+ const incl = Array.isArray(c.mustInclude) ? c.mustInclude.filter((x) => typeof x === 'string') : [];
501
+ const excl = strList('mustExclude');
502
+ const exclKey = new Map(); // exclude query -> identity key
503
+ for (const q of excl) {
504
+ const o = resolveUniqueIdentity(port, q);
505
+ if (!o) throw fcError(`未在港区中找到要排除的舰娘 "${q}"`, 400, 'EXCLUDE_NOT_FOUND');
506
+ exclKey.set(q, o.key);
507
+ }
508
+ if (excl.length && incl.length) {
509
+ for (const s of port.ships) {
510
+ const iq = incl.find((q) => matchesShipQuery(s, q));
511
+ const eq = iq ? excl.find((q) => exclKey.get(q) === shipIdentityKey(s)) : null;
512
+ if (iq && eq) throw fcError(`冲突选项: --include "${iq}" 与 --exclude "${eq}" 指向同一舰娘(${s.name}),不能同时使用`, 400, 'INCLUDE_EXCLUDE_CONFLICT');
513
+ }
514
+ }
515
+ for (const f of ['minShips', 'maxShips']) {
516
+ if (isUnset(c[f])) continue;
517
+ const n = strictInt(c[f]);
518
+ if (!Number.isInteger(n) || n < 1 || n > 6) throw bad(f, c[f], '应为 1~6 的整数');
519
+ }
520
+ if (!isUnset(c.minShips) && !isUnset(c.maxShips) && Number(c.minShips) > Number(c.maxShips)) {
521
+ throw fcError(`--min-ships ${Number(c.minShips)} 大于 --max-ships ${Number(c.maxShips)}`, 400, 'BAD_TASK_CONSTRAINT');
522
+ }
523
+ if (nonEmptyList(c.requireStype)) parseStypeExpr(c.requireStype);
524
+ if (!isUnset(c.requireGroups)) {
525
+ if (!Array.isArray(c.requireGroups)) throw bad('requireGroups', c.requireGroups, '应为数组,如 ["阳炎|不知火>=2"]');
526
+ for (const g of c.requireGroups) {
527
+ const t = parseGroupExpr(g);
528
+ const owned = t.names.map((q) => resolveUniqueIdentity(port, q)); // throws 400 on an ambiguous name
529
+ if (!owned.some(Boolean)) {
530
+ throw fcError(`--require-group "${t.label}" 中的舰娘在港区均不存在`, 400, 'GROUP_NOT_FOUND');
531
+ }
532
+ }
533
+ }
534
+ for (const q of strList('requireFlagShip')) {
535
+ if (!resolveUniqueIdentity(port, q)) throw fcError(`未在港区中找到旗舰限制舰娘 "${q}"`, 400, 'FLAG_SHIP_NOT_FOUND');
536
+ }
537
+ if (!isUnset(c.lockOrder) && typeof c.lockOrder !== 'boolean') throw bad('lockOrder', c.lockOrder, '应为 true / false');
538
+ if (!isUnset(c.stage3CrossSwap) && typeof c.stage3CrossSwap !== 'boolean') throw bad('stage3CrossSwap', c.stage3CrossSwap, '应为 true / false');
539
+ const fixed = resolveFixedRoster(port, c);
540
+ const legacyFixed = Array.isArray(c.fixedShips) && c.fixedShips.length > 0;
541
+ // (the library-internal fixedShips objects have no lock-order support: rejected rather than silently ignored)
542
+ if (c.lockOrder === true && !fixed) {
543
+ throw fcError(legacyFixed ? '--lock-order 不支持库内部 fixedShips,请改用 fixedRosterIds / fixedShipNames' : '--lock-order 需配合 --fix-fleet 或 --ships 使用', 400, 'LOCK_ORDER_WITHOUT_FIXED');
544
+ }
545
+ if (fixed) {
546
+ if (incl.length) throw fcError('冲突选项: 固定阵容 (--fix-fleet/--ships) 已确定全部舰娘,不能再用 --include', 400, 'FIXED_INCLUDE_CONFLICT');
547
+ for (const q of excl) {
548
+ const hit = fixed.ships.find((s) => exclKey.get(q) === shipIdentityKey(s));
549
+ if (hit) throw fcError(`冲突选项: --exclude "${q}" 指向固定阵容中的舰娘(${hit.name})`, 400, 'FIXED_EXCLUDE_CONFLICT');
550
+ }
551
+ }
552
+ return { fixed };
553
+ }
554
+
555
+ // Why a port ship is not in the usable pool (for 422 reasons); null = it is usable
556
+ function filteredReason(s, c, minLv, exclHit) {
557
+ if (exclHit && exclHit(s)) return '被 --exclude 排除';
558
+ if (c.onlyHealthy && (s.inDock || s.inExpedition || s.hp / s.maxHp <= 0.5)) return '被 --healthy 排除';
559
+ if (c.excludeExpedition !== false && s.inExpedition) return '远征中';
560
+ if (c.excludeDock !== false && s.inDock) return '入渠中';
561
+ if (!(s.lv >= minLv)) return `被 minLv=${minLv} 排除`;
562
+ return null;
563
+ }
564
+
565
+ // "BBV=2:可用航战 0 艘" / "吹雪|白雪>=3:可用 2 艘(另有 深雪 Lv6、初雪 Lv1 被 minLv=10 排除)"
566
+ function explainCounterShortfall(port, ct, available, usableShips, c = {}, minLv = 10) {
567
+ const usableKeys = new Set(usableShips.map((s) => shipIdentityKey(s)));
568
+ const exclHit = excludeMatcher(c, port);
569
+ const groups = new Map();
570
+ const seen = new Set();
571
+ for (const s of port.ships) {
572
+ if (!ct.match(s)) continue;
573
+ const k = shipIdentityKey(s);
574
+ if (usableKeys.has(k) || seen.has(k)) continue;
575
+ const r = filteredReason(s, c, minLv, exclHit);
576
+ if (!r) continue;
577
+ seen.add(k);
578
+ if (!groups.has(r)) groups.set(r, []);
579
+ groups.get(r).push(`${s.name} Lv${s.lv}`);
580
+ }
581
+ const extra = [...groups.entries()].map(([r, list]) => `${list.slice(0, 6).join('、')}${list.length > 6 ? ` 等 ${list.length} 艘` : ''} ${r}`).join(';');
582
+ const what = ct.kind === 'stype' ? `可用${ct.stypes.map((st) => STYPE_ZH[st] || st).join('/')} ${available} 艘` : `可用 ${available} 艘`;
583
+ return { text: `${ct.label}:${what}${extra ? `(另有 ${extra})` : ''}`, minLvFiltered: [...groups.keys()].some((r) => r.startsWith('被 minLv')) };
584
+ }
585
+
586
+ // Constraint-aware skeleton DP (exact counts + deterministic unranking over per-bucket take counts).
587
+ // bkSizes[b] = ships in bucket b; bkMatch[b][i] = bucket b counts toward counter i (uniform per bucket: stype + group/flag
588
+ // mask are part of the bucket key); counters = [{op, n}] (>= saturates at n, <= / = drop transitions above n);
589
+ // c0vals = counter values already contributed by locked ships. Mixed-radix state c; S = prod(n_i + 1) (null above stateCap).
590
+ // dp[b][r][k][c] = number of ways to pick r ships from buckets b..B-1 using exactly k buckets, ending in a satisfied state.
591
+ // With no counters (S = 1) the numbers and the unranking equal the unconstrained DP exactly.
592
+ function createConstrainedEnumerator(bkSizes, bkMatch, rem, counters, c0vals = [], stateCap = DP_STATE_CAP) {
593
+ const dims = counters.map((ct) => ct.n + 1);
594
+ const radix = [];
595
+ let S = 1;
596
+ for (const d of dims) {
597
+ radix.push(S);
598
+ S *= d;
599
+ if (S > stateCap) return null;
600
+ }
601
+ const B = bkSizes.length;
602
+ const maxK = Math.min(B, rem);
603
+ const K1 = maxK + 1;
604
+ const at = (r, k, c) => (r * K1 + k) * S + c;
605
+ let c0 = 0;
606
+ let infeasible = false;
607
+ counters.forEach((ct, i) => {
608
+ let v = c0vals[i] || 0;
609
+ if (ct.op === '>=') v = Math.min(v, ct.n);
610
+ else if (v > ct.n) infeasible = true;
611
+ c0 += Math.min(v, ct.n) * radix[i];
612
+ });
613
+ const sat = new Uint8Array(S);
614
+ for (let c = 0; c < S; c++) {
615
+ let ok = true;
616
+ for (let i = 0; i < counters.length && ok; i++) {
617
+ const v = Math.floor(c / radix[i]) % dims[i];
618
+ if (counters[i].op === '>=' ? v < counters[i].n : counters[i].op === '=' ? v !== counters[i].n : false) ok = false;
619
+ }
620
+ sat[c] = ok ? 1 : 0;
621
+ }
622
+ const adv = new Array(B);
623
+ for (let b = 0; b < B; b++) {
624
+ const cap = Math.min(rem, bkSizes[b]);
625
+ adv[b] = [null];
626
+ for (let take = 1; take <= cap; take++) {
627
+ const t = new Int32Array(S);
628
+ for (let c = 0; c < S; c++) {
629
+ let nc = c;
630
+ let ok = true;
631
+ for (let i = 0; i < counters.length; i++) {
632
+ if (!bkMatch[b][i]) continue;
633
+ const v = Math.floor(c / radix[i]) % dims[i];
634
+ let nv = v + take;
635
+ if (counters[i].op === '>=') nv = Math.min(nv, counters[i].n);
636
+ else if (nv > counters[i].n) { ok = false; break; }
637
+ nc += (nv - v) * radix[i];
638
+ }
639
+ t[c] = ok ? nc : -1;
640
+ }
641
+ adv[b].push(t);
642
+ }
643
+ }
644
+ const size = (rem + 1) * K1 * S;
645
+ const dp = new Array(B + 1);
646
+ dp[B] = new Float64Array(size);
647
+ for (let c = 0; c < S; c++) if (sat[c]) dp[B][at(0, 0, c)] = 1;
648
+ for (let b = B - 1; b >= 0; b--) {
649
+ const nx = dp[b + 1];
650
+ const cur = new Float64Array(size);
651
+ const cap = adv[b].length - 1;
652
+ for (let r = 0; r <= rem; r++) {
653
+ for (let k = 0; k <= maxK; k++) {
654
+ for (let c = 0; c < S; c++) {
655
+ let ways = nx[at(r, k, c)]; // take = 0
656
+ if (k > 0) {
657
+ const maxTake = Math.min(cap, r);
658
+ for (let take = 1; take <= maxTake; take++) {
659
+ const c2 = adv[b][take][c];
660
+ if (c2 < 0) continue;
661
+ ways += nx[at(r - take, k - 1, c2)];
662
+ if (ways > 1e12) { ways = 1e12; break; }
663
+ }
664
+ }
665
+ cur[at(r, k, c)] = ways;
666
+ }
667
+ }
668
+ }
669
+ dp[b] = cur;
670
+ }
671
+ const total = (k) => (infeasible || k < 1 || k > maxK ? 0 : dp[0][at(rem, k, c0)]);
672
+ let totalAll = 0;
673
+ for (let k = 1; k <= maxK; k++) totalAll += total(k);
674
+ // rank-th combination (0-based) using exactly targetK buckets -> per-bucket take counts
675
+ const unrank = (rank, targetK) => {
676
+ const takes = new Array(B).fill(0);
677
+ let idx = rank;
678
+ let r = rem;
679
+ let kRem = targetK;
680
+ let c = c0;
681
+ for (let b = 0; b < B && r > 0; b++) {
682
+ const w0 = dp[b + 1][at(r, kRem, c)];
683
+ if (idx < w0) continue;
684
+ idx -= w0;
685
+ const maxTake = Math.min(r, adv[b].length - 1);
686
+ for (let take = 1; take <= maxTake; take++) {
687
+ const c2 = adv[b][take][c];
688
+ const w = (kRem > 0 && c2 >= 0) ? dp[b + 1][at(r - take, kRem - 1, c2)] : 0;
689
+ if (idx < w) {
690
+ takes[b] = take;
691
+ r -= take;
692
+ kRem -= 1;
693
+ c = c2;
694
+ break;
695
+ }
696
+ idx -= w;
697
+ }
698
+ }
699
+ return takes;
700
+ };
701
+ return { S, maxK, total, totalAll, unrank, infeasible };
702
+ }
703
+
704
+ module.exports = {
705
+ STYPE_BY_CODE,
706
+ STYPE_ALIASES,
707
+ CODE_BY_STYPE,
708
+ DP_STATE_CAP,
709
+ parseStypeExpr,
710
+ parseGroupExpr,
711
+ hasTaskConstraints,
712
+ compileTaskConstraints,
713
+ describeTaskConstraints,
714
+ flagLimitText,
715
+ makeFlagPred,
716
+ fleetSatisfies,
717
+ resolveFixedRoster,
718
+ resolveFixedShipName,
719
+ resolveNameIdentities,
720
+ resolveUniqueIdentity,
721
+ fixedRosterForms,
722
+ computeExemptions,
723
+ applyFixedFlagship,
724
+ mustIncludeKeepIds,
725
+ buildActiveWarehouse,
726
+ mapFleetLimitPred,
727
+ fleetLimitViolationText,
728
+ excludeMatcher,
729
+ validateTaskAndRosterInputs,
730
+ explainCounterShortfall,
731
+ createConstrainedEnumerator,
732
+ opOk,
733
+ };