@rine-kit/pubg-share-page 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,72 @@
1
+ import type { NormalizedMatch, ReviewShareRecord } from '@rine-kit/pubg-domain';
2
+ import type { StoryContext } from './context.js';
3
+ /** A share visitor's cookie: only the share routes read it, and it never opens anything else. */
4
+ export declare const SHARE_COOKIE = "pubg_share";
5
+ /** The room's team as the page shows it, and the stored matches the share lists (those that are stored). */
6
+ export interface ShareContent {
7
+ squad: {
8
+ id: string;
9
+ label: string;
10
+ members: {
11
+ id: string;
12
+ name: string;
13
+ }[];
14
+ };
15
+ matches: NormalizedMatch[];
16
+ }
17
+ /**
18
+ * Where a host's data comes from: RINE reads Postgres, Lab can read SQLite. The handler never touches a database,
19
+ * and never sees a token — only its SHA-256.
20
+ */
21
+ export interface ShareStore {
22
+ /** The share with this token hash, or null. Revoked and expired shares may be returned; the handler rejects them. */
23
+ findShare(tokenHash: string): Promise<ReviewShareRecord | null>;
24
+ /**
25
+ * The team and the matches a share lists. Must be limited to `share.matchIds` and to the share's own team — this
26
+ * is what a link is allowed to read. Null when the team is gone.
27
+ */
28
+ loadContent(share: ReviewShareRecord): Promise<ShareContent | null>;
29
+ }
30
+ /** What the handler needs of an HTTP request, so any server (Fastify, Express, a bare http server) can host it. */
31
+ export interface ShareRequest {
32
+ method?: string;
33
+ /** The URL path, as received (percent-encoded), without the query string. */
34
+ path: string;
35
+ /** The Cookie header. */
36
+ cookie?: string | undefined;
37
+ /** True when the visitor reached the host over https (decides the cookie's Secure flag). */
38
+ https?: boolean;
39
+ /** Who is asking, for `allow`. */
40
+ remote?: string;
41
+ }
42
+ export interface ShareResponse {
43
+ status: number;
44
+ headers: Record<string, string>;
45
+ body: string | Buffer;
46
+ }
47
+ export interface ShareHandlerOptions {
48
+ store: ShareStore;
49
+ /** Telemetry analysis for the story view; null = the page shows the stored numbers only (story → 503). */
50
+ story?: StoryContext | null;
51
+ /** Directory with `<Map>_Main.jpg|png`; unset = no map artwork. */
52
+ mapDirectory?: string | undefined;
53
+ /** Called before each request that carries a token; false answers 429. */
54
+ allow?: (remote: string) => boolean;
55
+ now?: () => number;
56
+ }
57
+ export type ShareHandler = (request: ShareRequest) => Promise<ShareResponse | null>;
58
+ /** The chat text of a report as HTML: escaped first, then **bold** and line breaks (the only markup a report uses). */
59
+ export declare function reportHtml(text: string): string;
60
+ /**
61
+ * The read-only share surface of a PUBG report link, as one function from request to response.
62
+ *
63
+ * Access rules, enforced here for every route and not left to the host:
64
+ * - the only way in is a token: `/s/<token>` opens the page and sets a cookie holding it, and every data route
65
+ * (`/api/share/*`, `/api/maps/*`, `/share`) reads that cookie — there is no overview and no listing without one;
66
+ * - a token is 22 characters of url-safe base64, only its SHA-256 reaches the store;
67
+ * - a link opens exactly the matches it lists; a revoked, expired, unknown or malformed token all answer alike;
68
+ * - the opposing teams are anonymised before a story leaves the server.
69
+ * `/assets/*` (the page's own program, nothing about any player) is the one public path.
70
+ * Returns null for a path that is not a share route, so the host can fall through to its own 404.
71
+ */
72
+ export declare function createShareHandler(options: ShareHandlerOptions): ShareHandler;
@@ -0,0 +1,234 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync, statSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { CLIENT_DIST, clientAsset, clientBuilt, renderSharePage, toResearchSquad, } from './render.js';
5
+ import { aliasEnemies, escapeHtml, shareViewPayload } from './share-page.js';
6
+ import { computeMatchStory } from './story.js';
7
+ /** A share visitor's cookie: only the share routes read it, and it never opens anything else. */
8
+ export const SHARE_COOKIE = 'pubg_share';
9
+ const TOKEN = /^[A-Za-z0-9_-]{22}$/u;
10
+ const MAP_IMAGE = /^[A-Za-z0-9]+_Main$/u;
11
+ const MATCH_ID = /^[A-Za-z0-9_.-]{1,64}$/u;
12
+ const CONTENT_TTL_MS = 60_000;
13
+ /** What the tactical page may load: itself, inline script/style it carries, images, same-origin fetches. */
14
+ const PAGE_CSP = "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'";
15
+ const TEXT_CSP = "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'";
16
+ const CONTENT_TYPES = {
17
+ '.js': 'text/javascript; charset=utf-8',
18
+ '.css': 'text/css; charset=utf-8',
19
+ '.svg': 'image/svg+xml',
20
+ '.png': 'image/png',
21
+ '.json': 'application/json; charset=utf-8',
22
+ '.map': 'application/json',
23
+ };
24
+ /** The chat text of a report as HTML: escaped first, then **bold** and line breaks (the only markup a report uses). */
25
+ export function reportHtml(text) {
26
+ return escapeHtml(text)
27
+ .replace(/\*\*([^*\n]+)\*\*/gu, '<strong>$1</strong>')
28
+ .replace(/\n/gu, '<br>');
29
+ }
30
+ const textPage = (title, body) => `<!doctype html>
31
+ <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
32
+ <meta name="robots" content="noindex,nofollow"><title>${escapeHtml(title)}</title>
33
+ <style>
34
+ :root{color-scheme:dark light;--bg:#14121a;--fg:#ece9f1;--muted:#a9a3b5;--card:#1d1a26;--line:#2d2938}
35
+ @media (prefers-color-scheme:light){:root{--bg:#f6f4f8;--fg:#1b1822;--muted:#5d5769;--card:#fff;--line:#e0dce6}}
36
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.65 system-ui,"PingFang SC","Microsoft YaHei",sans-serif}
37
+ main{max-width:720px;margin:0 auto;padding:24px 16px 48px}
38
+ .card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:18px 20px;overflow-wrap:anywhere}
39
+ .meta{color:var(--muted);font-size:13px;margin-top:14px}
40
+ h1{font-size:18px;margin:0 0 14px}
41
+ </style></head><body><main>${body}</main></body></html>`;
42
+ function cookieToken(header) {
43
+ for (const part of (header ?? '').split(';')) {
44
+ const [name, ...value] = part.trim().split('=');
45
+ if (name === SHARE_COOKIE)
46
+ return value.join('=');
47
+ }
48
+ return null;
49
+ }
50
+ const sha256 = (value) => createHash('sha256').update(value).digest('hex');
51
+ function segments(path) {
52
+ try {
53
+ return path.split('/').map((part) => decodeURIComponent(part));
54
+ }
55
+ catch {
56
+ return null;
57
+ }
58
+ }
59
+ /**
60
+ * The read-only share surface of a PUBG report link, as one function from request to response.
61
+ *
62
+ * Access rules, enforced here for every route and not left to the host:
63
+ * - the only way in is a token: `/s/<token>` opens the page and sets a cookie holding it, and every data route
64
+ * (`/api/share/*`, `/api/maps/*`, `/share`) reads that cookie — there is no overview and no listing without one;
65
+ * - a token is 22 characters of url-safe base64, only its SHA-256 reaches the store;
66
+ * - a link opens exactly the matches it lists; a revoked, expired, unknown or malformed token all answer alike;
67
+ * - the opposing teams are anonymised before a story leaves the server.
68
+ * `/assets/*` (the page's own program, nothing about any player) is the one public path.
69
+ * Returns null for a path that is not a share route, so the host can fall through to its own 404.
70
+ */
71
+ export function createShareHandler(options) {
72
+ const { store, story = null, mapDirectory, allow, now = Date.now } = options;
73
+ const loaded = new Map();
74
+ const open = async (token) => {
75
+ if (!token || !TOKEN.test(token))
76
+ return null;
77
+ const share = await store.findShare(sha256(token));
78
+ if (!share || share.revokedAt !== null || Date.parse(share.expiresAt) <= now())
79
+ return null;
80
+ return { token, share };
81
+ };
82
+ /** The share's team and stored matches; kept for a minute so a story click costs no query. */
83
+ const contentOf = (found) => {
84
+ const key = sha256(found.token);
85
+ const hit = loaded.get(key);
86
+ if (hit && now() - hit.at < CONTENT_TTL_MS)
87
+ return hit.value.then((entry) => entry.content);
88
+ const value = store.loadContent(found.share).then((content) => ({ share: found.share, content }));
89
+ loaded.set(key, { at: now(), value });
90
+ value.catch(() => loaded.delete(key));
91
+ if (loaded.size > 200)
92
+ for (const [k, v] of loaded)
93
+ if (now() - v.at > CONTENT_TTL_MS)
94
+ loaded.delete(k);
95
+ return value.then((entry) => entry.content);
96
+ };
97
+ const respond = (status, csp, body, type, extra = {}) => ({
98
+ status,
99
+ headers: {
100
+ 'cache-control': 'no-store',
101
+ 'x-robots-tag': 'noindex',
102
+ 'content-security-policy': csp,
103
+ 'referrer-policy': 'no-referrer',
104
+ 'x-content-type-options': 'nosniff',
105
+ 'content-type': type,
106
+ ...extra,
107
+ },
108
+ body,
109
+ });
110
+ const json = (status, value) => respond(status, TEXT_CSP, JSON.stringify(value), 'application/json; charset=utf-8');
111
+ const tooMany = () => ({
112
+ status: 429,
113
+ headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' },
114
+ body: 'too many requests',
115
+ });
116
+ const gone = () => respond(404, TEXT_CSP, textPage('分享', '<div class="card"><h1>这个链接已失效</h1>链接过期了,或者发它的人撤回了。</div>'), 'text/html; charset=utf-8');
117
+ const sendPage = async (request, found) => {
118
+ const text = (() => {
119
+ try {
120
+ return JSON.parse(found.share.presentationJson);
121
+ }
122
+ catch {
123
+ return null;
124
+ }
125
+ })();
126
+ const content = clientBuilt() ? await contentOf(found) : null;
127
+ if (content && text) {
128
+ const squad = toResearchSquad(content.squad, content.matches.length);
129
+ const html = renderSharePage(readFileSync(join(CLIENT_DIST, 'index.html'), 'utf8'), found.share, squad, new Map(content.matches.map((match) => [match.matchId, match])));
130
+ const seconds = Math.max(0, Math.floor((Date.parse(found.share.expiresAt) - now()) / 1000));
131
+ const secure = request.https ? '; Secure' : '';
132
+ return respond(200, PAGE_CSP, html, 'text/html; charset=utf-8', {
133
+ 'set-cookie': `${SHARE_COOKIE}=${found.token}; Path=/; Max-Age=${seconds}; HttpOnly; SameSite=Strict${secure}`,
134
+ });
135
+ }
136
+ // The page is not built, or the team is gone: the report text alone, still only for a valid link.
137
+ const body = typeof text?.displayText === 'string' ? text.displayText : '';
138
+ if (!body)
139
+ return gone();
140
+ const title = typeof text?.title === 'string' && text.title ? text.title : 'PUBG 战绩';
141
+ const matches = typeof text?.matchCount === 'number' ? `共 ${text.matchCount} 场对局 · ` : '';
142
+ return respond(200, TEXT_CSP, textPage(title, `<div class="card">${reportHtml(body)}</div><p class="meta">${matches}链接 7 天内有效,不需要登录</p>`), 'text/html; charset=utf-8');
143
+ };
144
+ return async (request) => {
145
+ if ((request.method ?? 'GET') !== 'GET')
146
+ return null;
147
+ const parts = segments(request.path);
148
+ if (!parts)
149
+ return null;
150
+ const [, first, second, third, fourth, ...rest] = parts;
151
+ const remote = request.remote ?? '';
152
+ if (first === 'assets' && second !== undefined) {
153
+ const file = clientAsset(request.path);
154
+ if (!file)
155
+ return { status: 404, headers: { 'content-type': 'application/json' }, body: '{"error":"not_found"}' };
156
+ const type = CONTENT_TYPES[file.slice(file.lastIndexOf('.'))] ?? 'application/octet-stream';
157
+ // Vite names every built asset by its content hash, so a browser may keep it for good.
158
+ return {
159
+ status: 200,
160
+ headers: {
161
+ 'cache-control': 'public, max-age=31536000, immutable',
162
+ 'x-content-type-options': 'nosniff',
163
+ 'content-type': type,
164
+ },
165
+ body: readFileSync(file),
166
+ };
167
+ }
168
+ const isPage = (first === 's' && second !== undefined && third === undefined) || (first === 'share' && second === undefined);
169
+ const isView = first === 'api' && second === 'share' && third === 'view' && fourth === undefined;
170
+ const isStory = first === 'api' && second === 'share' && third === 'matches' && fourth !== undefined && rest.length === 1 && rest[0] === 'story';
171
+ const isMap = first === 'api' && second === 'maps' && third !== undefined && fourth === undefined;
172
+ if (!isPage && !isView && !isStory && !isMap)
173
+ return null;
174
+ if (allow && !allow(remote))
175
+ return tooMany();
176
+ if (isPage) {
177
+ // /s/<token> brings the token in the address; /share is the same page by cookie after the page has dropped it.
178
+ const found = await open(first === 's' ? (second ?? null) : cookieToken(request.cookie));
179
+ return found ? sendPage(request, found) : gone();
180
+ }
181
+ const found = await open(cookieToken(request.cookie));
182
+ if (!found)
183
+ return json(401, { error: 'share_required' });
184
+ if (isView) {
185
+ const content = await contentOf(found);
186
+ if (!content)
187
+ return json(404, { error: 'not_found' });
188
+ const squad = toResearchSquad(content.squad, content.matches.length);
189
+ return json(200, shareViewPayload(found.share, squad, new Map(content.matches.map((match) => [match.matchId, match]))));
190
+ }
191
+ if (isStory) {
192
+ const matchId = fourth ?? '';
193
+ // A link opens only the matches it lists.
194
+ if (!MATCH_ID.test(matchId) || !found.share.matchIds.includes(matchId))
195
+ return json(404, { error: 'not_in_share' });
196
+ const content = await contentOf(found);
197
+ const match = content?.matches.find((candidate) => candidate.matchId === matchId);
198
+ if (!content || !match)
199
+ return json(404, { error: 'not_in_share' });
200
+ if (!story)
201
+ return json(503, { error: 'story_unavailable' });
202
+ const squad = toResearchSquad(content.squad, content.matches.length);
203
+ const result = await computeMatchStory(story, squad, match);
204
+ return json(200, {
205
+ ...result,
206
+ story: result.story
207
+ ? aliasEnemies(result.story)
208
+ : null,
209
+ });
210
+ }
211
+ // map artwork
212
+ const name = third ?? '';
213
+ if (!mapDirectory || !MAP_IMAGE.test(name))
214
+ return json(404, { error: 'not_found' });
215
+ for (const [extension, type] of [
216
+ ['jpg', 'image/jpeg'],
217
+ ['png', 'image/png'],
218
+ ]) {
219
+ const file = join(mapDirectory, `${name}.${extension}`);
220
+ if (existsSync(file) && statSync(file).isFile()) {
221
+ return {
222
+ status: 200,
223
+ headers: {
224
+ 'cache-control': 'private, max-age=86400',
225
+ 'x-content-type-options': 'nosniff',
226
+ 'content-type': type,
227
+ },
228
+ body: readFileSync(file),
229
+ };
230
+ }
231
+ }
232
+ return json(404, { error: 'map_image_missing' });
233
+ };
234
+ }
@@ -0,0 +1,5 @@
1
+ export { analysisCacheVersion, StoryContext } from './context.js';
2
+ export { createShareHandler, reportHtml, SHARE_COOKIE, type ShareContent, type ShareHandler, type ShareHandlerOptions, type ShareRequest, type ShareResponse, type ShareStore, } from './handler.js';
3
+ export { clientBuilt, CLIENT_DIST, renderSharePage, toResearchSquad } from './render.js';
4
+ export { computeMatchStory } from './story.js';
5
+ export { aliasEnemies, escapeHtml, messagePage, shareViewPayload } from './share-page.js';
@@ -0,0 +1,5 @@
1
+ export { analysisCacheVersion, StoryContext } from './context.js';
2
+ export { createShareHandler, reportHtml, SHARE_COOKIE, } from './handler.js';
3
+ export { clientBuilt, CLIENT_DIST, renderSharePage, toResearchSquad } from './render.js';
4
+ export { computeMatchStory } from './story.js';
5
+ export { aliasEnemies, escapeHtml, messagePage, shareViewPayload } from './share-page.js';
@@ -0,0 +1,18 @@
1
+ import { type NormalizedMatch } from '@rine-kit/pubg-domain';
2
+ import { type MatchHighlight, type CombatQualityMatchStats, type DeathRecord, type FieldMatchStats, type FightMatchStats, type LandingSample, type LobbyMatchStats, type MatchRotation, type PlayerStyleMatch, type StoryDown, type StreakMatchStats } from '@rine-kit/pubg-intelligence';
3
+ export interface MatchTelemetryAnalysis {
4
+ highlights: MatchHighlight[];
5
+ quality: CombatQualityMatchStats;
6
+ deaths: DeathRecord[];
7
+ landings: LandingSample[];
8
+ field: FieldMatchStats;
9
+ fights: FightMatchStats;
10
+ style: Record<string, PlayerStyleMatch>;
11
+ lobby: Record<string, LobbyMatchStats>;
12
+ streaks: StreakMatchStats;
13
+ /** Why each squad knock-down happened, and how the squad moved with the circle. */
14
+ downs: StoryDown[];
15
+ rotation: MatchRotation;
16
+ }
17
+ /** Every per-match derivation for a squad from one raw payload. Pure and CPU-bound, so it runs on a worker thread. */
18
+ export declare function computeMatchAnalysis(raw: Uint8Array, match: NormalizedMatch, memberIds: readonly string[]): MatchTelemetryAnalysis;
@@ -0,0 +1,51 @@
1
+ import { parseTelemetryPayload } from '@rine-kit/pubg-domain';
2
+ import { analyzeCombatQuality, analyzeDeaths, analyzeFieldTelemetry, analyzeFights, analyzeLobby, analyzeMatchStory, analyzeStreaks, identifyMatchHighlights, analyzeStyleTelemetry, emptyFights, extractLandings, landingPlayerRef, normalizeBattleTelemetry, reconstructBattleEpisodes, } from '@rine-kit/pubg-intelligence';
3
+ /** Every per-match derivation for a squad from one raw payload. Pure and CPU-bound, so it runs on a worker thread. */
4
+ export function computeMatchAnalysis(raw, match, memberIds) {
5
+ // Decompress and parse once: every analyser accepts the parsed event list, and re-parsing a 25 MB file for each of
6
+ // them was most of the cost.
7
+ const payload = parseTelemetryPayload(raw);
8
+ const members = new Set(memberIds);
9
+ const memberRefs = new Set(memberIds.map(landingPlayerRef));
10
+ const telemetry = normalizeBattleTelemetry(payload, match);
11
+ const landings = extractLandings(payload, match, new Set(match.players.map((player) => player.accountId)));
12
+ const trackedPlayerIds = match.players
13
+ .filter((player) => members.has(player.accountId))
14
+ .map((player) => player.accountId);
15
+ const reconstruction = reconstructBattleEpisodes({ match, telemetry, trackedPlayerIds });
16
+ const fightStats = analyzeFights(reconstruction, match.matchId, trackedPlayerIds);
17
+ const rawStyle = analyzeStyleTelemetry(payload, new Set(trackedPlayerIds));
18
+ const style = {};
19
+ for (const player of match.players) {
20
+ const raw = rawStyle[player.accountId];
21
+ if (!raw || !members.has(player.accountId))
22
+ continue;
23
+ style[player.accountId] = {
24
+ ...raw,
25
+ minutes: Math.max(0, player.survivalTime) / 60,
26
+ fights: fightStats.roles[player.accountId] ?? emptyFights(),
27
+ };
28
+ }
29
+ const story = analyzeMatchStory(payload, new Set(trackedPlayerIds));
30
+ const streaks = analyzeStreaks(payload, new Set(trackedPlayerIds));
31
+ return {
32
+ highlights: identifyMatchHighlights({
33
+ payload,
34
+ match,
35
+ memberIds: trackedPlayerIds,
36
+ story,
37
+ streaks,
38
+ telemetry,
39
+ }),
40
+ quality: analyzeCombatQuality(reconstruction),
41
+ deaths: analyzeDeaths(telemetry, trackedPlayerIds),
42
+ landings: landings.filter((landing) => memberRefs.has(landing.playerRef)),
43
+ field: analyzeFieldTelemetry(payload, new Set(trackedPlayerIds)),
44
+ fights: fightStats,
45
+ style,
46
+ lobby: analyzeLobby(payload, new Set(trackedPlayerIds)),
47
+ streaks,
48
+ downs: story.downs,
49
+ rotation: story.rotation,
50
+ };
51
+ }
@@ -0,0 +1,2 @@
1
+ /** A player name safe to show on a page anyone with the link can open (phone numbers and the like are hidden). */
2
+ export declare function safePlayerName(value: string, index: number): string;
@@ -0,0 +1,6 @@
1
+ import { redactSensitiveText } from '@rine-kit/pubg-intelligence';
2
+ /** A player name safe to show on a page anyone with the link can open (phone numbers and the like are hidden). */
3
+ export function safePlayerName(value, index) {
4
+ const normalized = redactSensitiveText(value.trim()).replace(/\[手机号已隐藏\]/gu, '匿名队员');
5
+ return normalized || `队员 ${index + 1}`;
6
+ }
@@ -0,0 +1,24 @@
1
+ import type { NormalizedMatch, ReviewShareRecord } from '@rine-kit/pubg-domain';
2
+ import type { ResearchSquad } from '@rine-kit/pubg-intelligence';
3
+ /**
4
+ * The built page. From a checkout it sits at `<package>/dist/client` (two levels above `src/server`); from the
5
+ * published package this file is `dist/server/render.js` and the page is its sibling `dist/client`.
6
+ */
7
+ export declare const CLIENT_DIST: string;
8
+ export declare const clientBuilt: () => boolean;
9
+ /** A file of the built page for a request path under /assets/, or null (never outside the build's assets directory). */
10
+ export declare function clientAsset(pathname: string): string | null;
11
+ /**
12
+ * The page shell with the share's view carried inline (so the page needs no extra round trip) and an og title.
13
+ * The caller has already checked the link; nothing here reads a database.
14
+ */
15
+ export declare function renderSharePage(shell: string, share: ReviewShareRecord, squad: ResearchSquad, matches: ReadonlyMap<string, NormalizedMatch>): string;
16
+ /** The research squad the page works with: the room's team, whose members are the only players in the stored matches. */
17
+ export declare function toResearchSquad(team: {
18
+ id: string;
19
+ label: string;
20
+ members: {
21
+ id: string;
22
+ name: string;
23
+ }[];
24
+ }, matchCount: number): ResearchSquad;
@@ -0,0 +1,45 @@
1
+ import { existsSync, statSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { bootSteps, escapeHtml, inlineJson, shareTitle, shareViewPayload } from './share-page.js';
5
+ /**
6
+ * The built page. From a checkout it sits at `<package>/dist/client` (two levels above `src/server`); from the
7
+ * published package this file is `dist/server/render.js` and the page is its sibling `dist/client`.
8
+ */
9
+ export const CLIENT_DIST = (() => {
10
+ const here = dirname(fileURLToPath(import.meta.url));
11
+ const published = resolve(here, '../client');
12
+ return existsSync(join(published, 'index.html')) ? published : resolve(here, '../../dist/client');
13
+ })();
14
+ export const clientBuilt = () => existsSync(join(CLIENT_DIST, 'index.html'));
15
+ /** A file of the built page for a request path under /assets/, or null (never outside the build's assets directory). */
16
+ export function clientAsset(pathname) {
17
+ if (!pathname.startsWith('/assets/'))
18
+ return null;
19
+ const target = resolve(CLIENT_DIST, `.${pathname}`);
20
+ if (!target.startsWith(`${join(CLIENT_DIST, 'assets')}/`))
21
+ return null;
22
+ return existsSync(target) && statSync(target).isFile() ? target : null;
23
+ }
24
+ /**
25
+ * The page shell with the share's view carried inline (so the page needs no extra round trip) and an og title.
26
+ * The caller has already checked the link; nothing here reads a database.
27
+ */
28
+ export function renderSharePage(shell, share, squad, matches) {
29
+ const { title, description } = shareTitle(share);
30
+ const head = `<meta name="robots" content="noindex,nofollow"><meta property="og:title" content="${escapeHtml(title)}"><meta property="og:description" content="${escapeHtml(description)}"><meta property="og:type" content="website">`;
31
+ const view = `<script>window.__SHARE_VIEW__=${inlineJson(shareViewPayload(share, squad, matches))}</script>`;
32
+ return shell
33
+ .replace(/<title>[^<]*<\/title>/u, `<title>${escapeHtml(title)}</title>${head}${view}`)
34
+ .replace('<div id="root"></div>', `<div id="root">${bootSteps(share.matchIds.length)}</div>`);
35
+ }
36
+ /** The research squad the page works with: the room's team, whose members are the only players in the stored matches. */
37
+ export function toResearchSquad(team, matchCount) {
38
+ return {
39
+ id: team.id,
40
+ label: team.label,
41
+ memberIds: team.members.map((member) => member.id),
42
+ members: team.members,
43
+ matchCount,
44
+ };
45
+ }
@@ -0,0 +1,37 @@
1
+ import type { NormalizedMatch, ReviewShareRecord } from '@rine-kit/pubg-domain';
2
+ import { type ResearchSquad } from '@rine-kit/pubg-intelligence';
3
+ export declare const escapeHtml: (value: string) => string;
4
+ export declare function shareTitle(record: ReviewShareRecord): {
5
+ title: string;
6
+ description: string;
7
+ };
8
+ export declare function messagePage(title: string, body: string, refresh?: string): string;
9
+ export interface AliasableStory {
10
+ fights: Array<{
11
+ start: number;
12
+ enemies: Array<{
13
+ team: string;
14
+ }>;
15
+ }>;
16
+ downs: Array<{
17
+ t: number;
18
+ attackerTeam: string | null;
19
+ }>;
20
+ enemies: Array<{
21
+ id: string;
22
+ team: string;
23
+ route: Array<[number, number, number]>;
24
+ }>;
25
+ }
26
+ /** Opposing teams become 敌方 A, B, … in the order the squad met them; opposing account ids become opaque. */
27
+ export declare function aliasEnemies<T extends AliasableStory>(story: T): T;
28
+ /** What GET /api/share/view returns; the /s/ page also carries it inline so the page needs no extra round trip. */
29
+ export declare function shareViewPayload(share: ReviewShareRecord, squad: ResearchSquad, matches: ReadonlyMap<string, NormalizedMatch>): Record<string, unknown>;
30
+ /** JSON inside a <script>: nothing in it may close the tag or start a comment. */
31
+ export declare const inlineJson: (value: unknown) => string;
32
+ /**
33
+ * Shown before the page script has arrived (it is replaced as soon as the app mounts). The steps are the real ones:
34
+ * the server has checked the link and read the review by the time this HTML exists; the browser still has to fetch
35
+ * the page program and build the cards.
36
+ */
37
+ export declare function bootSteps(matchCount: number): string;
@@ -0,0 +1,120 @@
1
+ import { mapDisplayName } from '@rine-kit/pubg-intelligence';
2
+ export const escapeHtml = (value) => value.replace(/[&<>"']/gu, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
3
+ export function shareTitle(record) {
4
+ try {
5
+ if (record.kind === 'query') {
6
+ const query = JSON.parse(record.presentationJson);
7
+ const lines = (query.displayText ?? '')
8
+ .split('\n')
9
+ .map((line) => line.trim())
10
+ .filter(Boolean);
11
+ return {
12
+ title: `${query.title ?? 'PUBG 战绩'} · ${record.matchIds.length} 场`,
13
+ description: lines[1] ?? 'PUBG 战绩查询',
14
+ };
15
+ }
16
+ const review = JSON.parse(record.presentationJson);
17
+ const date = review.startAt
18
+ ? new Intl.DateTimeFormat('zh-CN', {
19
+ timeZone: review.timezone ?? 'Asia/Shanghai',
20
+ month: 'numeric',
21
+ day: 'numeric',
22
+ }).format(new Date(review.startAt))
23
+ : '';
24
+ const title = record.kind === 'match'
25
+ ? `单局复盘 · ${date}`
26
+ : `时段复盘 · ${date} · ${review.matchCount ?? record.matchIds.length} 场排位`;
27
+ return { title, description: review.headline ?? 'PUBG 小队复盘' };
28
+ }
29
+ catch {
30
+ return { title: 'PUBG 小队复盘', description: 'PUBG 小队复盘' };
31
+ }
32
+ }
33
+ export function messagePage(title, body, refresh) {
34
+ return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex,nofollow">${refresh ? `<meta http-equiv="refresh" content="${escapeHtml(refresh)}">` : ''}<title>${escapeHtml(title)}</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#0b1112;color:#dce6e2;font:15px/1.6 system-ui,sans-serif;padding:24px;box-sizing:border-box}main{max-width:360px;text-align:center}h1{font-size:19px;margin:0 0 8px}p{color:#93a39e;margin:0}</style></head><body><main><h1>${escapeHtml(title)}</h1><p>${escapeHtml(body)}</p></main></body></html>`;
35
+ }
36
+ /** Opposing teams become 敌方 A, B, … in the order the squad met them; opposing account ids become opaque. */
37
+ export function aliasEnemies(story) {
38
+ const order = [];
39
+ const see = (team) => {
40
+ if (team !== null && !order.includes(team))
41
+ order.push(team);
42
+ };
43
+ for (const fight of [...story.fights].sort((left, right) => left.start - right.start))
44
+ for (const enemy of fight.enemies)
45
+ see(enemy.team);
46
+ for (const down of [...story.downs].sort((left, right) => left.t - right.t))
47
+ see(down.attackerTeam);
48
+ for (const enemy of [...story.enemies].sort((left, right) => (left.route[0]?.[0] ?? 0) - (right.route[0]?.[0] ?? 0)))
49
+ see(enemy.team);
50
+ const label = (team) => {
51
+ const index = order.indexOf(team);
52
+ return `敌方 ${String.fromCharCode(65 + (index % 26))}${index >= 26 ? Math.floor(index / 26) + 1 : ''}`;
53
+ };
54
+ return {
55
+ ...story,
56
+ fights: story.fights.map((fight) => ({
57
+ ...fight,
58
+ enemies: fight.enemies.map((enemy) => ({ ...enemy, team: label(enemy.team) })),
59
+ })),
60
+ downs: story.downs.map((down) => ({
61
+ ...down,
62
+ attackerTeam: down.attackerTeam === null ? null : label(down.attackerTeam),
63
+ })),
64
+ enemies: story.enemies.map((enemy, index) => ({
65
+ ...enemy,
66
+ id: `enemy-${index + 1}`,
67
+ team: label(enemy.team),
68
+ })),
69
+ };
70
+ }
71
+ function teamLine(match, squad) {
72
+ const members = match.players.filter((player) => squad.memberIds.includes(player.accountId));
73
+ return {
74
+ placement: members[0]?.rank ?? null,
75
+ kills: members.reduce((sum, player) => sum + player.kills, 0),
76
+ knocks: members.reduce((sum, player) => sum + player.dbnos, 0),
77
+ damage: Math.round(members.reduce((sum, player) => sum + player.damage, 0)),
78
+ };
79
+ }
80
+ /** What GET /api/share/view returns; the /s/ page also carries it inline so the page needs no extra round trip. */
81
+ export function shareViewPayload(share, squad, matches) {
82
+ return {
83
+ kind: share.kind,
84
+ expiresAt: share.expiresAt,
85
+ review: JSON.parse(share.presentationJson),
86
+ matches: share.matchIds.map((matchId) => {
87
+ const match = matches.get(matchId);
88
+ if (!match)
89
+ return { matchId, available: false };
90
+ return {
91
+ matchId,
92
+ available: true,
93
+ createdAt: match.createdAt,
94
+ mapName: match.mapName,
95
+ mapLabel: mapDisplayName(match.mapName || '未知地图'),
96
+ durationSeconds: match.duration,
97
+ ...teamLine(match, squad),
98
+ };
99
+ }),
100
+ };
101
+ }
102
+ /** JSON inside a <script>: nothing in it may close the tag or start a comment. */
103
+ export const inlineJson = (value) => JSON.stringify(value)
104
+ .replace(/</gu, '\\u003c')
105
+ .replace(/\u2028/gu, '\\u2028')
106
+ .replace(/\u2029/gu, '\\u2029');
107
+ /**
108
+ * Shown before the page script has arrived (it is replaced as soon as the app mounts). The steps are the real ones:
109
+ * the server has checked the link and read the review by the time this HTML exists; the browser still has to fetch
110
+ * the page program and build the cards.
111
+ */
112
+ export function bootSteps(matchCount) {
113
+ const step = (state, label) => `<li class="${state}"><i></i><span>${escapeHtml(label)}</span></li>`;
114
+ return `<style>.share-boot{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;background:#0b1112;color:#dce6e2;font:14px/1.5 system-ui,sans-serif;padding:24px}.share-boot .boot-mark{width:43px;height:43px;border:1px solid #41584c;border-radius:12px;display:grid;place-items:center;color:#b8f277;font:800 23px system-ui;animation:sb-pulse 1.5s ease-in-out infinite}.load-steps{list-style:none;margin:0;padding:0;display:grid;gap:9px;min-width:240px}.load-steps li{display:flex;align-items:center;gap:10px;color:#6f817c}.load-steps li i{width:16px;height:16px;flex:none;border-radius:50%;border:2px solid #2c3e3a;box-sizing:border-box}.load-steps li.done{color:#b9c8c2}.load-steps li.done i{border-color:#b8f277;background:#b8f277;box-shadow:inset 0 0 0 3px #0b1112}.load-steps li.active{color:#eef5f1}.load-steps li.active i{border-color:#2c3e3a;border-top-color:#b8f277;animation:sb-spin .8s linear infinite}@keyframes sb-spin{to{transform:rotate(360deg)}}@keyframes sb-pulse{50%{opacity:.4}}</style><div class="share-boot"><div class="boot-mark">P</div><ol class="load-steps">${[
115
+ step('done', '校验分享链接'),
116
+ step('done', `读取复盘与 ${matchCount} 场对局`),
117
+ step('active', '下载页面程序'),
118
+ step('', '生成队员卡片与对局列表'),
119
+ ].join('')}</ol></div>`;
120
+ }