@rine-kit/presentation 0.0.0-stage → 0.1.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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/dist/src/builders/pubg.d.ts +35 -0
  3. package/dist/src/builders/pubg.js +725 -0
  4. package/dist/src/contracts/owner.d.ts +20 -0
  5. package/dist/src/contracts/owner.js +1 -0
  6. package/dist/src/contracts/pubg.d.ts +200 -0
  7. package/dist/src/contracts/pubg.js +1 -0
  8. package/dist/src/contracts/session-review.d.ts +72 -0
  9. package/dist/src/contracts/session-review.js +1 -0
  10. package/dist/src/index.d.ts +19 -0
  11. package/dist/src/index.js +19 -0
  12. package/dist/src/pubg-registry.d.ts +21 -0
  13. package/dist/src/pubg-registry.js +123 -0
  14. package/dist/src/renderers/daily-review.d.ts +22 -0
  15. package/dist/src/renderers/daily-review.js +149 -0
  16. package/dist/src/renderers/owner.d.ts +6 -0
  17. package/dist/src/renderers/owner.js +35 -0
  18. package/dist/src/renderers/pubg.d.ts +22 -0
  19. package/dist/src/renderers/pubg.js +603 -0
  20. package/dist/src/renderers/session-review.d.ts +15 -0
  21. package/dist/src/renderers/session-review.js +187 -0
  22. package/dist/src/reply-check.d.ts +3 -0
  23. package/dist/src/reply-check.js +44 -0
  24. package/dist/src/reply-guides.d.ts +10 -0
  25. package/dist/src/reply-guides.js +64 -0
  26. package/dist/src/time/format.d.ts +16 -0
  27. package/dist/src/time/format.js +63 -0
  28. package/dist/src/validation/session-review.d.ts +3 -0
  29. package/dist/src/validation/session-review.js +136 -0
  30. package/dist/src/validation/validate.d.ts +18 -0
  31. package/dist/src/validation/validate.js +736 -0
  32. package/dist/src/worldline/adapter.d.ts +3 -0
  33. package/dist/src/worldline/adapter.js +47 -0
  34. package/dist/src/worldline/contracts.d.ts +44 -0
  35. package/dist/src/worldline/contracts.js +40 -0
  36. package/dist/src/worldline/policy.d.ts +2 -0
  37. package/dist/src/worldline/policy.js +31 -0
  38. package/dist/src/worldline/renderer.d.ts +3 -0
  39. package/dist/src/worldline/renderer.js +5 -0
  40. package/dist/src/worldline/vocabulary.d.ts +2 -0
  41. package/dist/src/worldline/vocabulary.js +1 -0
  42. package/package.json +33 -3
  43. package/README.md +0 -3
@@ -0,0 +1,725 @@
1
+ import { containsInternalTimeTerms } from '../time/format.js';
2
+ import { sessionMapName } from '../renderers/session-review.js';
3
+ import { assertValid, validatePubgComparisonPresentation, validatePubgMatchDetailPresentation, validatePubgMatchListPresentation, validatePubgMatchReviewPresentation, validatePubgPeriodReviewPresentation, validatePubgStatsPresentation, validatePubgStatusPresentation, validatePubgTeamDamagePresentation, } from '../validation/validate.js';
4
+ function record(value) {
5
+ return value && typeof value === 'object' && !Array.isArray(value)
6
+ ? value
7
+ : {};
8
+ }
9
+ function text(value, fallback) {
10
+ const candidate = typeof value === 'string' ? value.trim() : '';
11
+ if (!candidate || containsInternalTimeTerms(candidate))
12
+ return fallback;
13
+ return candidate;
14
+ }
15
+ function scalar(value) {
16
+ if (value === null)
17
+ return null;
18
+ if (typeof value === 'number')
19
+ return Number.isFinite(value) ? value : null;
20
+ if (typeof value === 'string')
21
+ return value;
22
+ return null;
23
+ }
24
+ function numberOrNull(value) {
25
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
26
+ }
27
+ function stringOrNull(value) {
28
+ return typeof value === 'string' && value.trim() ? value : null;
29
+ }
30
+ function sourceRange(input) {
31
+ const range = input.sourceRange;
32
+ if (!range)
33
+ return undefined;
34
+ const segments = range.segments?.filter((segment) => segment.label.trim()) ?? [];
35
+ if (range.from === null && range.to === null && segments.length === 0)
36
+ return undefined;
37
+ return { from: range.from, to: range.to, ...(segments.length ? { segments } : {}) };
38
+ }
39
+ function evidencePool(input, extra = []) {
40
+ return new Set([
41
+ ...(input.evidenceRefs?.matchIds ?? []),
42
+ ...(input.evidenceRefs?.playerIds ?? []),
43
+ ...(input.evidenceRefs?.fields ?? []),
44
+ ...extra,
45
+ ]);
46
+ }
47
+ function evidenceFor(value, known) {
48
+ const row = record(value);
49
+ const raw = Array.isArray(row.evidenceRefs)
50
+ ? row.evidenceRefs
51
+ : Array.isArray(row.evidenceIds)
52
+ ? row.evidenceIds
53
+ : [];
54
+ return raw.filter((item) => typeof item === 'string' && known.has(item));
55
+ }
56
+ function textItems(value, fallbackEvidence = []) {
57
+ if (!Array.isArray(value))
58
+ return [];
59
+ return value.flatMap((item) => {
60
+ const row = record(item);
61
+ const rawText = typeof row.text === 'string' && row.text.trim()
62
+ ? row.text
63
+ : typeof row.title === 'string'
64
+ ? `${row.title}${typeof row.text === 'string' && row.text ? `:${row.text}` : ''}`
65
+ : '';
66
+ if (!rawText.trim())
67
+ return [];
68
+ const refs = Array.isArray(row.evidenceIds)
69
+ ? row.evidenceIds.filter((id) => typeof id === 'string')
70
+ : Array.isArray(row.evidenceRefs)
71
+ ? row.evidenceRefs.filter((id) => typeof id === 'string')
72
+ : fallbackEvidence;
73
+ return [{ text: rawText.trim(), evidenceRefs: refs }];
74
+ });
75
+ }
76
+ function values(value) {
77
+ const source = record(value);
78
+ return Object.fromEntries(Object.entries(source).map(([key, item]) => [key, scalar(item)]));
79
+ }
80
+ function metricRows(value, known) {
81
+ if (!Array.isArray(value))
82
+ return [];
83
+ return value.flatMap((item) => {
84
+ const row = record(item);
85
+ const label = text(row.label ?? row.key, '未知对象');
86
+ const position = row.position === null ? null : numberOrNull(row.position);
87
+ const rowEvidence = evidenceFor(row, known);
88
+ return [
89
+ {
90
+ label,
91
+ values: values(row.metrics ?? row.values),
92
+ ...(row.position !== undefined ? { position } : {}),
93
+ evidenceRefs: rowEvidence,
94
+ },
95
+ ];
96
+ });
97
+ }
98
+ function queryLabel(input, fallback) {
99
+ const query = record(input.queryResolved);
100
+ const selector = record(query.resolvedSelector ?? query.selector);
101
+ return text(selector.label ?? record(query.summary).periodLabel, fallback);
102
+ }
103
+ function publicPeriodLabel(input, fallback) {
104
+ let label = queryLabel(input, '');
105
+ if (!label) {
106
+ const query = record(input.queryResolved);
107
+ const selector = record(query.resolvedSelector ?? query.selector);
108
+ const value = stringOrNull(selector.value);
109
+ label = value
110
+ ? ({
111
+ today: '今日',
112
+ yesterday: '昨天',
113
+ last_night: '昨晚',
114
+ last_7_days: '最近七天',
115
+ previous_7_days: '此前七天',
116
+ this_week: '本周',
117
+ last_week: '上周',
118
+ }[value] ?? value)
119
+ : fallback;
120
+ }
121
+ return label === '今天' ? '今日' : label;
122
+ }
123
+ const METRIC_LABELS = {
124
+ matches: '场次',
125
+ kills: '击杀',
126
+ assists: '助攻',
127
+ damage: '伤害',
128
+ avg_damage: '场均伤害',
129
+ kd: 'KD',
130
+ deaths: '死亡',
131
+ wins: '胜利',
132
+ top10: '前十',
133
+ rank: '排名',
134
+ dbnos: '倒地',
135
+ revives: '救援',
136
+ headshot_kills: '爆头击杀',
137
+ survival_time: '生存时间',
138
+ longest_kill: '最远击杀',
139
+ avg_kills: '场均击杀',
140
+ avg_rank: '场均排名',
141
+ top10_rate: '前十率',
142
+ denominatorZero: '零死亡场次',
143
+ performance_score: '表现分',
144
+ chicken_index: '吃鸡指数',
145
+ };
146
+ function statusMessage(status) {
147
+ if (status === 'partial')
148
+ return '结果不完整,缺失事实保持为未知。';
149
+ if (status === 'no_matches')
150
+ return '没有找到符合条件的比赛。';
151
+ if (status === 'error')
152
+ return '当前数据源无法完成这次查询,没有使用旧聊天数据代替。';
153
+ return '';
154
+ }
155
+ function base(input) {
156
+ const status = input.status ?? 'ok';
157
+ const range = sourceRange(input);
158
+ return {
159
+ status,
160
+ dataUpdatedAt: input.dataUpdatedAt,
161
+ ...(range ? { sourceRange: range } : {}),
162
+ ...(input.coverage ? { coverage: input.coverage } : {}),
163
+ };
164
+ }
165
+ function knownFor(input, extra = []) {
166
+ const known = evidencePool(input, extra);
167
+ for (const item of extra)
168
+ known.add(item);
169
+ return known;
170
+ }
171
+ export function buildPubgStatusPresentation(input) {
172
+ const status = input.status ?? 'error';
173
+ const toolName = input.toolName ?? 'pubg';
174
+ const title = toolName === 'pubg_resolve_players'
175
+ ? 'PUBG 玩家查询'
176
+ : toolName === 'pubg_prefetch_telemetry'
177
+ ? 'PUBG Telemetry 同步'
178
+ : toolName === 'pubg_telemetry_sync_report'
179
+ ? 'PUBG Telemetry D-mail'
180
+ : 'PUBG 查询状态';
181
+ const errorCode = stringOrNull(input.error?.code);
182
+ const message = status === 'error' && input.error?.reason
183
+ ? `查询失败:${text(input.error.reason, '数据源返回错误。')}`
184
+ : statusMessage(status) || '查询完成。';
185
+ const presentation = {
186
+ ...base(input),
187
+ type: 'pubg_status',
188
+ headline: title,
189
+ message,
190
+ ...(errorCode ? { errorCode } : {}),
191
+ evidenceRefs: input.evidenceRefs?.matchIds ?? [],
192
+ };
193
+ return assertValid(validatePubgStatusPresentation(presentation, evidencePool(input)));
194
+ }
195
+ export function buildPubgStatsPresentation(input) {
196
+ const data = record(input.data);
197
+ const known = knownFor(input);
198
+ const summary = record(data.summary);
199
+ const rows = metricRows(data.rows, known);
200
+ const matchCount = numberOrNull(summary.uniqueMatchCount);
201
+ const summaryText = typeof data.summary === 'string'
202
+ ? text(data.summary, '战绩已生成。')
203
+ : matchCount === null
204
+ ? '战绩已生成。'
205
+ : `共 ${matchCount} 场。`;
206
+ const query = record(input.queryResolved);
207
+ const reference = record(query.reference);
208
+ const orderBy = record(query.orderBy);
209
+ const requestedMetrics = Array.isArray(query.metrics) ? query.metrics : [];
210
+ const subjectLabel = reference.subjectExplicit === true ? '玩家' : '队伍';
211
+ const operation = text(data.operation ?? query.operation, 'report');
212
+ const requestedMetric = stringOrNull(orderBy.metric) ?? stringOrNull(requestedMetrics[0]);
213
+ const publicHeadline = operation === 'rank'
214
+ ? `${publicPeriodLabel(input, 'PUBG')}${requestedMetric ? (METRIC_LABELS[requestedMetric] ?? requestedMetric) : ''}榜`
215
+ : `${publicPeriodLabel(input, 'PUBG')}${subjectLabel}战绩`;
216
+ const presentation = {
217
+ ...base(input),
218
+ type: 'pubg_stats',
219
+ headline: input.presentationStyle === 'public_agent' ? publicHeadline : queryLabel(input, 'PUBG 战绩'),
220
+ operation,
221
+ groupBy: text(data.groupBy ?? query.groupBy, 'player'),
222
+ summary: `${statusMessage(input.status ?? 'ok')}${statusMessage(input.status ?? 'ok') ? '\n' : ''}${summaryText}`,
223
+ rows,
224
+ evidenceRefs: input.evidenceRefs?.matchIds ?? [],
225
+ };
226
+ return assertValid(validatePubgStatsPresentation(presentation, known));
227
+ }
228
+ export function buildPubgMatchListPresentation(input) {
229
+ const data = record(input.data);
230
+ const known = knownFor(input);
231
+ const matches = Array.isArray(data.matches)
232
+ ? data.matches.flatMap((item) => {
233
+ const row = record(item);
234
+ const matchId = stringOrNull(row.matchId);
235
+ if (!matchId)
236
+ return [];
237
+ const players = Array.isArray(row.players)
238
+ ? row.players
239
+ .map((player) => {
240
+ const value = record(player);
241
+ return `${text(value.name ?? value.playerName, '未知玩家')} 击杀${scalar(value.kills) ?? '未知'} 伤害${scalar(value.damage) ?? '未知'}`;
242
+ })
243
+ .join(';')
244
+ : '';
245
+ return [
246
+ {
247
+ matchId,
248
+ startedAt: stringOrNull(row.startedAt),
249
+ mapName: text(row.mapName, '未知地图'),
250
+ gameMode: text(row.gameMode, '未知模式'),
251
+ placement: numberOrNull(row.placement),
252
+ summary: players || '玩家事实未知',
253
+ evidenceRefs: evidenceFor(row, known),
254
+ },
255
+ ];
256
+ })
257
+ : [];
258
+ const total = numberOrNull(data.total);
259
+ const summary = total === null
260
+ ? `返回 ${matches.length} 场比赛。`
261
+ : `共 ${total} 场比赛,当前返回 ${matches.length} 场。`;
262
+ const presentation = {
263
+ ...base(input),
264
+ type: 'pubg_match_list',
265
+ headline: queryLabel(input, 'PUBG 比赛列表'),
266
+ summary: `${statusMessage(input.status ?? 'ok')}${statusMessage(input.status ?? 'ok') ? '\n' : ''}${summary}`,
267
+ matches,
268
+ evidenceRefs: input.evidenceRefs?.matchIds ?? [],
269
+ };
270
+ return assertValid(validatePubgMatchListPresentation(presentation, known));
271
+ }
272
+ function comparisonSegmentRange(input, index) {
273
+ const segment = input.sourceRange?.segments?.[index];
274
+ if (!segment)
275
+ return undefined;
276
+ return { from: segment.from, to: segment.to };
277
+ }
278
+ export function buildPubgComparisonPresentation(input) {
279
+ const data = record(input.data);
280
+ const known = knownFor(input);
281
+ const segments = Array.isArray(data.segments)
282
+ ? data.segments.map((item, index) => {
283
+ const segment = record(item);
284
+ const range = comparisonSegmentRange(input, index);
285
+ return {
286
+ label: text(segment.label, `区间 ${index + 1}`),
287
+ ...(range ? { sourceRange: range } : {}),
288
+ rows: metricRows(segment.rows, known),
289
+ };
290
+ })
291
+ : [];
292
+ const presentation = {
293
+ ...base(input),
294
+ type: 'pubg_comparison',
295
+ headline: 'PUBG 对比',
296
+ summary: `${statusMessage(input.status ?? 'ok')}${statusMessage(input.status ?? 'ok') ? '\n' : ''}已保留两个区间的独立来源范围。`,
297
+ rows: metricRows(data.rows, known),
298
+ segments,
299
+ evidenceRefs: input.evidenceRefs?.matchIds ?? [],
300
+ };
301
+ return assertValid(validatePubgComparisonPresentation(presentation, known));
302
+ }
303
+ export function buildPubgMatchDetailPresentation(input) {
304
+ const data = record(input.data);
305
+ const match = record(data.match);
306
+ const known = knownFor(input);
307
+ const matchId = stringOrNull(match.matchId) ?? '未知对局';
308
+ const players = Array.isArray(match.players)
309
+ ? match.players.flatMap((item) => {
310
+ const player = record(item);
311
+ const label = text(player.displayName ?? player.playerName ?? player.accountId, '未知玩家');
312
+ return [
313
+ {
314
+ label,
315
+ values: values({
316
+ kills: player.kills,
317
+ assists: player.assists,
318
+ damage: player.damage,
319
+ dbnos: player.dbnos,
320
+ rank: player.rank,
321
+ }),
322
+ evidenceRefs: evidenceFor(player, known),
323
+ },
324
+ ];
325
+ })
326
+ : [];
327
+ const presentation = {
328
+ ...base(input),
329
+ type: 'pubg_match_detail',
330
+ headline: `${text(match.mapName, '未知地图')} · ${matchId}`,
331
+ matchId,
332
+ startedAt: stringOrNull(match.createdAt ?? match.startedAt),
333
+ mapName: text(match.mapName, '未知地图'),
334
+ gameMode: text(match.gameMode, '未知模式'),
335
+ duration: numberOrNull(match.duration),
336
+ players,
337
+ evidenceRefs: input.evidenceRefs?.matchIds ?? [],
338
+ };
339
+ return assertValid(validatePubgMatchDetailPresentation(presentation, known));
340
+ }
341
+ export function buildPubgMatchReviewPresentation(input) {
342
+ const data = record(input.data);
343
+ const facts = record(data.facts);
344
+ const match = record(facts.match);
345
+ const squad = record(facts.squad);
346
+ const analysis = record(data.derivedAnalysis);
347
+ const evidence = Array.isArray(facts.evidence)
348
+ ? facts.evidence.flatMap((item) => {
349
+ const id = record(item).id;
350
+ return typeof id === 'string' ? [id] : [];
351
+ })
352
+ : [];
353
+ const known = new Set([
354
+ ...(input.evidenceRefs?.matchIds ?? []),
355
+ ...(input.evidenceRefs?.playerIds ?? []),
356
+ ...evidence,
357
+ ]);
358
+ const keyMoments = textItems(analysis.turningPoints, evidence);
359
+ const highlights = textItems(analysis.awards, evidence);
360
+ const improvements = textItems(analysis.actionPlan ?? analysis.improvements);
361
+ const summary = typeof analysis.summary === 'string' && analysis.summary.trim()
362
+ ? analysis.summary
363
+ : '本场复盘事实已生成。';
364
+ const mapName = typeof match.mapName === 'string' ? match.mapName : '未知地图';
365
+ const ordinal = numberOrNull(match.ordinal);
366
+ const candidate = {
367
+ ...base(input),
368
+ type: 'pubg_match_review',
369
+ headline: `${ordinal === null ? '' : `第${ordinal}局 · `}${mapName}`,
370
+ overview: {
371
+ placement: numberOrNull(squad.placement),
372
+ kills: numberOrNull(squad.kills),
373
+ assists: numberOrNull(squad.assists),
374
+ damage: numberOrNull(squad.damage),
375
+ dbnos: numberOrNull(squad.knocks),
376
+ revives: numberOrNull(squad.revives),
377
+ },
378
+ keyMoments,
379
+ highlights,
380
+ improvements,
381
+ analysis: summary,
382
+ evidenceRefs: evidence,
383
+ };
384
+ return assertValid(validatePubgMatchReviewPresentation(candidate, known));
385
+ }
386
+ export function buildPubgPeriodReviewPresentation(input) {
387
+ const data = record(input.data);
388
+ const rawReviews = Array.isArray(data.reviews) ? data.reviews : [];
389
+ const reviewEvidence = rawReviews.flatMap((item) => {
390
+ const wrapper = record(item);
391
+ const facts = record(record(wrapper.data ?? wrapper).facts);
392
+ return Array.isArray(facts.evidence)
393
+ ? facts.evidence.flatMap((evidence) => {
394
+ const id = record(evidence).id;
395
+ return typeof id === 'string' && id.trim() ? [id] : [];
396
+ })
397
+ : [];
398
+ });
399
+ const known = knownFor(input, reviewEvidence);
400
+ const orderedMatches = rawReviews.flatMap((item, index) => {
401
+ const wrapper = record(item);
402
+ const reviewData = record(wrapper.data ?? wrapper);
403
+ const facts = record(reviewData.facts);
404
+ const match = record(facts.match ?? wrapper.match);
405
+ const squad = record(facts.squad);
406
+ const matchId = stringOrNull(wrapper.matchId ?? match.matchId);
407
+ if (!matchId)
408
+ return [];
409
+ return [
410
+ {
411
+ matchId,
412
+ label: `${index + 1}. ${text(match.mapName, '未知地图')}`,
413
+ startedAt: stringOrNull(match.createdAt ?? match.startedAt),
414
+ placement: numberOrNull(squad.placement ?? match.placement),
415
+ },
416
+ ];
417
+ });
418
+ const matches = orderedMatches.length
419
+ ? orderedMatches
420
+ : Array.isArray(data.matches)
421
+ ? data.matches.flatMap((item, index) => {
422
+ const match = record(item);
423
+ const matchId = stringOrNull(match.matchId);
424
+ return matchId
425
+ ? [
426
+ {
427
+ matchId,
428
+ label: `${index + 1}. ${text(match.mapName, '未知地图')}`,
429
+ startedAt: stringOrNull(match.startedAt),
430
+ placement: numberOrNull(match.placement),
431
+ },
432
+ ]
433
+ : [];
434
+ })
435
+ : [];
436
+ const reviewItems = rawReviews.flatMap((item) => {
437
+ const wrapper = record(item);
438
+ return textItems(record(record(wrapper.data ?? wrapper).derivedAnalysis).awards, [...known]);
439
+ });
440
+ const summaryValue = data.summary;
441
+ const summary = typeof summaryValue === 'string' && summaryValue.trim()
442
+ ? summaryValue
443
+ : `${matches.length} 场对局${input.status === 'partial' ? ',部分 Telemetry 暂不可用' : ''}。`;
444
+ const period = record(data.period);
445
+ const label = text(period.label ?? queryLabel(input, 'PUBG 周期复盘'), 'PUBG 周期复盘');
446
+ const candidate = {
447
+ ...base(input),
448
+ type: 'pubg_period_review',
449
+ period: {
450
+ label,
451
+ ...(stringOrNull(period.displayDate)
452
+ ? { displayDate: stringOrNull(period.displayDate) }
453
+ : {}),
454
+ },
455
+ summary,
456
+ orderedMatches: matches,
457
+ highlights: textItems(data.highlights, [...known, ...(input.evidenceRefs?.matchIds ?? [])])
458
+ .concat(reviewItems)
459
+ .slice(0, 12),
460
+ patterns: textItems(data.patterns, [...known]).slice(0, 12),
461
+ analysis: text(data.analysis, input.status === 'partial'
462
+ ? '周期结果存在覆盖缺口,未知事实未被补成确定值。'
463
+ : '周期复盘事实已按 Domain 返回顺序整理。'),
464
+ evidenceRefs: input.evidenceRefs?.matchIds ?? [],
465
+ };
466
+ return assertValid(validatePubgPeriodReviewPresentation(candidate, known));
467
+ }
468
+ function playerName(value) {
469
+ const row = record(value);
470
+ return text(row.name ?? row.displayName ?? row.playerId, '未知玩家');
471
+ }
472
+ const VEHICLE_NAMES = [
473
+ [/PonyCoupe/u, '小轿车'],
474
+ [/Dacia|Sedan/u, '轿车'],
475
+ [/Blanc/u, 'Blanc 跑车'],
476
+ [/Mirado/u, 'Mirado 跑车'],
477
+ [/PickupTruck/u, '皮卡'],
478
+ [/Uaz/iu, '吉普'],
479
+ [/Motorbike|Dirtbike|Scooter/u, '摩托'],
480
+ [/Buggy/u, '蹦蹦车'],
481
+ [/Rony/u, '小巴'],
482
+ [/Boat|AquaRail/u, '船'],
483
+ [/Bus|Van/u, '巴士'],
484
+ ];
485
+ /** 飞踢 / 重拳 / 皮卡撞击 / Beryl M762 走火: what one team-damage event was, in the squad's words. */
486
+ function teamHitKind(event) {
487
+ const source = text(event.source, '');
488
+ const weapon = text(event.weapon, '');
489
+ if (source === 'MELEE')
490
+ return event.meleeKind === 'KICK' ? '飞踢' : event.meleeKind === 'PUNCH' ? '重拳' : '近战';
491
+ if (source === 'VEHICLE')
492
+ return `${VEHICLE_NAMES.find(([pattern]) => pattern.test(weapon))?.[1] ?? '载具'}撞击`;
493
+ if (source === 'GUN')
494
+ return `${weapon
495
+ .replace(/^Weap/u, '')
496
+ .replace(/_C$/u, '')
497
+ .replace(/([a-z])([A-Z0-9])/gu, '$1 $2') || '枪械'} 走火`;
498
+ if (source === 'EXPLOSIVE')
499
+ return '爆炸物';
500
+ return '其他伤害';
501
+ }
502
+ function addSlice(slices, label, hitCount, damage) {
503
+ const slice = slices.get(label) ?? { label, hitCount: 0, damage: 0 };
504
+ slice.hitCount += hitCount;
505
+ slice.damage += damage;
506
+ slices.set(label, slice);
507
+ }
508
+ function sortedSlices(slices) {
509
+ return [...slices.values()]
510
+ .map((slice) => ({ ...slice, damage: Math.round(slice.damage * 100) / 100 }))
511
+ .sort((a, b) => b.hitCount - a.hitCount || b.damage - a.damage);
512
+ }
513
+ /** Reads the per-match events behind the direction totals; undefined when the result carried none. */
514
+ function teamDamageLedger(data, directions) {
515
+ const matches = Array.isArray(data.matches) ? data.matches.map(record) : [];
516
+ const directionIndex = new Map(directions.map((direction, index) => [`${direction.actorId}:${direction.victimId}`, index]));
517
+ const names = new Map();
518
+ for (const direction of directions) {
519
+ if (direction.actorId)
520
+ names.set(direction.actorId, direction.actor);
521
+ if (direction.victimId)
522
+ names.set(direction.victimId, direction.victim);
523
+ }
524
+ const sources = new Map();
525
+ const perDirection = directions.map(() => new Map());
526
+ const perMatch = [];
527
+ let events = 0;
528
+ matches.forEach((match, ordinal) => {
529
+ const pairs = new Map();
530
+ for (const raw of Array.isArray(match.teamDamage) ? match.teamDamage : []) {
531
+ const event = record(raw);
532
+ const index = directionIndex.get(`${stringOrNull(event.actorPlayerId)}:${stringOrNull(event.victimPlayerId)}`);
533
+ if (index === undefined)
534
+ continue; // a direction the query filtered out
535
+ const hitCount = numberOrNull(event.hitCount) ?? 0;
536
+ const damage = numberOrNull(event.damage) ?? 0;
537
+ const kind = teamHitKind(event);
538
+ events += 1;
539
+ addSlice(sources, kind, hitCount, damage);
540
+ addSlice(perDirection[index], kind, hitCount, damage);
541
+ const direction = directions[index];
542
+ const pair = pairs.get(`${index}`) ?? {
543
+ actor: direction.actor,
544
+ victim: direction.victim,
545
+ hitCount: 0,
546
+ damage: 0,
547
+ };
548
+ pair.hitCount += hitCount;
549
+ pair.damage += damage;
550
+ pairs.set(`${index}`, pair);
551
+ }
552
+ if (!pairs.size)
553
+ return;
554
+ const list = [...pairs.values()]
555
+ .map((pair) => ({ ...pair, damage: Math.round(pair.damage * 100) / 100 }))
556
+ .sort((a, b) => b.damage - a.damage);
557
+ const placement = numberOrNull(match.placement);
558
+ const map = sessionMapName(text(match.mapName, ''));
559
+ const at = stringOrNull(match.startedAtLocal);
560
+ perMatch.push({
561
+ label: `第 ${ordinal + 1} 局(${map}${placement === null ? '' : ` #${placement}`}${at ? `,${at}` : ''})`,
562
+ hitCount: list.reduce((total, pair) => total + pair.hitCount, 0),
563
+ damage: Math.round(list.reduce((total, pair) => total + pair.damage, 0) * 100) / 100,
564
+ pairs: list,
565
+ });
566
+ });
567
+ if (!events)
568
+ return undefined;
569
+ const actors = new Set(directions.map((direction) => direction.actor));
570
+ return {
571
+ sources: sortedSlices(sources),
572
+ directionSources: perDirection.map(sortedSlices),
573
+ highlights: perMatch.sort((a, b) => b.damage - a.damage).slice(0, 2),
574
+ quiet: [...new Set(directions.map((direction) => direction.victim))].filter((victim) => !actors.has(victim)),
575
+ };
576
+ }
577
+ export function buildPubgTeamDamagePresentation(input) {
578
+ const data = record(input.data);
579
+ const known = knownFor(input);
580
+ const rawDirections = Array.isArray(data.directions)
581
+ ? data.directions.flatMap((item) => {
582
+ const row = record(item);
583
+ const actorId = stringOrNull(record(row.actor).playerId);
584
+ const victimId = stringOrNull(record(row.victim).playerId);
585
+ if (input.teamDamage?.actorPlayerId && actorId !== input.teamDamage.actorPlayerId)
586
+ return [];
587
+ if (input.teamDamage?.victimPlayerId && victimId !== input.teamDamage.victimPlayerId)
588
+ return [];
589
+ const actor = playerName(row.actor);
590
+ const victim = playerName(row.victim);
591
+ return [
592
+ {
593
+ actor,
594
+ victim,
595
+ actorId,
596
+ victimId,
597
+ hitCount: numberOrNull(row.hitCount),
598
+ damage: numberOrNull(row.damage),
599
+ knownHitCount: numberOrNull(row.knownHitCount) ?? numberOrNull(row.hitCount) ?? 0,
600
+ knownDamage: numberOrNull(row.knownDamage) ?? numberOrNull(row.damage) ?? 0,
601
+ complete: row.complete === true,
602
+ evidenceRefs: evidenceFor(row, known),
603
+ },
604
+ ];
605
+ })
606
+ : [];
607
+ const completeCoverage = input.coverage?.complete ?? data.complete === true;
608
+ let actorTotals;
609
+ let rankingBasis;
610
+ if (input.teamDamage?.aggregateByActor) {
611
+ const totals = [
612
+ ...rawDirections
613
+ .reduce((aggregates, row) => {
614
+ const key = row.actorId ?? row.actor;
615
+ const total = aggregates.get(key) ?? {
616
+ actor: row.actor,
617
+ damage: 0,
618
+ hitCount: 0,
619
+ knownDamage: 0,
620
+ knownHitCount: 0,
621
+ complete: completeCoverage,
622
+ evidenceRefs: new Set(),
623
+ };
624
+ total.knownDamage += row.knownDamage;
625
+ total.knownHitCount += row.knownHitCount;
626
+ if (row.damage === null || row.hitCount === null || !row.complete)
627
+ total.complete = false;
628
+ else {
629
+ total.damage += row.damage;
630
+ total.hitCount += row.hitCount;
631
+ }
632
+ for (const ref of row.evidenceRefs)
633
+ total.evidenceRefs.add(ref);
634
+ aggregates.set(key, total);
635
+ return aggregates;
636
+ }, new Map())
637
+ .values(),
638
+ ].map((total) => ({
639
+ ...total,
640
+ damage: completeCoverage && total.complete ? total.damage : null,
641
+ hitCount: completeCoverage && total.complete ? total.hitCount : null,
642
+ complete: completeCoverage && total.complete,
643
+ evidenceRefs: [...total.evidenceRefs],
644
+ }));
645
+ const rankByCompleteDamage = completeCoverage && totals.every((total) => total.complete);
646
+ rankingBasis = rankByCompleteDamage ? 'damage' : 'knownDamage';
647
+ totals.sort((left, right) => (rankByCompleteDamage ? (right.damage ?? 0) : right.knownDamage) -
648
+ (rankByCompleteDamage ? (left.damage ?? 0) : left.knownDamage) ||
649
+ left.actor.localeCompare(right.actor));
650
+ actorTotals = totals.map((total, index) => ({ ...total, position: index + 1 }));
651
+ }
652
+ const ledger = teamDamageLedger(data, rawDirections);
653
+ const directions = rawDirections.map(({ actorId: _actorId, victimId: _victimId, knownDamage, knownHitCount, ...direction }) => ({
654
+ ...direction,
655
+ ...(input.presentationStyle === 'public_agent' ? { knownDamage, knownHitCount } : {}),
656
+ }));
657
+ const source = stringOrNull(data.source);
658
+ const meleeKind = stringOrNull(data.meleeKind);
659
+ const direction = text(data.direction, directions.length
660
+ ? directions.map((item) => `${item.actor} → ${item.victim}`).join('、')
661
+ : 'all directions');
662
+ const publicDamageAction = meleeKind === 'KICK'
663
+ ? '队友踢击'
664
+ : meleeKind === 'PUNCH'
665
+ ? '队友拳击'
666
+ : meleeKind === 'OTHER'
667
+ ? '队友近战'
668
+ : '队友伤害';
669
+ const publicHeadline = `${publicPeriodLabel(input, '')}${publicDamageAction}`;
670
+ const totalHitCount = numberOrNull(data.totalHitCount);
671
+ const totalDamage = numberOrNull(data.totalDamage);
672
+ const summary = input.status === 'partial' || !completeCoverage
673
+ ? input.presentationStyle === 'public_agent' && !directions.length
674
+ ? '队友伤害资料不可用或覆盖不完整,不能据此认定为 0。'
675
+ : '部分 Telemetry 暂不可用,未知数量没有被当作 0。'
676
+ : actorTotals
677
+ ? `队友伤害按已覆盖资料汇总,共 ${actorTotals.length} 名有记录队员。`
678
+ : directions.length
679
+ ? `共 ${directions.length} 个方向。`
680
+ : statusMessage(input.status ?? 'ok') || '未发现队友动作。';
681
+ const candidate = {
682
+ ...base(input),
683
+ type: 'pubg_team_damage',
684
+ headline: input.presentationStyle === 'public_agent' ? publicHeadline : 'PUBG 队友动作/误伤',
685
+ direction,
686
+ source,
687
+ meleeKind,
688
+ totalHitCount,
689
+ totalDamage,
690
+ directions,
691
+ ...(ledger ? { ledger } : {}),
692
+ ...(actorTotals ? { actorTotals, ...(rankingBasis ? { rankingBasis } : {}) } : {}),
693
+ summary,
694
+ evidenceRefs: input.evidenceRefs?.matchIds ?? [],
695
+ };
696
+ return assertValid(validatePubgTeamDamagePresentation(candidate, known));
697
+ }
698
+ /** Build one validated presentation for any registered native PUBG tool. */
699
+ export function buildPubgPresentation(input) {
700
+ switch (input.toolName) {
701
+ case 'pubg_query_stats':
702
+ return buildPubgStatsPresentation(input);
703
+ case 'pubg_search_matches':
704
+ return buildPubgMatchListPresentation(input);
705
+ case 'pubg_compare_stats':
706
+ return buildPubgComparisonPresentation(input);
707
+ case 'pubg_get_match':
708
+ return buildPubgMatchDetailPresentation(input);
709
+ case 'pubg_get_review_facts':
710
+ if (input.status === 'error' || input.status === 'no_matches')
711
+ return buildPubgStatusPresentation(input);
712
+ return buildPubgMatchReviewPresentation(input);
713
+ case 'pubg_get_period_review':
714
+ if (input.status === 'error')
715
+ return buildPubgStatusPresentation(input);
716
+ return buildPubgPeriodReviewPresentation(input);
717
+ case 'pubg_query_team_damage':
718
+ return buildPubgTeamDamagePresentation(input);
719
+ case 'pubg_resolve_players':
720
+ case 'pubg_prefetch_telemetry':
721
+ case 'pubg_telemetry_sync_report':
722
+ default:
723
+ return buildPubgStatusPresentation(input);
724
+ }
725
+ }