@chrischall/warapp-mcp 0.5.0 → 0.7.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.
- package/.claude-plugin/marketplace.json +3 -3
- package/.claude-plugin/plugin.json +1 -1
- package/README.md +133 -8
- package/dist/analysis/accept-surrender.js +20 -2
- package/dist/analysis/calibrate.js +1 -0
- package/dist/analysis/card-support.js +177 -17
- package/dist/analysis/card-threats.js +126 -14
- package/dist/analysis/chat-advice.js +182 -0
- package/dist/analysis/chat-blocks.js +106 -0
- package/dist/analysis/chat-intent.js +559 -0
- package/dist/analysis/chat-read.js +159 -0
- package/dist/analysis/decision-replay.js +279 -0
- package/dist/analysis/decision-truth.js +146 -0
- package/dist/analysis/finished-game.js +62 -3
- package/dist/analysis/game-lessons.js +15 -10
- package/dist/analysis/hold-diff.js +3 -1
- package/dist/analysis/income-trend.js +38 -0
- package/dist/analysis/intel.js +75 -0
- package/dist/analysis/opens.js +64 -0
- package/dist/analysis/opponent-profile.js +121 -10
- package/dist/analysis/opponents.js +246 -20
- package/dist/analysis/outlook.js +360 -15
- package/dist/analysis/picks.js +91 -12
- package/dist/analysis/plan/after-leftover.js +4 -1
- package/dist/analysis/plan/bonus-attempts.js +105 -0
- package/dist/analysis/plan/capture-instead.js +116 -0
- package/dist/analysis/plan/captures.js +49 -7
- package/dist/analysis/plan/conceded-out.js +13 -2
- package/dist/analysis/plan/estimates.js +203 -30
- package/dist/analysis/plan/guard-off.js +2 -1
- package/dist/analysis/plan/holds.js +110 -9
- package/dist/analysis/plan/jabs.js +113 -0
- package/dist/analysis/plan/leftover.js +393 -8
- package/dist/analysis/plan/orders.js +76 -4
- package/dist/analysis/plan/relations.js +135 -2
- package/dist/analysis/plan/report.js +69 -3
- package/dist/analysis/plan/second-sizing.js +133 -0
- package/dist/analysis/plan/shared.js +279 -27
- package/dist/analysis/plan/siege.js +303 -0
- package/dist/analysis/plan/stand-still.js +9 -5
- package/dist/analysis/plan/state.js +8 -0
- package/dist/analysis/plan/stockpile.js +104 -0
- package/dist/analysis/plan/strike.js +39 -7
- package/dist/analysis/plan/targets.js +256 -110
- package/dist/analysis/plan/threats.js +148 -10
- package/dist/analysis/plan/transfers.js +57 -6
- package/dist/analysis/plan/two-move.js +70 -0
- package/dist/analysis/plan/vacated.js +124 -2
- package/dist/analysis/planner.js +527 -49
- package/dist/analysis/profile.js +13 -2
- package/dist/analysis/since-last.js +18 -5
- package/dist/analysis/stress.js +8 -2
- package/dist/board.js +36 -2
- package/dist/bonus-attempt-store.js +55 -0
- package/dist/build-id.js +106 -0
- package/dist/bundle.js +54138 -41059
- package/dist/cards.js +7 -5
- package/dist/chat-automation.js +22 -0
- package/dist/chat.js +35 -1
- package/dist/client.js +14 -0
- package/dist/commerce.js +111 -0
- package/dist/decision-log.js +1093 -0
- package/dist/finished-store.js +5 -1
- package/dist/index.js +9 -1
- package/dist/lessons-store.js +322 -21
- package/dist/live.js +43 -0
- package/dist/move-order.js +64 -3
- package/dist/normalize.js +17 -0
- package/dist/open-games.js +36 -16
- package/dist/outlook-log.js +42 -1
- package/dist/profile-store.js +12 -2
- package/dist/protocol/methods.js +62 -5
- package/dist/protocol/rpc.js +8 -0
- package/dist/relations-store.js +38 -4
- package/dist/review-export.js +198 -0
- package/dist/siege-store.js +49 -0
- package/dist/state-bundle.js +584 -0
- package/dist/state-cli.js +71 -0
- package/dist/strategy/notes.js +56 -0
- package/dist/team-cards.js +25 -0
- package/dist/tools/accept-surrender.js +23 -9
- package/dist/tools/award.js +20 -2
- package/dist/tools/card-advice.js +93 -28
- package/dist/tools/card-plays.js +2 -2
- package/dist/tools/card-support-advice.js +37 -7
- package/dist/tools/chat-advice.js +330 -0
- package/dist/tools/chat-inbox.js +19 -4
- package/dist/tools/chat.js +106 -17
- package/dist/tools/check-plan.js +68 -12
- package/dist/tools/commerce-deploy.js +33 -0
- package/dist/tools/common.js +31 -0
- package/dist/tools/decision-capture.js +459 -0
- package/dist/tools/end-of-game.js +151 -21
- package/dist/tools/game-kind.js +92 -0
- package/dist/tools/how-lost.js +7 -2
- package/dist/tools/index.js +10 -0
- package/dist/tools/join-game.js +10 -4
- package/dist/tools/live-context.js +6 -0
- package/dist/tools/live.js +10 -1
- package/dist/tools/map-curves.js +73 -0
- package/dist/tools/notifications.js +4 -3
- package/dist/tools/opponents.js +2 -0
- package/dist/tools/past-games.js +74 -8
- package/dist/tools/picks.js +61 -10
- package/dist/tools/profile-hook.js +62 -3
- package/dist/tools/profile-opponents.js +4 -0
- package/dist/tools/push.js +2 -2
- package/dist/tools/relations.js +139 -0
- package/dist/tools/scout.js +16 -2
- package/dist/tools/state.js +232 -0
- package/dist/tools/strategy.js +3 -3
- package/dist/tools/stress-opponents.js +7 -2
- package/dist/tools/surrender-pending.js +10 -1
- package/dist/tools/surrender.js +18 -3
- package/dist/tools/survival.js +11 -3
- package/dist/tools/team-brief.js +2 -2
- package/dist/tools/team.js +12 -3
- package/dist/tools/turn.js +643 -76
- package/dist/tools/where.js +3 -1
- package/dist/version.js +1 -1
- package/manifest.json +32 -3
- package/mint.yaml +37 -4
- package/package.json +4 -4
- package/server.json +20 -2
- package/skills/warapp-mcp/SKILL.md +73 -17
package/dist/analysis/profile.js
CHANGED
|
@@ -13,6 +13,11 @@ import { neighborsOf } from './graph.js';
|
|
|
13
13
|
export const AHEAD_RATIO = 1.25;
|
|
14
14
|
/** Behind when my income is at most this many times the strongest opponent's estimated income. */
|
|
15
15
|
export const BEHIND_RATIO = 0.8;
|
|
16
|
+
/**
|
|
17
|
+
* #287 (1v1 only, the owner's choice): behind, not ahead or even, when the opponent's armies in view are at
|
|
18
|
+
* least this many times mine (what it shows is the least it has). The reciprocal of {@link BEHIND_RATIO}.
|
|
19
|
+
*/
|
|
20
|
+
export const OUTNUMBERED_RATIO = 1.25;
|
|
16
21
|
/**
|
|
17
22
|
* A player's strength in a free-for-all ranking (#167): its visible armies plus this many turns of
|
|
18
23
|
* its income — what it can field over the next few turns.
|
|
@@ -284,14 +289,20 @@ export function gameProfile(input) {
|
|
|
284
289
|
standing = 'behind';
|
|
285
290
|
standingSource ??= 'visible';
|
|
286
291
|
}
|
|
292
|
+
else if (format === '1v1' && (standing === 'ahead' || standing === 'even') && theirArmies >= OUTNUMBERED_RATIO * sideArmies) {
|
|
293
|
+
// #287 (owner, 1v1 only): outnumbered by a quarter or more in view is no even game, whatever the incomes.
|
|
294
|
+
// Not in a free-for-all: a clear leader above me (#167) would always read behind and the profile defend.
|
|
295
|
+
notes.push(`Standing behind, not ${standing} (#287): ${theirsText} visible armies are at least ${OUTNUMBERED_RATIO}× ${mineText}, and what it shows is the least it has.`);
|
|
296
|
+
standing = 'behind';
|
|
297
|
+
standingSource ??= 'visible';
|
|
298
|
+
}
|
|
287
299
|
else if (standing === 'ahead' && sideArmies < BEHIND_RATIO * theirArmies) {
|
|
288
300
|
notes.push(`Not ahead: the income comparison says so, but ${mineText} visible armies are below ${BEHIND_RATIO}× ${theirsText} in view. Standing even.`);
|
|
289
301
|
standing = 'even';
|
|
290
302
|
}
|
|
291
303
|
}
|
|
292
304
|
// #275 (b): an observation broke an opponent's estimate: what it really earns is unknown and above it,
|
|
293
|
-
// so the game is not even
|
|
294
|
-
// (an opponent's ≥ 1.25 × mine, no tripwire) is not part of #275 — it is deferred to #287.
|
|
305
|
+
// so the game is not even (armies in view alone at OUTNUMBERED_RATIO × mine are #287's 1v1 rule above).
|
|
295
306
|
if (standing === 'even') {
|
|
296
307
|
const running = enemies.filter((e) => untrustedFigure.has(e.playerId)).map((e) => e.playerId).sort((a, b) => a - b);
|
|
297
308
|
if (running.length) {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Since last turn (#194): this turn's income against the next income the plan of the previous
|
|
2
2
|
// turn expected, and what changed hands since the previous board — the positive bonuses I held
|
|
3
3
|
// that are broken now, and the territories I held that are no longer mine (taken by a player,
|
|
4
|
-
// neutral again, or out of view)
|
|
4
|
+
// neutral again, or out of view), and (#442) the captures that plan expected and did not make, with
|
|
5
|
+
// who holds each now. Pure and deterministic (ascending ids); no I/O.
|
|
5
6
|
//
|
|
6
7
|
// The expected figure is the plan's `expected.nextIncome` as it stood when the previous turn was
|
|
7
8
|
// planned: it assumed the plan's orders were sent and every kept border held, so a shortfall says
|
|
@@ -39,12 +40,24 @@ export function sinceLastTurn(input) {
|
|
|
39
40
|
.map(({ b }) => ({ bonusId: b.id, value: b.value }))
|
|
40
41
|
.sort((x, y) => x.bonusId - y.bonusId);
|
|
41
42
|
const ownerNow = new Map(current.territories.map((t) => [t.territoryId, t.owner]));
|
|
43
|
+
const toOf = (territoryId) => {
|
|
44
|
+
const o = ownerNow.get(territoryId);
|
|
45
|
+
return o?.kind === 'player' ? o.playerId : null;
|
|
46
|
+
};
|
|
47
|
+
const ownerBefore = new Map(previous.territories.map((t) => [t.territoryId, t.owner]));
|
|
48
|
+
if (input.expectedCaptures)
|
|
49
|
+
out.capturesMissed = [...new Set(input.expectedCaptures)]
|
|
50
|
+
.filter((id) => graph.territoryById.has(id) && !now.has(id) && !before.has(id))
|
|
51
|
+
.sort(byNum)
|
|
52
|
+
.map((territoryId) => {
|
|
53
|
+
const to = toOf(territoryId);
|
|
54
|
+
const was = ownerBefore.get(territoryId);
|
|
55
|
+
const fresh = to !== null && !(was?.kind === 'player' && was.playerId === to);
|
|
56
|
+
return { territoryId, to, ...(fresh ? { fresh: true } : {}) };
|
|
57
|
+
});
|
|
42
58
|
out.territoriesLost = [...before]
|
|
43
59
|
.filter((id) => !now.has(id))
|
|
44
60
|
.sort(byNum)
|
|
45
|
-
.map((territoryId) => {
|
|
46
|
-
const o = ownerNow.get(territoryId);
|
|
47
|
-
return { territoryId, to: o?.kind === 'player' ? o.playerId : null };
|
|
48
|
-
});
|
|
61
|
+
.map((territoryId) => ({ territoryId, to: toOf(territoryId) }));
|
|
49
62
|
return out;
|
|
50
63
|
}
|
package/dist/analysis/stress.js
CHANGED
|
@@ -497,7 +497,10 @@ export function stressPlan(input) {
|
|
|
497
497
|
// Worst first: my commander, an elimination undone, then income, territories held, captures undone, armies.
|
|
498
498
|
const order = harmful
|
|
499
499
|
.map((r, i) => ({ r, i }))
|
|
500
|
-
.sort((a, b) =>
|
|
500
|
+
.sort((a, b) =>
|
|
501
|
+
// #376: a reply a truce rules out comes after every reply that keeps the truces, so `worst` is a real threat.
|
|
502
|
+
Number(a.r.breaksTruce === true) - Number(b.r.breaksTruce === true) ||
|
|
503
|
+
Number(b.r.commanderLost) - Number(a.r.commanderLost) ||
|
|
501
504
|
b.r.eliminationsFailed.length - a.r.eliminationsFailed.length ||
|
|
502
505
|
// A negative bonus lost is no reason to rank a reply below one that takes nothing.
|
|
503
506
|
Math.max(0, b.r.incomeLost) - Math.max(0, a.r.incomeLost) ||
|
|
@@ -544,13 +547,16 @@ export function stressPlan(input) {
|
|
|
544
547
|
needs: r.needs,
|
|
545
548
|
bonusesLost,
|
|
546
549
|
incomeLost: bonusesLost.reduce((n, b) => n + b.value, 0),
|
|
550
|
+
// #376: the partner of a truce covering the territory or the step to it breaks the truce to take it.
|
|
551
|
+
...(covers.get(r.opponent)?.has(r.territory) || covers.get(r.opponent)?.has(r.via) ? { breaksTruce: true } : {}),
|
|
547
552
|
};
|
|
548
553
|
const known = exposed.get(r.territory);
|
|
549
554
|
if (!known || found.attackers > known.attackers)
|
|
550
555
|
exposed.set(r.territory, found);
|
|
551
556
|
}
|
|
552
557
|
}
|
|
553
|
-
const exposedNextTurn = [...exposed.values()].sort((a, b) =>
|
|
558
|
+
const exposedNextTurn = [...exposed.values()].sort((a, b) => Number(a.breaksTruce === true) - Number(b.breaksTruce === true) ||
|
|
559
|
+
Math.max(0, b.incomeLost) - Math.max(0, a.incomeLost) || b.needs - b.armies - (a.needs - a.armies) || a.territory - b.territory);
|
|
554
560
|
return {
|
|
555
561
|
exact: baseline.exact,
|
|
556
562
|
assumptions: [...assumptions],
|
package/dist/board.js
CHANGED
|
@@ -48,17 +48,48 @@ function armiesOf(v) {
|
|
|
48
48
|
return armiesOf(pick(v, ['numArmies', 'NumArmies', 'armies']));
|
|
49
49
|
return asInt(v) ?? null;
|
|
50
50
|
}
|
|
51
|
+
/** #437: the unit tags GameFeed's history writes after the bar; only `cmdr` is VERIFIED live (2026-11-20). */
|
|
52
|
+
const UNIT_TAGS = { cmdr: 'commander' };
|
|
53
|
+
/**
|
|
54
|
+
* #437, VERIFIED live 2026-11-20 (a finished Commanders game's GameFeed history): a territory where a special
|
|
55
|
+
* unit stands sends `armies` as `"<N>|cmdr,<GUID>,<owner id>,"` — N the plain armies alone (every start read 5,
|
|
56
|
+
* the commander's too, and 0 once its armies left), then per unit its tag, GUID and owner (a GameFeed id),
|
|
57
|
+
* each followed by a comma. Returns `undefined` for any other value; units that do not read are dropped.
|
|
58
|
+
*/
|
|
59
|
+
function unitArmiesOf(v) {
|
|
60
|
+
if (typeof v !== 'string')
|
|
61
|
+
return undefined;
|
|
62
|
+
const bar = v.indexOf('|');
|
|
63
|
+
if (bar < 0)
|
|
64
|
+
return undefined;
|
|
65
|
+
const armies = asInt(v.slice(0, bar).trim()) ?? null;
|
|
66
|
+
const fields = v.slice(bar + 1).split(',');
|
|
67
|
+
const units = [];
|
|
68
|
+
for (let i = 0; i + 2 < fields.length; i += 3) {
|
|
69
|
+
const tag = fields[i].trim();
|
|
70
|
+
const id = fields[i + 1].trim();
|
|
71
|
+
const playerId = asInt(fields[i + 2].trim());
|
|
72
|
+
if (!tag || !id || playerId === undefined)
|
|
73
|
+
break;
|
|
74
|
+
units.push({ kind: UNIT_TAGS[tag] ?? 'unknown', id, playerId });
|
|
75
|
+
}
|
|
76
|
+
return { armies, units };
|
|
77
|
+
}
|
|
51
78
|
function entryOf(raw, fallbackId) {
|
|
52
79
|
if (!isRec(raw))
|
|
53
80
|
return undefined;
|
|
54
81
|
const territoryId = asInt(pick(raw, ID_KEYS)) ?? fallbackId;
|
|
55
82
|
if (territoryId === undefined)
|
|
56
83
|
return undefined;
|
|
84
|
+
const rawArmies = pick(raw, ARMY_KEYS);
|
|
85
|
+
const withUnits = unitArmiesOf(rawArmies);
|
|
57
86
|
const entry = {
|
|
58
87
|
territoryId,
|
|
59
88
|
owner: ownerOf(pick(raw, OWNER_KEYS)),
|
|
60
|
-
armies: armiesOf(
|
|
89
|
+
armies: withUnits ? withUnits.armies : armiesOf(rawArmies),
|
|
61
90
|
};
|
|
91
|
+
if (withUnits?.units.length)
|
|
92
|
+
entry.specialUnits = withUnits.units;
|
|
62
93
|
const fog = pick(raw, FOG_KEYS);
|
|
63
94
|
if ((typeof fog === 'string' && fog) || typeof fog === 'number') {
|
|
64
95
|
const level = String(fog).trim();
|
|
@@ -70,9 +101,12 @@ function entryOf(raw, fallbackId) {
|
|
|
70
101
|
if (/fog/i.test(level) || level === '4') {
|
|
71
102
|
entry.owner = { kind: 'unknown' };
|
|
72
103
|
entry.armies = null;
|
|
104
|
+
delete entry.specialUnits;
|
|
73
105
|
}
|
|
74
|
-
else if (/owneronly/i.test(level) || level === '3')
|
|
106
|
+
else if (/owneronly/i.test(level) || level === '3') {
|
|
75
107
|
entry.armies = null;
|
|
108
|
+
delete entry.specialUnits;
|
|
109
|
+
}
|
|
76
110
|
}
|
|
77
111
|
return entry;
|
|
78
112
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// The bonus attempt memory on disk (#298): per game and account, at
|
|
2
|
+
// `<dataDir>/bonus-attempts/<gameId>-<playerId>.json`, the contested bonuses whose completion my plans
|
|
3
|
+
// attempted (each attempt's turn, whether it was all-in, whether the next board showed it failed) and
|
|
4
|
+
// the drops in force. Ids and numbers only, never a name; 0600 in a 0700 directory, written atomically
|
|
5
|
+
// under the in-process path lock (the siege store's pattern, src/siege-store.ts). Written by
|
|
6
|
+
// warapp_plan_turn on a plan that is not a what-if and read back as `PlanInput.bonusAttempts`. Reads are
|
|
7
|
+
// loose: an unusable file is no memory, an unusable record or attempt is dropped; nothing here throws.
|
|
8
|
+
import { randomUUID } from 'node:crypto';
|
|
9
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { withPathLock } from './path-lock.js';
|
|
12
|
+
const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
13
|
+
const isInt = (v) => typeof v === 'number' && Number.isSafeInteger(v);
|
|
14
|
+
export const bonusAttemptsDir = (dir) => join(dir, 'bonus-attempts');
|
|
15
|
+
export const bonusAttemptsPath = (dir, gameId, playerId) => join(bonusAttemptsDir(dir), `${gameId}-${playerId}.json`);
|
|
16
|
+
function attemptOf(v) {
|
|
17
|
+
if (!isRec(v) || !isInt(v.turn) || typeof v.allIn !== 'boolean')
|
|
18
|
+
return undefined;
|
|
19
|
+
return { turn: v.turn, allIn: v.allIn, ...(typeof v.failed === 'boolean' ? { failed: v.failed } : {}) };
|
|
20
|
+
}
|
|
21
|
+
function recordOf(v) {
|
|
22
|
+
if (!isRec(v) || !isInt(v.bonusId) || !Array.isArray(v.attempts))
|
|
23
|
+
return undefined;
|
|
24
|
+
const attempts = v.attempts.map(attemptOf).filter((a) => a !== undefined);
|
|
25
|
+
const drop = isRec(v.drop) && isInt(v.drop.from) && isInt(v.drop.until) ? { from: v.drop.from, until: v.drop.until } : undefined;
|
|
26
|
+
return { bonusId: v.bonusId, attempts, ...(drop ? { drop } : {}) };
|
|
27
|
+
}
|
|
28
|
+
/** The attempt memory kept for `gameId` as `playerId`; `undefined` when none or unusable. Never throws. */
|
|
29
|
+
export async function readBonusAttempts(dir, gameId, playerId) {
|
|
30
|
+
try {
|
|
31
|
+
const c = JSON.parse(await readFile(bonusAttemptsPath(dir, gameId, playerId), 'utf8'));
|
|
32
|
+
if (!isRec(c) || c.gameId !== gameId || c.playerId !== playerId || !Array.isArray(c.bonuses))
|
|
33
|
+
return undefined;
|
|
34
|
+
return { bonuses: c.bonuses.map(recordOf).filter((r) => r !== undefined) };
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Write the attempt memory, atomically, 0600. `true` when written; never throws. */
|
|
41
|
+
export async function writeBonusAttempts(dir, gameId, playerId, memory) {
|
|
42
|
+
const path = bonusAttemptsPath(dir, gameId, playerId);
|
|
43
|
+
return withPathLock(path, async () => {
|
|
44
|
+
try {
|
|
45
|
+
await mkdir(bonusAttemptsDir(dir), { recursive: true, mode: 0o700 });
|
|
46
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
47
|
+
await writeFile(tmp, JSON.stringify({ gameId, playerId, bonuses: memory.bonuses }), { mode: 0o600 });
|
|
48
|
+
await rename(tmp, path);
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
package/dist/build-id.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// The build the server runs (#437 task 1), for the decision log beside `planner.version`: the git commit
|
|
2
|
+
// when it runs from a checkout of this package (read from `.git` directly, no process spawned; a worktree's
|
|
3
|
+
// `.git` file and its common dir followed, a packed ref read too), else a hash of the running module file
|
|
4
|
+
// (`dist/bundle.js` once bundled). Only the package root's own `.git` is read: installed inside another
|
|
5
|
+
// project's checkout, that project's commit is never taken for ours. Read once per process (`serverBuild`).
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
7
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
8
|
+
import { dirname, join, resolve } from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
const PACKAGE_NAME = '@chrischall/warapp-mcp';
|
|
11
|
+
const SHA = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
|
|
12
|
+
const readText = (path) => {
|
|
13
|
+
try {
|
|
14
|
+
return readFileSync(path, 'utf8');
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return undefined;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
/** The commit HEAD names in the checkout at `root`; `undefined` when there is none or it does not read. */
|
|
21
|
+
export function gitCommit(root) {
|
|
22
|
+
let gitDir = join(root, '.git');
|
|
23
|
+
try {
|
|
24
|
+
if (statSync(gitDir).isFile()) {
|
|
25
|
+
const m = /^gitdir:\s*(.+?)\s*$/m.exec(readText(gitDir) ?? '');
|
|
26
|
+
if (!m)
|
|
27
|
+
return undefined;
|
|
28
|
+
gitDir = resolve(root, m[1]);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
const head = readText(join(gitDir, 'HEAD'))?.trim();
|
|
35
|
+
if (!head)
|
|
36
|
+
return undefined;
|
|
37
|
+
if (SHA.test(head))
|
|
38
|
+
return head;
|
|
39
|
+
const ref = /^ref:\s*(refs\/\S+)$/.exec(head)?.[1];
|
|
40
|
+
if (!ref || ref.split('/').includes('..'))
|
|
41
|
+
return undefined;
|
|
42
|
+
const commonDir = readText(join(gitDir, 'commondir'))?.trim();
|
|
43
|
+
const common = commonDir ? resolve(gitDir, commonDir) : gitDir;
|
|
44
|
+
for (const d of [gitDir, common]) {
|
|
45
|
+
const v = readText(join(d, ref))?.trim();
|
|
46
|
+
if (v && SHA.test(v))
|
|
47
|
+
return v;
|
|
48
|
+
}
|
|
49
|
+
for (const line of (readText(join(common, 'packed-refs')) ?? '').split('\n')) {
|
|
50
|
+
const [sha, name] = line.trim().split(/\s+/);
|
|
51
|
+
if (name === ref && sha && SHA.test(sha))
|
|
52
|
+
return sha;
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
/** The nearest folder at or above `from` holding a package.json, and whether it is this package's. */
|
|
57
|
+
function packageRoot(from) {
|
|
58
|
+
let d = from;
|
|
59
|
+
for (let i = 0; i < 64; i++) {
|
|
60
|
+
const pkg = join(d, 'package.json');
|
|
61
|
+
if (existsSync(pkg)) {
|
|
62
|
+
try {
|
|
63
|
+
return { root: d, ours: JSON.parse(readFileSync(pkg, 'utf8')).name === PACKAGE_NAME };
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return { root: d, ours: false };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const up = dirname(d);
|
|
70
|
+
if (up === d)
|
|
71
|
+
return undefined;
|
|
72
|
+
d = up;
|
|
73
|
+
}
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The build of the server whose module file is `moduleFile`: `git:<sha>` from this package's own checkout,
|
|
78
|
+
* else `sha256:<16 hex>` of the module file; `undefined` when neither reads. Never throws.
|
|
79
|
+
*/
|
|
80
|
+
export function readBuild(moduleFile) {
|
|
81
|
+
try {
|
|
82
|
+
const pkg = packageRoot(dirname(moduleFile));
|
|
83
|
+
const commit = pkg?.ours ? gitCommit(pkg.root) : undefined;
|
|
84
|
+
if (commit)
|
|
85
|
+
return `git:${commit}`;
|
|
86
|
+
return `sha256:${createHash('sha256').update(readFileSync(moduleFile)).digest('hex').slice(0, 16)}`;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
let cached;
|
|
93
|
+
/** {@link readBuild} of the running server, read once per process. */
|
|
94
|
+
export function serverBuild() {
|
|
95
|
+
if (!cached) {
|
|
96
|
+
let file;
|
|
97
|
+
try {
|
|
98
|
+
file = fileURLToPath(import.meta.url);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
file = undefined;
|
|
102
|
+
}
|
|
103
|
+
cached = { build: file ? readBuild(file) : undefined };
|
|
104
|
+
}
|
|
105
|
+
return cached.build;
|
|
106
|
+
}
|