@mavonengine/cli 0.0.5 → 0.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9,12 +9,13 @@ import {
9
9
  import {
10
10
  DEFAULT_DOCS_URL,
11
11
  MCP_CONFIG_FILE,
12
+ __export,
12
13
  version,
13
14
  writeMcpConfig
14
- } from "./chunk-WOOU36T7.js";
15
+ } from "./chunk-3VVGSO5T.js";
15
16
 
16
17
  // src/index.ts
17
- import process11 from "process";
18
+ import process15 from "process";
18
19
 
19
20
  // src/commands/build.ts
20
21
  import { spawn as spawn4 } from "child_process";
@@ -26,10 +27,187 @@ import { parseArgs as parseArgs4 } from "util";
26
27
  // ../core/dist/Plugins/ProjectConfig.js
27
28
  import { existsSync, readdirSync, readFileSync, writeFileSync } from "fs";
28
29
  import { dirname, isAbsolute, join, relative, resolve } from "path";
30
+
31
+ // ../core/dist/Plugins/compat.js
32
+ var VERSION_RE = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Z-]+(?:\.[0-9A-Z-]+)*))?(?:\+[0-9A-Z-]+(?:\.[0-9A-Z-]+)*)?$/i;
33
+ var PARTIAL_RE = /^v?(\d+|[x*])(?:\.(\d+|[x*]))?(?:\.(\d+|[x*]))?(?:-([0-9A-Z-]+(?:\.[0-9A-Z-]+)*))?(?:\+[0-9A-Z-]+(?:\.[0-9A-Z-]+)*)?$/i;
34
+ var COMPARATOR_RE = /^(<=|>=|~>|[<>=^~])?\s*([^\s<>=^~]\S*)$/;
35
+ var HYPHEN_RE = /^(\S+)\s+-\s+(\S+)$/;
36
+ var OPERATOR_SPACE_RE = /(<=|>=|~>|[<>=^~])\s+/g;
37
+ var WHITESPACE_RE = /\s+/;
38
+ var NUMERIC_RE = /^\d+$/;
39
+ var WILDCARD_RE = /^[x*]$/i;
40
+ function prereleaseOf(text) {
41
+ return text ? text.split(".").map((part) => NUMERIC_RE.test(part) ? Number(part) : part) : [];
42
+ }
43
+ function parseVersion(version3) {
44
+ const match = VERSION_RE.exec(version3.trim());
45
+ if (!match)
46
+ return void 0;
47
+ return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), prerelease: prereleaseOf(match[4]) };
48
+ }
49
+ function compareVersions(a, b) {
50
+ for (const key of ["major", "minor", "patch"]) {
51
+ if (a[key] !== b[key])
52
+ return a[key] - b[key];
53
+ }
54
+ if (!a.prerelease.length || !b.prerelease.length)
55
+ return b.prerelease.length - a.prerelease.length;
56
+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i++) {
57
+ const x = a.prerelease[i];
58
+ const y = b.prerelease[i];
59
+ if (x === void 0 || y === void 0)
60
+ return x === void 0 ? -1 : 1;
61
+ if (x === y)
62
+ continue;
63
+ if (typeof x === "number" && typeof y === "number")
64
+ return x - y;
65
+ if (typeof x === "number" || typeof y === "number")
66
+ return typeof x === "number" ? -1 : 1;
67
+ return x < y ? -1 : 1;
68
+ }
69
+ return 0;
70
+ }
71
+ function version2(major, minor, patch, prerelease = []) {
72
+ return { major, minor, patch, prerelease };
73
+ }
74
+ function floor(major, minor, patch) {
75
+ return version2(major, minor, patch, [0]);
76
+ }
77
+ function desugar(text) {
78
+ const match = COMPARATOR_RE.exec(text);
79
+ if (!match)
80
+ return void 0;
81
+ const op = match[1] === "~>" ? "~" : match[1] ?? "";
82
+ const partial = PARTIAL_RE.exec(match[2]);
83
+ if (!partial)
84
+ return void 0;
85
+ const parts = [partial[1], partial[2], partial[3]];
86
+ const wild = parts.findIndex((part) => part === void 0 || WILDCARD_RE.test(part));
87
+ const given = wild === -1 ? 3 : wild;
88
+ const [major, minor, patch] = parts.map((part, i) => i < given ? Number(part) : 0);
89
+ const pre = given === 3 ? prereleaseOf(partial[4]) : [];
90
+ const exact = version2(major, minor, patch, pre);
91
+ const make = (o, v, explicit = false) => ({ op: o, version: v, explicit });
92
+ if (given === 0)
93
+ return op === "<" || op === ">" ? [make("<", floor(0, 0, 0))] : [];
94
+ const next = given === 1 ? floor(major + 1, 0, 0) : floor(major, minor + 1, 0);
95
+ switch (op) {
96
+ case "":
97
+ case "=":
98
+ return given === 3 ? [make("=", exact, true)] : [make(">=", version2(major, minor, 0)), make("<", next)];
99
+ case ">":
100
+ return given === 3 ? [make(">", exact, true)] : [make(">=", version2(next.major, next.minor, 0))];
101
+ case ">=":
102
+ return [make(">=", exact, true)];
103
+ case "<":
104
+ return [make("<", given === 3 ? exact : floor(major, minor, 0), given === 3)];
105
+ case "<=":
106
+ return given === 3 ? [make("<=", exact, true)] : [make("<", next)];
107
+ case "~":
108
+ return [make(">=", exact, true), make("<", given === 1 ? floor(major + 1, 0, 0) : floor(major, minor + 1, 0))];
109
+ case "^": {
110
+ let upper;
111
+ if (major > 0 || given === 1)
112
+ upper = floor(major + 1, 0, 0);
113
+ else if (minor > 0 || given === 2)
114
+ upper = floor(0, minor + 1, 0);
115
+ else
116
+ upper = floor(0, 0, patch + 1);
117
+ return [make(">=", exact, true), make("<", upper)];
118
+ }
119
+ }
120
+ return void 0;
121
+ }
122
+ function parseRange(range) {
123
+ const sets = [];
124
+ for (const alternative of range.split("||")) {
125
+ const text = alternative.trim();
126
+ const set = [];
127
+ const hyphen = HYPHEN_RE.exec(text);
128
+ if (hyphen) {
129
+ const from = desugar(`>=${hyphen[1]}`);
130
+ const to = desugar(`<=${hyphen[2]}`);
131
+ if (!from || !to)
132
+ return void 0;
133
+ set.push(...from, ...to);
134
+ } else if (text) {
135
+ for (const part of text.replace(OPERATOR_SPACE_RE, "$1").split(WHITESPACE_RE)) {
136
+ const comparators = desugar(part);
137
+ if (!comparators)
138
+ return void 0;
139
+ set.push(...comparators);
140
+ }
141
+ }
142
+ sets.push(set);
143
+ }
144
+ return sets;
145
+ }
146
+ function validRange(range) {
147
+ return typeof range === "string" && parseRange(range) !== void 0;
148
+ }
149
+ function holds(v, { op, version: other }) {
150
+ const order = compareVersions(v, other);
151
+ switch (op) {
152
+ case "<":
153
+ return order < 0;
154
+ case "<=":
155
+ return order <= 0;
156
+ case ">":
157
+ return order > 0;
158
+ case ">=":
159
+ return order >= 0;
160
+ case "=":
161
+ return order === 0;
162
+ }
163
+ }
164
+ function sameRelease(a, b) {
165
+ return a.major === b.major && a.minor === b.minor && a.patch === b.patch;
166
+ }
167
+ function satisfies(version3, range) {
168
+ const v = parseVersion(version3);
169
+ const sets = parseRange(range);
170
+ if (!v || !sets)
171
+ return false;
172
+ return sets.some((set) => set.every((comparator) => holds(v, comparator)) && (!v.prerelease.length || set.some((c) => c.explicit && c.version.prerelease.length && sameRelease(c.version, v))));
173
+ }
174
+ function maxSatisfying(versions, range) {
175
+ let best;
176
+ for (const text of versions) {
177
+ const v = parseVersion(text);
178
+ if (v && satisfies(text, range) && (!best || compareVersions(v, best.version) > 0))
179
+ best = { text, version: v };
180
+ }
181
+ return best?.text;
182
+ }
183
+ function engineRangeOf(packageJson) {
184
+ const engine = packageJson?.mavonengine?.engine ?? packageJson?.peerDependencies?.["@mavonengine/core"];
185
+ return typeof engine === "string" && engine.trim() ? engine.trim() : void 0;
186
+ }
187
+ function engineCompat(engine, coreVersion) {
188
+ if (!engine || !coreVersion || !validRange(engine) || !parseVersion(coreVersion))
189
+ return "unknown";
190
+ return satisfies(coreVersion, engine) ? "compatible" : "incompatible";
191
+ }
192
+
193
+ // ../core/dist/Plugins/ProjectConfig.js
29
194
  var CONFIG_FILE = "mavonengine.json";
30
195
  var TARGETS = ["client", "server", "both"];
31
196
  var PluginConfigError = class extends Error {
32
197
  };
198
+ var TRAILING_SLASHES_RE = /\/+$/;
199
+ function parseAppUrl(value) {
200
+ if (typeof value !== "string" || !value.trim())
201
+ return void 0;
202
+ try {
203
+ const url = new URL(value.trim());
204
+ if (url.protocol !== "https:" && url.protocol !== "http:")
205
+ return void 0;
206
+ } catch {
207
+ return void 0;
208
+ }
209
+ return value.trim().replace(TRAILING_SLASHES_RE, "");
210
+ }
33
211
  function configPath(root) {
34
212
  return join(root, CONFIG_FILE);
35
213
  }
@@ -89,6 +267,17 @@ function findPackageDir(root, pkg) {
89
267
  return void 0;
90
268
  }
91
269
  }
270
+ function installedPackageVersion(root, pkg) {
271
+ const dir = findPackageDir(root, pkg);
272
+ if (!dir)
273
+ return void 0;
274
+ try {
275
+ const version3 = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).version;
276
+ return typeof version3 === "string" ? version3 : void 0;
277
+ } catch {
278
+ return void 0;
279
+ }
280
+ }
92
281
  function validateManifest(pkg, value) {
93
282
  if (!value || typeof value !== "object")
94
283
  throw new PluginConfigError(`${pkg}: "mavonengine" in package.json must be an object`);
@@ -99,6 +288,8 @@ function validateManifest(pkg, value) {
99
288
  if (runsOn(manifest.target, side) && typeof manifest[side] !== "string")
100
289
  throw new PluginConfigError(`${pkg}: "mavonengine.${side}" is required for target "${manifest.target}"`);
101
290
  }
291
+ if (manifest.publish !== void 0 && (typeof manifest.publish !== "string" || !manifest.publish))
292
+ throw new PluginConfigError(`${pkg}: "mavonengine.publish" must be a directory of the package`);
102
293
  return manifest;
103
294
  }
104
295
  function readPluginManifest(root, pkg) {
@@ -124,6 +315,8 @@ function assetsDir(plugin) {
124
315
  function enabledPlugins(root, side) {
125
316
  const plugins = [];
126
317
  const warnings = [];
318
+ const incompatible = [];
319
+ const coreVersion = installedPackageVersion(root, "@mavonengine/core");
127
320
  for (const [pkg, entry] of Object.entries(readConfig(root).plugins)) {
128
321
  if (entry?.enabled === false)
129
322
  continue;
@@ -140,6 +333,8 @@ function enabledPlugins(root, side) {
140
333
  }
141
334
  if (!runsOn(installed.manifest.target, side))
142
335
  continue;
336
+ if (engineCompat(installed.manifest.engine, coreVersion) === "incompatible")
337
+ incompatible.push(`${pkg}${installed.version ? ` ${installed.version}` : ""} is made for @mavonengine/core ${installed.manifest.engine}, the project has ${coreVersion}, run 'mavonengine doctor'`);
143
338
  const entryPath = resolveInside(installed.dir, installed.manifest[side]);
144
339
  if (!entryPath || !existsSync(entryPath)) {
145
340
  warnings.push(`${pkg}: ${side} entry ${installed.manifest[side]} not found, is the plugin built?`);
@@ -152,7 +347,7 @@ function enabledPlugins(root, side) {
152
347
  entry: entryPath
153
348
  });
154
349
  }
155
- return { plugins, warnings };
350
+ return { plugins, warnings, incompatible };
156
351
  }
157
352
  function shippedAssetPaths(manifest, usedPrefabs) {
158
353
  const assets = manifest.assets;
@@ -287,6 +482,16 @@ function tickSample(t) {
287
482
  maxCommandsPerTick: num(t.maxCommandsPerTick)
288
483
  };
289
484
  }
485
+ function queueSample(q) {
486
+ return {
487
+ timestamp: num(q.timestamp),
488
+ size: num(q.size),
489
+ running: num(q.running),
490
+ processed: num(q.processed),
491
+ retried: num(q.retried),
492
+ failed: num(q.failed)
493
+ };
494
+ }
290
495
  function accountFrom(value) {
291
496
  if (!isRecord(value) || typeof value.id !== "string" || !value.id)
292
497
  return null;
@@ -301,6 +506,7 @@ function normalizeSnapshot(raw) {
301
506
  const memory = section(s.memory);
302
507
  const physics = isRecord(s.physics) ? s.physics : null;
303
508
  const latency = isRecord(s.latencySimulation) ? s.latencySimulation : null;
509
+ const queue = isRecord(s.queue) ? s.queue : null;
304
510
  return {
305
511
  schemaVersion: num(s.schemaVersion, SUPPORTED_SCHEMA_VERSION),
306
512
  engineVersion: str(s.engineVersion, "unknown"),
@@ -357,7 +563,14 @@ function normalizeSnapshot(raw) {
357
563
  heapTotal: num(memory.heapTotal),
358
564
  external: num(memory.external)
359
565
  },
360
- latencySimulation: latency ? { fixedLatency: num(latency.fixedLatency), jitter: num(latency.jitter), packetLoss: num(latency.packetLoss) } : null
566
+ latencySimulation: latency ? { fixedLatency: num(latency.fixedLatency), jitter: num(latency.jitter), packetLoss: num(latency.packetLoss) } : null,
567
+ // Servers older than the queue have none
568
+ queue: queue ? {
569
+ driver: str(queue.driver, "unknown"),
570
+ working: queue.working !== false,
571
+ latest: isRecord(queue.latest) ? queueSample(queue.latest) : null,
572
+ history: arr(queue.history, queueSample)
573
+ } : null
361
574
  };
362
575
  }
363
576
  function normalizeLogs(raw) {
@@ -1019,6 +1232,8 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
1019
1232
  const cpuHistory = [];
1020
1233
  const bandwidthHistory = [];
1021
1234
  const tickHistory = [];
1235
+ const queueHistory = [];
1236
+ let queued = 0;
1022
1237
  const logs = [];
1023
1238
  let previousPlayers = 0;
1024
1239
  const joinedAt = [];
@@ -1145,6 +1360,13 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
1145
1360
  commandsPerSecond,
1146
1361
  maxCommandsPerTick: playerCount + Math.floor(random() * 3)
1147
1362
  });
1363
+ const dispatched = Math.round(playerCount * 0.3) + (step % 20 === 0 ? 25 : 0);
1364
+ const processed = Math.min(queued + dispatched, 4 + step % 3);
1365
+ const failed = processed > 0 && step % 13 === 0 ? 1 : 0;
1366
+ queued = queued + dispatched - processed;
1367
+ if (failed)
1368
+ log("error", "Job grant-reward failed all 3 tries: Error: reward service unavailable");
1369
+ push(queueHistory, { timestamp: now, size: queued, running: Math.min(queued, 1), processed: processed - failed, retried: step % 7 === 0 ? 1 : 0, failed });
1148
1370
  const average = (ms) => {
1149
1371
  const recent = cpuHistory.slice(-Math.max(1, Math.round(ms / sampleIntervalMs)));
1150
1372
  return Math.round(recent.reduce((acc, h) => acc + h.cpuPercentage, 0) / recent.length * 100) / 100;
@@ -1183,7 +1405,8 @@ function simulatedSource(seed = 1, sampleIntervalMs = 1e3) {
1183
1405
  heapTotal: heapUsed + 3e7,
1184
1406
  external: 5e6
1185
1407
  },
1186
- latencySimulation: null
1408
+ latencySimulation: null,
1409
+ queue: { driver: "database", working: true, latest: queueHistory.at(-1), history: [...queueHistory] }
1187
1410
  };
1188
1411
  return snapshot;
1189
1412
  },
@@ -1265,14 +1488,14 @@ function readableTheme(name) {
1265
1488
  import { stripVTControlCharacters } from "util";
1266
1489
 
1267
1490
  // ../core/dist/Utils/BootBanner.js
1268
- function bootBanner({ version: version2, threeRevision, rapierVersion, mode }) {
1491
+ function bootBanner({ version: version3, threeRevision, rapierVersion, mode }) {
1269
1492
  const row = (label, value) => `\u2502 ${`${label}:`.padEnd(10)}${value.padEnd(28)} \u2502`;
1270
1493
  return [
1271
1494
  "\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510",
1272
1495
  "\u2502 \u2502",
1273
1496
  "\u2502 MavonEngine \u2502",
1274
1497
  "\u2502 \u2502",
1275
- row("Version", version2),
1498
+ row("Version", version3),
1276
1499
  ...threeRevision ? [row("Three.js", `r${threeRevision}`)] : [],
1277
1500
  ...rapierVersion ? [row("Rapier", rapierVersion)] : [],
1278
1501
  row("Mode", mode),
@@ -1782,12 +2005,22 @@ function waiting(ui, theme, state) {
1782
2005
  });
1783
2006
  }
1784
2007
  function wideLayout(ui, theme, state, snapshot, view, transparent) {
1785
- ui.grid({ columns: ["1fr", "1fr"], rows: [11, 11], size: 22 }, (grid) => {
1786
- grid.panel({ title: "CPU" }, (p) => cpuPanel(p, theme, snapshot));
1787
- grid.panel({ title: "Network" }, (p) => networkPanel(p, theme, snapshot));
1788
- grid.panel({ title: "Tick" }, (p) => tickPanel(p, theme, snapshot));
1789
- grid.panel({ title: "World" }, (p) => worldPanel(p, theme, snapshot));
1790
- });
2008
+ if (snapshot.queue) {
2009
+ ui.grid({ columns: ["1fr", "1fr", "1fr"], rows: [11, 11], size: 22 }, (grid) => {
2010
+ grid.panel({ title: "CPU" }, (p) => cpuPanel(p, theme, snapshot));
2011
+ grid.panel({ title: "Network" }, (p) => networkPanel(p, theme, snapshot));
2012
+ grid.panel({ title: "Tick" }, (p) => tickPanel(p, theme, snapshot));
2013
+ grid.panel({ title: queueTitle(snapshot.queue), colSpan: 2 }, (p) => queuePanel(p, theme, snapshot.queue));
2014
+ grid.panel({ title: "World" }, (p) => worldPanel(p, theme, snapshot));
2015
+ });
2016
+ } else {
2017
+ ui.grid({ columns: ["1fr", "1fr"], rows: [11, 11], size: 22 }, (grid) => {
2018
+ grid.panel({ title: "CPU" }, (p) => cpuPanel(p, theme, snapshot));
2019
+ grid.panel({ title: "Network" }, (p) => networkPanel(p, theme, snapshot));
2020
+ grid.panel({ title: "Tick" }, (p) => tickPanel(p, theme, snapshot));
2021
+ grid.panel({ title: "World" }, (p) => worldPanel(p, theme, snapshot));
2022
+ });
2023
+ }
1791
2024
  ui.row({ size: "1fr" }, (row) => {
1792
2025
  playersPanel(row, theme, snapshot, view, transparent);
1793
2026
  logsPanel(row, theme, state, view);
@@ -1797,6 +2030,8 @@ function narrowLayout(ui, theme, state, snapshot, view, transparent) {
1797
2030
  ui.panel({ title: "CPU", size: 9 }, (p) => cpuPanel(p, theme, snapshot));
1798
2031
  ui.panel({ title: "Network", size: 9 }, (p) => networkPanel(p, theme, snapshot));
1799
2032
  ui.panel({ title: "Tick", size: 9 }, (p) => tickPanel(p, theme, snapshot));
2033
+ if (snapshot.queue)
2034
+ ui.panel({ title: queueTitle(snapshot.queue), size: 9 }, (p) => queuePanel(p, theme, snapshot.queue));
1800
2035
  ui.panel({ title: "World", size: 11 }, (p) => worldPanel(p, theme, snapshot));
1801
2036
  playersPanel(ui, theme, snapshot, view, transparent);
1802
2037
  logsPanel(ui, theme, state, view);
@@ -1864,6 +2099,38 @@ function tickPanel(ui, theme, { tick, tickRate }) {
1864
2099
  { label: "Commands/s", value: `${latest?.commandsPerSecond ?? 0} (max ${latest?.maxCommandsPerTick ?? 0}/tick)` }
1865
2100
  ], { spread: true });
1866
2101
  }
2102
+ function queueTitle(queue) {
2103
+ return `Queue (${queue.driver}${queue.working ? "" : ", not worked here"})`;
2104
+ }
2105
+ function queueTotals(queue) {
2106
+ return queue.history.reduce((sum, s) => ({ processed: sum.processed + s.processed, failed: sum.failed + s.failed, retried: sum.retried + s.retried }), { processed: 0, failed: 0, retried: 0 });
2107
+ }
2108
+ function queuePanel(ui, theme, queue) {
2109
+ const latest = queue.latest;
2110
+ const totals = queueTotals(queue);
2111
+ const seconds = Math.round(queue.history.length > 1 ? (queue.history.at(-1).timestamp - queue.history[0].timestamp) / 1e3 : 0);
2112
+ const window = seconds >= 60 ? `${Math.round(seconds / 60)}m` : `${seconds}s`;
2113
+ ui.multiGraph([
2114
+ { label: "queued", values: queue.history.map((s) => s.size), color: theme.graph[0] },
2115
+ { label: "processed", values: queue.history.map((s) => s.processed), color: theme.graph[1] },
2116
+ { label: "failed", values: queue.history.map((s) => s.failed), color: theme.danger }
2117
+ ], {
2118
+ min: 0,
2119
+ max: Math.max(4, ...queue.history.map((s) => Math.max(s.size, s.processed, s.failed))),
2120
+ axis: true,
2121
+ axisFormat: (v) => String(Math.round(v)),
2122
+ legend: true,
2123
+ legendAlign: "right",
2124
+ size: "1fr"
2125
+ });
2126
+ ui.keyValues([
2127
+ { label: "Queued", value: String(latest?.size ?? 0), color: theme.graph[0] },
2128
+ { label: "Running", value: String(latest?.running ?? 0) },
2129
+ { label: `Processed ${window}`, value: String(totals.processed), color: theme.graph[1] },
2130
+ { label: `Retried ${window}`, value: String(totals.retried), color: totals.retried ? theme.warning : void 0 },
2131
+ { label: `Failed ${window}`, value: String(totals.failed), color: totals.failed ? theme.danger : void 0 }
2132
+ ], { spread: true });
2133
+ }
1867
2134
  function worldPanel(ui, theme, { players, world, physics, memory }) {
1868
2135
  ui.keyValues([
1869
2136
  { label: "Players", value: String(players.length), color: theme.primary },
@@ -2855,9 +3122,15 @@ import process4 from "process";
2855
3122
  import { Readable, Transform } from "stream";
2856
3123
  import { pipeline } from "stream/promises";
2857
3124
  import AdmZip from "adm-zip";
2858
- var TEMPLATE_URL = "https://github.com/MavonEngine/Core/archive/refs/tags/0.0.19-alpha.zip";
3125
+ var TEMPLATE_URL = "https://github.com/MavonEngine/Core/archive/refs/tags/0.0.21-alpha.zip";
2859
3126
  var TEMPLATE_SUBPATH = "packages/multiplayer-template";
2860
3127
  var PROJECT_NAME_RE = /^[\w@./-][\w@./\- ]*$/;
3128
+ var NAME_SEPARATORS_RE = /[-_\s]+/;
3129
+ var PATH_SEPARATORS_RE = /[\\/]/;
3130
+ function appNameFor(projectName) {
3131
+ const words = projectName.split(PATH_SEPARATORS_RE).at(-1).split(NAME_SEPARATORS_RE).filter(Boolean);
3132
+ return words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ") || projectName;
3133
+ }
2861
3134
  function projectDirFor(projectName, parentDir) {
2862
3135
  return resolve2(parentDir, projectName);
2863
3136
  }
@@ -2960,6 +3233,12 @@ async function createProject({ projectName, parentDir, report, signal, templateU
2960
3233
  writeFileSync2(pkgJsonPath, `${JSON.stringify(pkg, null, 2)}
2961
3234
  `);
2962
3235
  }
3236
+ updateConfig(projectDir, (config) => {
3237
+ if (typeof config.appName === "string" && config.appName.trim())
3238
+ return false;
3239
+ config.appName = appNameFor(projectName);
3240
+ return true;
3241
+ });
2963
3242
  if (writeMcpConfig(projectDir))
2964
3243
  report.output(`Wrote ${MCP_CONFIG_FILE} so AI assistants with MCP support can inspect the running game server
2965
3244
  `);
@@ -3041,8 +3320,8 @@ function dependencyNames(root) {
3041
3320
  }
3042
3321
  function installedNames(specs, root, before, after) {
3043
3322
  const names = specs.map((spec) => packageNameFromSpec(spec, root)).filter((name) => !!name);
3044
- for (const [name, version2] of after) {
3045
- if (before.get(name) !== version2)
3323
+ for (const [name, version3] of after) {
3324
+ if (before.get(name) !== version3)
3046
3325
  names.push(name);
3047
3326
  }
3048
3327
  return [...new Set(names)];
@@ -3215,7 +3494,7 @@ var PluginInstaller = class {
3215
3494
  // src/dev/control.ts
3216
3495
  var MAX_BODY_BYTES = 8192;
3217
3496
  function readBody(req) {
3218
- return new Promise((resolve7, reject) => {
3497
+ return new Promise((resolve13, reject) => {
3219
3498
  let body = "";
3220
3499
  req.setEncoding("utf8");
3221
3500
  req.on("data", (chunk) => {
@@ -3225,7 +3504,7 @@ function readBody(req) {
3225
3504
  req.destroy();
3226
3505
  }
3227
3506
  });
3228
- req.on("end", () => resolve7(body));
3507
+ req.on("end", () => resolve13(body));
3229
3508
  req.on("error", reject);
3230
3509
  });
3231
3510
  }
@@ -3277,11 +3556,11 @@ function startDevControl(installer) {
3277
3556
  res.end(JSON.stringify({ error: err.message }));
3278
3557
  });
3279
3558
  });
3280
- return new Promise((resolve7, reject) => {
3559
+ return new Promise((resolve13, reject) => {
3281
3560
  server.once("error", reject);
3282
3561
  server.listen(0, "127.0.0.1", () => {
3283
3562
  const url = `http://127.0.0.1:${server.address().port}`;
3284
- resolve7({
3563
+ resolve13({
3285
3564
  url,
3286
3565
  token,
3287
3566
  env: { [DEV_CONTROL_URL_ENV]: url, [DEV_CONTROL_TOKEN_ENV]: token },
@@ -3323,7 +3602,7 @@ var LOCKFILES = [
3323
3602
  ["bun.lockb", "bun"],
3324
3603
  ["package-lock.json", "npm"]
3325
3604
  ];
3326
- var WHITESPACE_RE = /\s+/;
3605
+ var WHITESPACE_RE2 = /\s+/;
3327
3606
  var RUNS_MAVONENGINE_DEV_RE = /\bmavonengine\s+dev\b/;
3328
3607
  var DEV_ENV_FLAG = "MAVONENGINE_DEV_SCRIPT";
3329
3608
  var DEV_SERVER_SCRIPT = "dev:server";
@@ -3407,7 +3686,7 @@ function detectPackageManager(root) {
3407
3686
  function descendants(root, psOutput) {
3408
3687
  const children = /* @__PURE__ */ new Map();
3409
3688
  for (const line of psOutput.trim().split("\n")) {
3410
- const [pid, ppid] = line.trim().split(WHITESPACE_RE).map(Number);
3689
+ const [pid, ppid] = line.trim().split(WHITESPACE_RE2).map(Number);
3411
3690
  if (!children.has(ppid))
3412
3691
  children.set(ppid, []);
3413
3692
  children.get(ppid).push(pid);
@@ -3530,7 +3809,7 @@ function startDevSession(root, options = {}) {
3530
3809
  let dev = startDev(root, options);
3531
3810
  let restarting = false;
3532
3811
  let settle;
3533
- const exited = new Promise((resolve7, reject) => settle = { resolve: resolve7, reject });
3812
+ const exited = new Promise((resolve13, reject) => settle = { resolve: resolve13, reject });
3534
3813
  const watch = (current) => {
3535
3814
  current.exited.then((code) => {
3536
3815
  if (current === dev && !restarting)
@@ -3833,139 +4112,1017 @@ async function runCreateCommand(options) {
3833
4112
  return runCreatePlain(projectName, options.cwd);
3834
4113
  }
3835
4114
 
3836
- // src/commands/mcp.ts
4115
+ // src/commands/doctor.ts
4116
+ import { existsSync as existsSync10, readFileSync as readFileSync8 } from "fs";
4117
+ import { join as join8, resolve as resolve7 } from "path";
3837
4118
  import process9 from "process";
3838
4119
  import { parseArgs as parseArgs6 } from "util";
3839
4120
 
3840
- // src/mcp/GameServerClient.ts
3841
- var GameServerError = class extends Error {
4121
+ // src/doctor/checks.ts
4122
+ import { existsSync as existsSync9, readFileSync as readFileSync7 } from "fs";
4123
+ import { join as join7 } from "path";
4124
+
4125
+ // src/upgrade/migrations.ts
4126
+ import { existsSync as existsSync8 } from "fs";
4127
+ import { join as join6 } from "path";
4128
+ import { pathToFileURL } from "url";
4129
+
4130
+ // ../core/dist/Migrations/index.js
4131
+ var Migrations_exports = {};
4132
+ __export(Migrations_exports, {
4133
+ MIGRATIONS: () => MIGRATIONS,
4134
+ MIGRATIONS_API: () => MIGRATIONS_API,
4135
+ ProjectFiles: () => ProjectFiles,
4136
+ applyMigrations: () => applyMigrations,
4137
+ migrationsFor: () => migrationsFor,
4138
+ pendingMigrations: () => pendingMigrations,
4139
+ recordedMigrations: () => recordedMigrations
4140
+ });
4141
+
4142
+ // ../core/dist/Migrations/migrations.js
4143
+ var CONFIG = "mavonengine.json";
4144
+ var RUNS_MAVONENGINE_DEV_RE2 = /\bmavonengine\s+dev\b/;
4145
+ var TITLE_RE = /(<title[^>]*>)([\s\S]*?)(<\/title>)/i;
4146
+ var ENTITY_RE = /&(amp|lt|gt|quot|#39|apos);/g;
4147
+ var ENTITIES = { "amp": "&", "lt": "<", "gt": ">", "quot": '"', "#39": "'", "apos": "'" };
4148
+ var APP_NAME_PLACEHOLDER = "%MAVONENGINE_APP_NAME%";
4149
+ var INDEX_HTML = ["client/index.html", "index.html"];
4150
+ var devScript = {
4151
+ id: "0.0.22-dev-script",
4152
+ since: "0.0.22",
4153
+ description: "`npm run dev` starts `mavonengine dev`, the old dev script becomes `dev:server`",
4154
+ applies({ files }) {
4155
+ const scripts = files.readJson("package.json")?.scripts;
4156
+ return typeof scripts?.dev === "string" && scripts["dev:server"] === void 0 && !RUNS_MAVONENGINE_DEV_RE2.test(scripts.dev);
4157
+ },
4158
+ run({ files, versions }) {
4159
+ const pkg = files.readJson("package.json");
4160
+ pkg.scripts = Object.fromEntries(Object.entries(pkg.scripts).flatMap(([name, script]) => name === "dev" ? [["dev", "mavonengine dev"], ["dev:server", script]] : [[name, script]]));
4161
+ if (!pkg.dependencies?.["@mavonengine/cli"] && !pkg.devDependencies?.["@mavonengine/cli"]) {
4162
+ const devDependencies = { ...pkg.devDependencies, "@mavonengine/cli": versions.cli ?? "latest" };
4163
+ pkg.devDependencies = Object.fromEntries(Object.entries(devDependencies).sort(([a], [b]) => a.localeCompare(b)));
4164
+ }
4165
+ files.writeJson("package.json", pkg);
4166
+ }
3842
4167
  };
3843
- var NET_UNAVAILABLE = "The network debug endpoints are not available: the game server runs with NODE_ENV=production (they are never served there), or it uses a @mavonengine/core release without them";
3844
- function packetParams(query) {
3845
- return Object.fromEntries(Object.entries(query).filter(([, value]) => value !== void 0 && value !== "").map(([key, value]) => [key, String(value)]));
4168
+ function titleFiles(files) {
4169
+ return INDEX_HTML.flatMap((path) => {
4170
+ const html = files.read(path);
4171
+ const match = html === void 0 ? void 0 : TITLE_RE.exec(html);
4172
+ return match && !match[2].includes(APP_NAME_PLACEHOLDER) ? [{ path, html, title: match[2] }] : [];
4173
+ });
3846
4174
  }
3847
- var DATABASE_UNAVAILABLE = "The game server doesn't show its database: it runs a @mavonengine/core release without GET /api/game/database";
3848
- var DATABASE_DENIED = "The database is only shown with the server's admin token, since it holds what players did: pass it with --token (or MAVONENGINE_METRICS_TOKEN), or run the server on this machine without one";
3849
- var DEV_UNAVAILABLE = "The dev endpoints are not available: the game server runs with NODE_ENV=production (they are never served there), or it uses a @mavonengine/core release without them";
3850
- var GameServerClient = class {
3851
- url;
3852
- clientUrl;
3853
- base;
3854
- clientBase;
3855
- token;
3856
- timeoutMs;
3857
- fetchImpl;
3858
- constructor({ url, clientUrl, token, timeoutMs = 3e3, fetch = globalThis.fetch }) {
3859
- this.base = new URL(url.endsWith("/") ? url : `${url}/`);
3860
- this.url = this.base.href;
3861
- this.clientBase = clientUrl ? new URL(clientUrl.endsWith("/") ? clientUrl : `${clientUrl}/`) : this.base;
3862
- this.clientUrl = this.clientBase.href;
3863
- this.token = token;
3864
- this.timeoutMs = timeoutMs;
3865
- this.fetchImpl = fetch;
4175
+ var appNameTitle = {
4176
+ id: "0.0.25-app-name-title",
4177
+ since: "0.0.25",
4178
+ description: `index.html's title becomes ${APP_NAME_PLACEHOLDER}, the title it had becomes appName in ${CONFIG}`,
4179
+ applies: ({ files }) => titleFiles(files).length > 0,
4180
+ run({ files }) {
4181
+ const found = titleFiles(files);
4182
+ for (const { path, html } of found)
4183
+ files.write(path, html.replace(TITLE_RE, `$1${APP_NAME_PLACEHOLDER}$3`));
4184
+ const config = files.readJson(CONFIG) ?? { plugins: {} };
4185
+ const title = found[0].title.replace(ENTITY_RE, (_, entity) => ENTITIES[entity]).trim();
4186
+ if (config.appName === void 0 && title) {
4187
+ config.appName = title;
4188
+ files.writeJson(CONFIG, config);
4189
+ }
3866
4190
  }
3867
- health() {
3868
- return this.get("api/game/health");
4191
+ };
4192
+ var MIGRATIONS = [devScript, appNameTitle];
4193
+
4194
+ // ../core/dist/Migrations/ProjectFiles.js
4195
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
4196
+ import { dirname as dirname4, resolve as resolve6, sep } from "path";
4197
+ var INDENT_RE = /^[ \t]+(?=")/m;
4198
+ var ProjectFiles = class {
4199
+ constructor(root) {
4200
+ this.staged = /* @__PURE__ */ new Map();
4201
+ this.root = resolve6(root);
3869
4202
  }
3870
- metrics() {
3871
- return this.get("api/game/metrics");
4203
+ full(path) {
4204
+ const full = resolve6(this.root, path);
4205
+ if (full !== this.root && !full.startsWith(this.root + sep))
4206
+ throw new Error(`${path} is outside the project`);
4207
+ return full;
3872
4208
  }
3873
- logs(afterId = 0) {
3874
- return this.get("api/game/logs", { after: String(afterId) }, "The server does not keep logs (metrics.logBufferSize is 0)");
4209
+ onDisk(path) {
4210
+ const full = this.full(path);
4211
+ return existsSync7(full) ? readFileSync6(full, "utf8") : void 0;
3875
4212
  }
3876
- requests(afterId = 0) {
3877
- return this.get("api/game/requests", { after: String(afterId) }, "The server does not record requests (metrics.requestLogSize is 0)");
4213
+ exists(path) {
4214
+ return this.staged.has(path) || existsSync7(this.full(path));
3878
4215
  }
3879
- scene() {
3880
- return this.get("api/game/dev/scene", {}, DEV_UNAVAILABLE);
4216
+ /** The file with the changes made so far, or undefined when it doesn't exist */
4217
+ read(path) {
4218
+ return this.staged.get(path) ?? this.onDisk(path);
3881
4219
  }
3882
- entities(query = {}) {
3883
- const params = {};
3884
- if (query.type)
3885
- params.type = query.type;
3886
- if (query.near)
3887
- params.near = `${query.near.x},${query.near.y},${query.near.z}`;
3888
- for (const key of ["radius", "limit", "offset"]) {
3889
- if (query[key] !== void 0)
3890
- params[key] = String(query[key]);
4220
+ write(path, content) {
4221
+ this.full(path);
4222
+ if (this.onDisk(path) === content)
4223
+ this.staged.delete(path);
4224
+ else
4225
+ this.staged.set(path, content);
4226
+ }
4227
+ /** The parsed file, or undefined when it doesn't exist. Throws when it isn't JSON */
4228
+ readJson(path) {
4229
+ const text = this.read(path);
4230
+ if (text === void 0)
4231
+ return void 0;
4232
+ try {
4233
+ return JSON.parse(text);
4234
+ } catch (err) {
4235
+ throw new Error(`${path} is not valid JSON: ${err.message}`);
3891
4236
  }
3892
- return this.get("api/game/dev/entities", params, DEV_UNAVAILABLE);
3893
4237
  }
3894
- entity(id) {
3895
- return this.get(`api/game/dev/entities/${encodeURIComponent(id)}`, {}, DEV_UNAVAILABLE);
4238
+ /** Write JSON indented like the file already is (two spaces for a new one), with a newline at the end */
4239
+ writeJson(path, value) {
4240
+ const indent = INDENT_RE.exec(this.read(path) ?? "")?.[0] ?? " ";
4241
+ this.write(path, `${JSON.stringify(value, null, indent)}
4242
+ `);
3896
4243
  }
3897
- /** The plugins of the project and whether each runs on the server */
3898
- plugins() {
3899
- return this.get("api/game/plugins", {}, "The game server doesn't list its plugins: it runs a @mavonengine/core release without GET /api/game/plugins, or its metrics endpoints are off");
4244
+ /** What `commit()` would write, in the order the files were first changed */
4245
+ changes() {
4246
+ return Array.from(this.staged, ([path, after]) => ({ path, before: this.onDisk(path), after }));
3900
4247
  }
3901
- /** Every HTTP endpoint of the server, with who registered it */
3902
- routes() {
3903
- return this.get("api/game/routes", {}, "The game server doesn't list its endpoints: it runs a @mavonengine/core release without GET /api/game/routes, or its metrics endpoints are off");
4248
+ /** Write every change to disk */
4249
+ commit() {
4250
+ const changes = this.changes();
4251
+ for (const { path, after } of changes) {
4252
+ const full = this.full(path);
4253
+ mkdirSync2(dirname4(full), { recursive: true });
4254
+ writeFileSync3(full, after);
4255
+ }
4256
+ this.staged.clear();
4257
+ return changes;
3904
4258
  }
3905
- /** The database plugin, the tables with whose they are, their columns and row counts, and the migrations that ran */
3906
- database() {
3907
- return this.get("api/game/database", {}, DATABASE_UNAVAILABLE, DATABASE_DENIED);
4259
+ };
4260
+
4261
+ // ../core/dist/Migrations/index.js
4262
+ var MIGRATIONS_API = 1;
4263
+ var CONFIG2 = "mavonengine.json";
4264
+ function migrationsFor(coreVersion, migrations = MIGRATIONS) {
4265
+ const core = parseVersion(coreVersion);
4266
+ if (!core)
4267
+ return [];
4268
+ return migrations.filter((migration) => {
4269
+ const since = parseVersion(migration.since);
4270
+ return since && compareVersions({ ...core, prerelease: [] }, since) >= 0;
4271
+ });
4272
+ }
4273
+ function recordedMigrations(files) {
4274
+ const recorded = files.readJson(CONFIG2)?.migrations;
4275
+ return Array.isArray(recorded) ? recorded.filter((id) => typeof id === "string") : [];
4276
+ }
4277
+ function pendingMigrations(ctx, migrations = MIGRATIONS) {
4278
+ const done = new Set(recordedMigrations(ctx.files));
4279
+ return migrationsFor(ctx.versions.core, migrations).filter((migration) => !done.has(migration.id) && migration.applies(ctx));
4280
+ }
4281
+ function applyMigrations(ctx, pending, migrations = MIGRATIONS) {
4282
+ for (const migration of pending)
4283
+ migration.run(ctx);
4284
+ const config = ctx.files.readJson(CONFIG2) ?? { plugins: {} };
4285
+ const recorded = new Set(recordedMigrations(ctx.files));
4286
+ const ids = migrationsFor(ctx.versions.core, migrations).map((migration) => migration.id);
4287
+ if (ids.some((id) => !recorded.has(id))) {
4288
+ config.migrations = [...recorded, ...ids.filter((id) => !recorded.has(id))];
4289
+ ctx.files.writeJson(CONFIG2, config);
3908
4290
  }
3909
- /** A page of a table's rows */
3910
- tableRows(table, offset = 0, limit = 50) {
3911
- return this.get(`api/game/database/tables/${encodeURIComponent(table)}`, { offset: String(offset), limit: String(limit) }, `There is no table "${table}". database_overview lists them`, DATABASE_DENIED);
4291
+ return ctx.files.changes();
4292
+ }
4293
+
4294
+ // src/upgrade/migrations.ts
4295
+ async function loadMigrations(root) {
4296
+ const dir = findPackageDir(root, "@mavonengine/core");
4297
+ const file = dir ? join6(dir, "dist", "Migrations", "index.js") : void 0;
4298
+ if (file && existsSync8(file)) {
4299
+ try {
4300
+ const module = await import(pathToFileURL(file).href);
4301
+ if (module.MIGRATIONS_API === MIGRATIONS_API && Array.isArray(module.MIGRATIONS))
4302
+ return { module, from: "project" };
4303
+ } catch {
4304
+ }
3912
4305
  }
3913
- /** Packets and network events the server recorded, oldest first */
3914
- packets(query = {}) {
3915
- return this.get("api/game/dev/net/packets", packetParams(query), NET_UNAVAILABLE);
4306
+ return { module: Migrations_exports, from: "cli" };
4307
+ }
4308
+
4309
+ // src/doctor/checks.ts
4310
+ var GROUPS = ["Environment", CONFIG_FILE, "Plugins", "Migrations"];
4311
+ var CLI_NODE_RANGE = ">=24";
4312
+ var TOP_LEVEL_KEYS = /* @__PURE__ */ new Set(["$schema", "plugins", "database", "auth", "notifications", "appUrl", "appName", "migrations"]);
4313
+ var PROVIDER_KEYS = ["database", "auth", "notifications"];
4314
+ var PLAIN_SPEC_RE = /^[\s\d.<>=^~x*|-]+$/i;
4315
+ function readJson(path) {
4316
+ try {
4317
+ return JSON.parse(readFileSync7(path, "utf8"));
4318
+ } catch {
4319
+ return void 0;
3916
4320
  }
3917
- /** One recorded packet with its payload */
3918
- packet(id) {
3919
- return this.get(`api/game/dev/net/packets/${id}`, {}, NET_UNAVAILABLE);
4321
+ }
4322
+ function installedPackageJson(root, pkg) {
4323
+ const dir = findPackageDir(root, pkg);
4324
+ return dir ? readJson(join7(dir, "package.json")) : void 0;
4325
+ }
4326
+ function coreVersionOf(root) {
4327
+ const version3 = installedPackageJson(root, "@mavonengine/core")?.version;
4328
+ return typeof version3 === "string" ? version3 : void 0;
4329
+ }
4330
+ function installCommand(pm, spec = "") {
4331
+ return `${pm} ${pm === "npm" ? "install" : spec ? "add" : "install"}${spec ? ` ${spec}` : ""}`;
4332
+ }
4333
+ function isNewer(candidate, than) {
4334
+ const a = candidate ? parseVersion(candidate) : void 0;
4335
+ const b = than ? parseVersion(than) : void 0;
4336
+ return !!a && !!b && compareVersions(a, b) > 0;
4337
+ }
4338
+ async function checkEnvironment(ctx) {
4339
+ const findings = [];
4340
+ const add = (finding) => findings.push({ group: "Environment", ...finding });
4341
+ const coreJson = installedPackageJson(ctx.root, "@mavonengine/core");
4342
+ const needs = [CLI_NODE_RANGE, coreJson?.engines?.node].filter((range) => typeof range === "string" && validRange(range));
4343
+ const unmet = needs.filter((range) => !satisfies(ctx.nodeVersion, range));
4344
+ add(unmet.length ? { level: "error", label: `Node ${ctx.nodeVersion}`, detail: `needs ${unmet.join(" and ")}`, fix: "install a newer Node, e.g. from https://nodejs.org" } : { level: "ok", label: `Node ${ctx.nodeVersion}`, detail: `needs ${[...new Set(needs)].join(" and ")}` });
4345
+ const declared = { ...ctx.packageJson.devDependencies, ...ctx.packageJson.dependencies };
4346
+ const packages = Object.keys(declared).filter((name) => name.startsWith("@mavonengine/"));
4347
+ const engine = packages.filter((name) => {
4348
+ const json2 = installedPackageJson(ctx.root, name);
4349
+ return !json2 || json2.mavonengine === void 0;
4350
+ });
4351
+ const packuments = new Map(await Promise.all(engine.map(async (name) => [name, await ctx.npm?.get(name)])));
4352
+ for (const name of engine) {
4353
+ const spec = String(declared[name]);
4354
+ const json2 = installedPackageJson(ctx.root, name);
4355
+ const version3 = typeof json2?.version === "string" ? json2.version : void 0;
4356
+ if (!version3) {
4357
+ add({ level: "error", label: name, detail: `in package.json (${spec}) but not installed`, fix: installCommand(ctx.packageManager) });
4358
+ continue;
4359
+ }
4360
+ if (PLAIN_SPEC_RE.test(spec) && validRange(spec) && !satisfies(version3, spec)) {
4361
+ add({ level: "error", label: `${name} ${version3}`, detail: `package.json asks for ${spec}`, fix: installCommand(ctx.packageManager) });
4362
+ continue;
4363
+ }
4364
+ const latest = packuments.get(name)?.latest;
4365
+ if (isNewer(latest, version3))
4366
+ add({ level: "info", label: `${name} ${version3}`, detail: `${latest} is out` });
4367
+ else
4368
+ add({ level: "ok", label: `${name} ${version3}` });
3920
4369
  }
3921
- /** Who is sent which entities */
3922
- sync() {
3923
- return this.get("api/game/dev/net/sync", {}, NET_UNAVAILABLE);
4370
+ if (!packages.includes("@mavonengine/core"))
4371
+ add({ level: "error", label: "@mavonengine/core", detail: "not in package.json", fix: installCommand(ctx.packageManager, "@mavonengine/core") });
4372
+ return findings;
4373
+ }
4374
+ function registryFinding(npm) {
4375
+ if (npm?.unreachable)
4376
+ return { group: "Environment", level: "warn", label: "npm registry", detail: `${npm.unreachable}, so newer versions weren't looked for`, fix: "check the connection, or pass --offline" };
4377
+ }
4378
+ function checkConfig(root, env = {}) {
4379
+ const findings = [];
4380
+ const add = (finding) => findings.push({ group: CONFIG_FILE, ...finding });
4381
+ const path = configPath(root);
4382
+ if (!existsSync9(path)) {
4383
+ add({ level: "info", label: CONFIG_FILE, detail: "there is none, so no plugins are loaded", fix: "mavonengine install <plugin> creates it" });
4384
+ return { findings, config: { plugins: {} } };
3924
4385
  }
3925
- /** The game tabs open in a browser, through the dev bridge */
3926
- clients() {
3927
- return this.bridge("__mavonengine/clients", {});
4386
+ let raw;
4387
+ try {
4388
+ raw = JSON.parse(readFileSync7(path, "utf8"));
4389
+ } catch (err) {
4390
+ add({ level: "error", label: CONFIG_FILE, detail: `not valid JSON: ${err.message}` });
4391
+ return { findings };
3928
4392
  }
3929
- /**
3930
- * Ask one tab. `clientId` defaults to the only open tab (or the only one not running the editor)
3931
- */
3932
- client(query, params = {}, clientId = "auto") {
3933
- const defined = Object.fromEntries(Object.entries(params).filter(([, v]) => v !== void 0).map(([k, v]) => [k, String(v)]));
3934
- const timeoutMs = query === "trace" ? Number(params.durationMs ?? 3e3) + 15e3 : query === "screenshot" ? 15e3 : query === "status" ? 1e4 : 8e3;
3935
- return this.bridge(`__mavonengine/clients/${encodeURIComponent(clientId)}/${query}`, defined, timeoutMs);
4393
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
4394
+ add({ level: "error", label: CONFIG_FILE, detail: "must contain a JSON object" });
4395
+ return { findings };
3936
4396
  }
3937
- async bridge(path, params, timeoutMs = 5e3) {
3938
- const target = new URL(path, this.clientBase);
3939
- for (const [key, value] of Object.entries(params))
3940
- target.searchParams.set(key, value);
3941
- let res;
3942
- try {
3943
- res = await this.fetchImpl(target, {
3944
- headers: this.token ? { Authorization: `Bearer ${this.token}` } : {},
3945
- signal: AbortSignal.timeout(timeoutMs)
4397
+ const config = raw;
4398
+ if (config.plugins !== void 0 && (!config.plugins || typeof config.plugins !== "object" || Array.isArray(config.plugins))) {
4399
+ add({ level: "error", label: `${CONFIG_FILE} plugins`, detail: "must be an object of package names" });
4400
+ return { findings };
4401
+ }
4402
+ config.plugins ??= {};
4403
+ add({ level: "ok", label: CONFIG_FILE, detail: `${Object.keys(config.plugins).length} plugin${Object.keys(config.plugins).length === 1 ? "" : "s"}` });
4404
+ for (const key of Object.keys(config)) {
4405
+ if (!TOP_LEVEL_KEYS.has(key))
4406
+ add({ level: "info", label: `"${key}"`, detail: "is not a setting MavonEngine knows, a typo?" });
4407
+ }
4408
+ if (config.appUrl !== void 0) {
4409
+ const url = parseAppUrl(config.appUrl);
4410
+ if (!url)
4411
+ add({ level: "error", label: `appUrl ${JSON.stringify(config.appUrl)}`, detail: "is not an http(s) URL", fix: 'e.g. "appUrl": "https://mygame.com"' });
4412
+ else
4413
+ add({ level: "ok", label: `appUrl ${url}`, detail: env.MAVONENGINE_APP_URL ? `MAVONENGINE_APP_URL overrides it here: ${env.MAVONENGINE_APP_URL}` : void 0 });
4414
+ }
4415
+ if (config.appName !== void 0 && (typeof config.appName !== "string" || !config.appName.trim()))
4416
+ add({ level: "warn", label: "appName", detail: "should be the game's name, as text" });
4417
+ for (const key of PROVIDER_KEYS) {
4418
+ const pkg = config[key];
4419
+ if (pkg === void 0)
4420
+ continue;
4421
+ if (typeof pkg !== "string")
4422
+ add({ level: "error", label: `${key}`, detail: 'should be the package name of a plugin in "plugins"' });
4423
+ else if (!config.plugins[pkg])
4424
+ add({ level: "error", label: `${key}: ${pkg}`, detail: 'is not in "plugins"', fix: `mavonengine install ${pkg}` });
4425
+ else if (config.plugins[pkg]?.enabled === false)
4426
+ add({ level: "warn", label: `${key}: ${pkg}`, detail: 'is turned off in "plugins"' });
4427
+ }
4428
+ for (const [pkg, entry] of Object.entries(config.plugins)) {
4429
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
4430
+ add({ level: "error", label: `plugins["${pkg}"]`, detail: 'must be an object, e.g. { "enabled": true }' });
4431
+ continue;
4432
+ }
4433
+ if (entry.enabled !== void 0 && typeof entry.enabled !== "boolean")
4434
+ add({ level: "warn", label: `plugins["${pkg}"].enabled`, detail: "should be true or false" });
4435
+ if (entry.prefabs !== void 0 && (!Array.isArray(entry.prefabs) || entry.prefabs.some((prefab) => typeof prefab !== "string")))
4436
+ add({ level: "warn", label: `plugins["${pkg}"].prefabs`, detail: "should be a list of prefab names" });
4437
+ if (entry.options !== void 0 && (!entry.options || typeof entry.options !== "object" || Array.isArray(entry.options)))
4438
+ add({ level: "warn", label: `plugins["${pkg}"].options`, detail: "should be an object" });
4439
+ }
4440
+ return { findings, config };
4441
+ }
4442
+ async function compatibleVersions(npm, pkg, coreVersion) {
4443
+ const packument = await npm?.get(pkg);
4444
+ if (!packument)
4445
+ return {};
4446
+ const supporting = Object.entries(packument.versions).filter(([, json2]) => engineCompat(engineRangeOf(json2), coreVersion) === "compatible").map(([version3]) => version3);
4447
+ return { forCore: maxSatisfying(supporting, "*"), latest: packument.latest, packument };
4448
+ }
4449
+ async function checkPlugins(ctx, config) {
4450
+ const findings = [];
4451
+ const add = (finding) => findings.push({ group: "Plugins", ...finding });
4452
+ const coreVersion = coreVersionOf(ctx.root);
4453
+ const entries = Object.entries(config.plugins).filter(([, entry]) => entry && typeof entry === "object");
4454
+ const results = await Promise.all(entries.map(async ([pkg, entry]) => {
4455
+ const found = [];
4456
+ const enabled = entry.enabled !== false;
4457
+ const dir = findPackageDir(ctx.root, pkg);
4458
+ const json2 = dir ? readJson(join7(dir, "package.json")) : void 0;
4459
+ if (!dir || !json2) {
4460
+ found.push({ level: enabled ? "error" : "warn", label: pkg, detail: `in ${CONFIG_FILE} but not installed`, fix: `mavonengine install ${pkg}` });
4461
+ return found;
4462
+ }
4463
+ const label = `${pkg}${json2.version ? ` ${json2.version}` : ""}`;
4464
+ if (json2.mavonengine === void 0 || !json2.mavonengine || typeof json2.mavonengine !== "object") {
4465
+ found.push({ level: "error", label, detail: 'not a MavonEngine plugin: its package.json has no "mavonengine" field' });
4466
+ return found;
4467
+ }
4468
+ const manifest = json2.mavonengine;
4469
+ if (!["client", "server", "both"].includes(manifest.target)) {
4470
+ found.push({ level: "error", label, detail: '"mavonengine.target" must be client, server or both' });
4471
+ return found;
4472
+ }
4473
+ if (!enabled) {
4474
+ found.push({ level: "info", label, detail: "turned off" });
4475
+ return found;
4476
+ }
4477
+ for (const side of ["client", "server"]) {
4478
+ if (!runsOn(manifest.target, side))
4479
+ continue;
4480
+ const file = typeof manifest[side] === "string" ? resolveInside(dir, manifest[side]) : void 0;
4481
+ if (!file || !existsSync9(file))
4482
+ found.push({ level: "error", label, detail: `${side} entry ${manifest[side] ?? "(none)"} not found, is the plugin built?` });
4483
+ }
4484
+ const prefabs = Array.isArray(entry.prefabs) ? entry.prefabs.filter((prefab) => typeof prefab === "string") : [];
4485
+ const base = assetsDir({ package: pkg, dir, manifest });
4486
+ const missing = shippedAssetPaths(manifest, prefabs).filter((path) => {
4487
+ const file = resolveInside(base, path);
4488
+ return !file || !existsSync9(file);
4489
+ });
4490
+ if (missing.length)
4491
+ found.push({ level: "warn", label, detail: `asset${missing.length === 1 ? "" : "s"} missing from the release: ${missing.join(", ")}` });
4492
+ if (manifest.publish && !existsSync9(join7(dir, manifest.publish)))
4493
+ found.push({ level: "warn", label, detail: `"mavonengine.publish" directory ${manifest.publish} is not in the package` });
4494
+ const range = engineRangeOf(json2);
4495
+ if (!range) {
4496
+ found.push({ level: "info", label, detail: `doesn't say which @mavonengine/core it supports ("mavonengine.engine")` });
4497
+ } else if (!validRange(range)) {
4498
+ found.push({ level: "warn", label, detail: `"mavonengine.engine" ${JSON.stringify(range)} is not a semver range` });
4499
+ } else if (coreVersion && !satisfies(coreVersion, range)) {
4500
+ const { forCore } = await compatibleVersions(ctx.npm, pkg, coreVersion);
4501
+ found.push({
4502
+ level: "error",
4503
+ label,
4504
+ detail: `made for @mavonengine/core ${range}, the project has ${coreVersion}`,
4505
+ fix: forCore ? `mavonengine install ${pkg}@${forCore}` : `no published version supports core ${coreVersion}; move @mavonengine/core into ${range}`
3946
4506
  });
3947
- } catch (err) {
3948
- throw new GameServerError(`Can't reach the client dev server at ${this.clientUrl}: ${err.message}. Is it running?`);
4507
+ } else if (coreVersion) {
4508
+ const { forCore } = await compatibleVersions(ctx.npm, pkg, coreVersion);
4509
+ if (isNewer(forCore, json2.version))
4510
+ found.push({ level: "info", label, detail: `core ${range}; ${forCore} is out and supports core ${coreVersion}`, fix: `mavonengine install ${pkg}@${forCore}` });
3949
4511
  }
3950
- const isJson = res.headers.get("content-type")?.includes("application/json");
3951
- const body = isJson ? await res.json().catch(() => null) : null;
3952
- if (!isJson || res.status === 404 && !body?.error) {
3953
- throw new GameServerError(`No dev bridge at ${this.clientUrl}. The game client must be served by Vite in dev with the mavonengine Vite plugin (@mavonengine/core/vite.config). If Vite runs on its own port, pass --client-url, e.g. http://localhost:5173`);
4512
+ if (!found.some((finding) => finding.label === label))
4513
+ found.push({ level: "ok", label, detail: range ? `core ${range}` : void 0 });
4514
+ return found;
4515
+ }));
4516
+ for (const found of results) {
4517
+ for (const finding of found)
4518
+ add(finding);
4519
+ }
4520
+ const declared = Object.keys({ ...ctx.packageJson.devDependencies, ...ctx.packageJson.dependencies });
4521
+ for (const pkg of declared) {
4522
+ if (config.plugins[pkg] !== void 0)
4523
+ continue;
4524
+ const json2 = installedPackageJson(ctx.root, pkg);
4525
+ if (json2?.mavonengine && typeof json2.mavonengine === "object")
4526
+ add({ level: "info", label: pkg, detail: `a plugin that is installed but not in ${CONFIG_FILE}, so it isn't loaded`, fix: `mavonengine install ${pkg}` });
4527
+ }
4528
+ if (!findings.length)
4529
+ add({ level: "ok", label: "no plugins" });
4530
+ return findings;
4531
+ }
4532
+ async function checkMigrations(ctx, cliVersion) {
4533
+ const coreVersion = coreVersionOf(ctx.root);
4534
+ if (!coreVersion)
4535
+ return [];
4536
+ const { module } = await loadMigrations(ctx.root);
4537
+ let pending;
4538
+ try {
4539
+ pending = module.pendingMigrations({ files: new module.ProjectFiles(ctx.root), versions: { core: coreVersion, cli: cliVersion } });
4540
+ } catch (err) {
4541
+ return [{ group: "Migrations", level: "warn", label: "migrations", detail: `can't be checked: ${err.message}` }];
4542
+ }
4543
+ if (!pending.length)
4544
+ return [{ group: "Migrations", level: "ok", label: "none pending" }];
4545
+ return pending.map((migration, index) => ({
4546
+ group: "Migrations",
4547
+ level: "warn",
4548
+ label: migration.id,
4549
+ detail: migration.description,
4550
+ fix: index === pending.length - 1 ? "mavonengine upgrade --only-migrations" : void 0
4551
+ }));
4552
+ }
4553
+
4554
+ // src/doctor/npm.ts
4555
+ var NPM_REGISTRY_URL = "https://registry.npmjs.org";
4556
+ var TRAILING_SLASHES_RE2 = /\/+$/;
4557
+ var NpmRegistry = class {
4558
+ url;
4559
+ /** Why the registry couldn't be reached, once it couldn't */
4560
+ unreachable;
4561
+ timeoutMs;
4562
+ fetch;
4563
+ cache = /* @__PURE__ */ new Map();
4564
+ constructor({ url = NPM_REGISTRY_URL, timeoutMs = 1e4, fetch = globalThis.fetch } = {}) {
4565
+ this.url = url.replace(TRAILING_SLASHES_RE2, "");
4566
+ this.timeoutMs = timeoutMs;
4567
+ this.fetch = fetch;
4568
+ }
4569
+ /** The package, or undefined when the registry doesn't have it or can't be reached. Asked once per package */
4570
+ get(pkg) {
4571
+ let packument = this.cache.get(pkg);
4572
+ if (!packument) {
4573
+ packument = this.load(pkg);
4574
+ this.cache.set(pkg, packument);
3954
4575
  }
3955
- if (res.status === 401 || res.status === 403)
3956
- throw new GameServerError(`${body?.error ?? "Not allowed"}: pass --token or set MAVONENGINE_METRICS_TOKEN for both the CLI and the dev server`);
3957
- if (!res.ok)
3958
- throw new GameServerError(body?.error ?? `Client dev server responded ${res.status} ${res.statusText}`);
3959
- return body;
4576
+ return packument;
3960
4577
  }
3961
- async get(path, params = {}, notFound, denied) {
3962
- const target = new URL(path, this.base);
3963
- for (const [key, value] of Object.entries(params))
3964
- target.searchParams.set(key, value);
4578
+ async load(pkg) {
4579
+ if (this.unreachable)
4580
+ return void 0;
4581
+ const url = `${this.url}/${pkg.replace("/", "%2F")}`;
3965
4582
  let res;
3966
4583
  try {
3967
- res = await this.fetchImpl(target, {
3968
- headers: this.token ? { Authorization: `Bearer ${this.token}` } : {},
4584
+ res = await this.fetch(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(this.timeoutMs) });
4585
+ } catch (err) {
4586
+ this.unreachable ??= `can't reach ${this.url}: ${err.message}`;
4587
+ return void 0;
4588
+ }
4589
+ if (res.status === 404)
4590
+ return void 0;
4591
+ if (!res.ok) {
4592
+ this.unreachable ??= `${this.url} answered ${res.status} ${res.statusText}`;
4593
+ return void 0;
4594
+ }
4595
+ try {
4596
+ const doc = await res.json();
4597
+ return { name: doc.name ?? pkg, latest: doc["dist-tags"]?.latest, versions: doc.versions ?? {} };
4598
+ } catch (err) {
4599
+ this.unreachable ??= `${url} is not valid JSON: ${err.message}`;
4600
+ return void 0;
4601
+ }
4602
+ }
4603
+ };
4604
+
4605
+ // src/commands/doctor.ts
4606
+ var DOCTOR_HELP = `Usage: mavonengine doctor [options]
4607
+
4608
+ Check the MavonEngine project you are in: the Node version, the @mavonengine packages,
4609
+ ${CONFIG_FILE}, and whether each plugin in it is installed, built and made for the
4610
+ project's @mavonengine/core. Changes nothing.
4611
+
4612
+ Asks the npm registry which versions exist, to say what to install when something
4613
+ doesn't fit. --offline leaves that out.
4614
+
4615
+ Exits with 1 when something is wrong, and with --strict also on warnings.
4616
+
4617
+ Options:
4618
+ --offline Don't ask the npm registry
4619
+ --strict Fail on warnings too
4620
+ --json Print the findings as JSON
4621
+ --cwd <dir> Start looking for the project here (default: current directory)
4622
+ -h, --help Show this help
4623
+ `;
4624
+ function parseDoctorArgs(args, cwd = process9.cwd(), env = process9.env) {
4625
+ const { values, positionals } = parseArgs6({
4626
+ args,
4627
+ options: {
4628
+ offline: { type: "boolean", default: false },
4629
+ strict: { type: "boolean", default: false },
4630
+ json: { type: "boolean", default: false },
4631
+ cwd: { type: "string" },
4632
+ help: { type: "boolean", short: "h", default: false }
4633
+ },
4634
+ strict: true,
4635
+ allowPositionals: true
4636
+ });
4637
+ if (values.help)
4638
+ return "help";
4639
+ if (positionals.length > 0)
4640
+ throw new UsageError(`unexpected argument '${positionals[0]}'
4641
+
4642
+ ${DOCTOR_HELP}`);
4643
+ return {
4644
+ cwd: resolve7(cwd, values.cwd ?? "."),
4645
+ offline: values.offline,
4646
+ strict: values.strict,
4647
+ json: values.json,
4648
+ registry: env.npm_config_registry || NPM_REGISTRY_URL
4649
+ };
4650
+ }
4651
+ async function runDoctor(root, options, io = {}) {
4652
+ const ctx = {
4653
+ root,
4654
+ packageManager: detectPackageManager(root),
4655
+ packageJson: JSON.parse(readFileSync8(join8(root, "package.json"), "utf8")),
4656
+ nodeVersion: io.nodeVersion ?? process9.versions.node,
4657
+ npm: options.offline ? void 0 : new NpmRegistry({ url: options.registry, fetch: io.fetch })
4658
+ };
4659
+ const { findings: configFindings, config } = checkConfig(root, io.env ?? process9.env);
4660
+ const [environment, plugins, migrations] = await Promise.all([
4661
+ checkEnvironment(ctx),
4662
+ config ? checkPlugins(ctx, config) : [],
4663
+ config ? checkMigrations(ctx, version) : []
4664
+ ]);
4665
+ const registry = registryFinding(ctx.npm);
4666
+ const findings = [...environment, ...registry ? [registry] : [], ...configFindings, ...plugins, ...migrations];
4667
+ return {
4668
+ root,
4669
+ packageManager: ctx.packageManager,
4670
+ coreVersion: coreVersionOf(root),
4671
+ findings,
4672
+ errors: findings.filter((finding) => finding.level === "error").length,
4673
+ warnings: findings.filter((finding) => finding.level === "warn").length
4674
+ };
4675
+ }
4676
+ var MARKS = { ok: "\u2713", info: "i", warn: "!", error: "\u2717" };
4677
+ var COLORS = { ok: "32", info: "36", warn: "33", error: "31" };
4678
+ function formatReport(report, { color = false } = {}) {
4679
+ const paint = (code, text) => color ? `\x1B[${code}m${text}\x1B[0m` : text;
4680
+ const lines = [`MavonEngine project at ${report.root} (${report.packageManager}${report.coreVersion ? `, @mavonengine/core ${report.coreVersion}` : ""})`];
4681
+ for (const group of GROUPS) {
4682
+ const findings = report.findings.filter((finding) => finding.group === group);
4683
+ if (!findings.length)
4684
+ continue;
4685
+ const width = Math.min(40, Math.max(...findings.map((finding) => finding.label.length)));
4686
+ lines.push("", paint("1", group));
4687
+ for (const finding of findings) {
4688
+ const text = finding.detail ? `${finding.label.padEnd(width)} ${finding.detail}` : finding.label;
4689
+ lines.push(` ${paint(COLORS[finding.level], MARKS[finding.level])} ${text}`);
4690
+ if (finding.fix)
4691
+ lines.push(` ${paint("2", `\u2192 ${finding.fix}`)}`);
4692
+ }
4693
+ }
4694
+ const count = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
4695
+ lines.push("", report.errors || report.warnings ? `${count(report.errors, "error")}, ${count(report.warnings, "warning")}` : paint(COLORS.ok, "Everything looks fine"));
4696
+ return `${lines.join("\n")}
4697
+ `;
4698
+ }
4699
+ async function runDoctorCommand(options, io = { write: (text) => void process9.stdout.write(text), color: !!process9.stdout.isTTY && !process9.env.NO_COLOR }) {
4700
+ const root = findProjectRoot(options.cwd);
4701
+ if (!root || !existsSync10(join8(root, "package.json")))
4702
+ throw new UsageError(`no MavonEngine project found in ${options.cwd} or its parents (looking for a package.json with @mavonengine/core and a dev script)`);
4703
+ const report = await runDoctor(root, options, io);
4704
+ io.write(options.json ? `${JSON.stringify(report, null, 2)}
4705
+ ` : formatReport(report, { color: io.color }));
4706
+ return report.errors || options.strict && report.warnings ? 1 : 0;
4707
+ }
4708
+
4709
+ // src/commands/make.ts
4710
+ import { join as join11, resolve as resolve9 } from "path";
4711
+ import process10 from "process";
4712
+ import { parseArgs as parseArgs7 } from "util";
4713
+
4714
+ // src/make/plugin.ts
4715
+ import { existsSync as existsSync12, readFileSync as readFileSync9, writeFileSync as writeFileSync5 } from "fs";
4716
+ import { join as join10 } from "path";
4717
+
4718
+ // src/make/scaffold.ts
4719
+ import { existsSync as existsSync11, mkdirSync as mkdirSync3, writeFileSync as writeFileSync4 } from "fs";
4720
+ import { dirname as dirname5, isAbsolute as isAbsolute3, join as join9, relative as relative3, resolve as resolve8 } from "path";
4721
+ var PACKAGE_NAME_RE = /^(?:@[a-z0-9][\w.~-]*\/)?[a-z0-9][\w.~-]*$/;
4722
+ var WORD_SEPARATORS_RE = /[^a-z0-9]+/i;
4723
+ function nameWords(name) {
4724
+ return name.split("/").at(-1).split(WORD_SEPARATORS_RE).filter(Boolean);
4725
+ }
4726
+ function kebabName(name) {
4727
+ return nameWords(name).map((word) => word.toLowerCase()).join("-");
4728
+ }
4729
+ function titleName(name) {
4730
+ return nameWords(name).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
4731
+ }
4732
+ function writeScaffold(dir, files) {
4733
+ if (existsSync11(dir))
4734
+ throw new Error(`${dir} already exists`);
4735
+ const root = resolve8(dir);
4736
+ const paths = Object.keys(files);
4737
+ for (const path of paths) {
4738
+ const full = resolve8(root, path);
4739
+ const inside = relative3(root, full);
4740
+ if (!inside || inside.startsWith("..") || isAbsolute3(inside))
4741
+ throw new Error(`Refusing to write ${path} outside ${dir}`);
4742
+ }
4743
+ for (const path of paths) {
4744
+ const full = join9(root, path);
4745
+ mkdirSync3(dirname5(full), { recursive: true });
4746
+ writeFileSync4(full, files[path]);
4747
+ }
4748
+ return paths;
4749
+ }
4750
+
4751
+ // src/make/plugin.ts
4752
+ var PLUGINS_DIR = "plugins";
4753
+ var PLUGINS_WORKSPACE = `${PLUGINS_DIR}/*`;
4754
+ var INDENT_RE2 = /^[ \t]+/m;
4755
+ function pluginDirFor(name) {
4756
+ return `${PLUGINS_DIR}/${kebabName(name)}`;
4757
+ }
4758
+ function json(value) {
4759
+ return `${JSON.stringify(value, null, 2)}
4760
+ `;
4761
+ }
4762
+ function pluginFiles({ name, target, engine }) {
4763
+ const title = titleName(name) || name;
4764
+ const slug = kebabName(name) || "plugin";
4765
+ const client = runsOn(target, "client");
4766
+ const server = runsOn(target, "server");
4767
+ const files = {};
4768
+ files["package.json"] = json({
4769
+ name,
4770
+ type: "module",
4771
+ version: "0.1.0",
4772
+ private: true,
4773
+ description: `${title}: a MavonEngine plugin`,
4774
+ scripts: {
4775
+ typecheck: "tsc -p tsconfig.json"
4776
+ },
4777
+ ...engine ? { peerDependencies: { "@mavonengine/core": engine } } : {},
4778
+ mavonengine: {
4779
+ target,
4780
+ ...client ? { client: "./src/client.ts" } : {},
4781
+ ...server ? { server: "./src/server.ts" } : {},
4782
+ ...engine ? { engine } : {}
4783
+ }
4784
+ });
4785
+ files["tsconfig.json"] = json({
4786
+ compilerOptions: {
4787
+ target: "es2022",
4788
+ lib: client ? ["es2022", "dom"] : ["es2022"],
4789
+ module: "nodenext",
4790
+ moduleResolution: "nodenext",
4791
+ strict: true,
4792
+ noEmit: true,
4793
+ skipLibCheck: true,
4794
+ // The server entry runs through Node's type stripping, which only takes erasable syntax and .ts imports
4795
+ allowImportingTsExtensions: true,
4796
+ erasableSyntaxOnly: true,
4797
+ verbatimModuleSyntax: true
4798
+ },
4799
+ include: ["src"]
4800
+ });
4801
+ if (client) {
4802
+ files["src/client.ts"] = `import { defineClientPlugin } from '@mavonengine/core/Plugins/types'
4803
+
4804
+ export default defineClientPlugin({
4805
+ name: ${JSON.stringify(title)},
4806
+
4807
+ // Files the game loads with the plugin, from its assets/ directory:
4808
+ // assets: ctx => [{ name: 'tree', type: 'gltfModel', path: ctx.assetUrl('models/tree.glb') }],
4809
+
4810
+ setup(ctx) {
4811
+ ctx.logger?.info(\`\${ctx.package} loaded on the client\`)
4812
+ },
4813
+
4814
+ update(_delta, _ctx) {},
4815
+ })
4816
+ `;
4817
+ }
4818
+ if (server) {
4819
+ files["src/server.ts"] = `import { defineServerPlugin } from '@mavonengine/core/Plugins/types'
4820
+
4821
+ export default defineServerPlugin({
4822
+ name: ${JSON.stringify(title)},
4823
+
4824
+ setup(ctx) {
4825
+ ctx.logger?.info(\`\${ctx.package} loaded on the server\`)
4826
+ },
4827
+
4828
+ http(app, _ctx) {
4829
+ app.get('/api/${slug}/status', (_req, res) => res.json({ ok: true }))
4830
+ },
4831
+
4832
+ onConnection(_channel, _client, _ctx) {},
4833
+
4834
+ tick(_delta, _ctx) {},
4835
+ })
4836
+ `;
4837
+ }
4838
+ const sides = [client && "`src/client.ts` runs in the game", server && "`src/server.ts` runs on the game server"].filter(Boolean);
4839
+ files["README.md"] = `# ${title}
4840
+
4841
+ A MavonEngine plugin, made with \`mavonengine make:plugin\`. ${sides.join(" and ")}.
4842
+
4843
+ It is a workspace of the project and registered in \`mavonengine.json\`, so \`mavonengine dev\` loads it.
4844
+ ${client ? "The game reloads when the client entry changes. " : ""}${server ? "Restart the game server to pick up changes to the server entry." : ""}
4845
+
4846
+ - Options: \`plugins["${name}"].options\` in \`mavonengine.json\`, as \`ctx.options\`.
4847
+ - Assets: put them in \`assets/\` and list them under \`mavonengine.assets\` in \`package.json\`.
4848
+ - Types: \`npm run typecheck\` in this directory.
4849
+
4850
+ See [Writing a plugin](https://github.com/MavonEngine/Core/tree/main/packages/cli#writing-a-plugin) for every hook.
4851
+ `;
4852
+ return files;
4853
+ }
4854
+ function linkPlugin(root, pm, name, dir) {
4855
+ const path = join10(root, "package.json");
4856
+ const text = readFileSync9(path, "utf8");
4857
+ const pkg = JSON.parse(text);
4858
+ const indent = INDENT_RE2.exec(text)?.[0] ?? " ";
4859
+ let change;
4860
+ if (pm === "pnpm" || existsSync12(join10(root, "pnpm-workspace.yaml"))) {
4861
+ const spec = `link:./${dir}`;
4862
+ if (pkg.dependencies?.[name] === spec)
4863
+ return void 0;
4864
+ pkg.dependencies = { ...pkg.dependencies, [name]: spec };
4865
+ change = `added "${name}": "${spec}" to dependencies`;
4866
+ } else {
4867
+ const list = Array.isArray(pkg.workspaces) ? pkg.workspaces : pkg.workspaces?.packages;
4868
+ const globs = Array.isArray(list) ? list.map(String) : [];
4869
+ if (globs.includes(PLUGINS_WORKSPACE) || globs.includes(dir) || globs.includes(`./${dir}`))
4870
+ return void 0;
4871
+ if (pkg.workspaces && !Array.isArray(pkg.workspaces) && typeof pkg.workspaces === "object")
4872
+ pkg.workspaces.packages = [...globs, PLUGINS_WORKSPACE];
4873
+ else
4874
+ pkg.workspaces = [...globs, PLUGINS_WORKSPACE];
4875
+ change = `added "${PLUGINS_WORKSPACE}" to workspaces`;
4876
+ }
4877
+ writeFileSync5(path, `${JSON.stringify(pkg, null, indent)}
4878
+ `);
4879
+ return change;
4880
+ }
4881
+
4882
+ // src/commands/make.ts
4883
+ var TARGETS2 = ["client", "server", "both"];
4884
+ var MAKE_PLUGIN_HELP = `Usage: mavonengine make:plugin <name> [options]
4885
+
4886
+ Create a plugin inside the MavonEngine project you are in, in plugins/<name>/.
4887
+ It is linked as a workspace, registered in ${CONFIG_FILE} and runs from its
4888
+ TypeScript sources, so 'mavonengine dev' loads it without a build step.
4889
+
4890
+ <name> is the plugin's package name, e.g. forest or @acme/forest.
4891
+
4892
+ Options:
4893
+ --target <side> client, server or both (default: both)
4894
+ --cwd <dir> Start looking for the project here (default: current directory)
4895
+ --no-register Leave ${CONFIG_FILE} alone
4896
+ --no-install Don't run the package manager to link the plugin
4897
+ -h, --help Show this help
4898
+ `;
4899
+ function parseMakePluginArgs(args, cwd = process10.cwd()) {
4900
+ const { values, positionals } = parseArgs7({
4901
+ args,
4902
+ options: {
4903
+ target: { type: "string", default: "both" },
4904
+ cwd: { type: "string" },
4905
+ register: { type: "boolean", default: true },
4906
+ install: { type: "boolean", default: true },
4907
+ help: { type: "boolean", short: "h", default: false }
4908
+ },
4909
+ strict: true,
4910
+ allowPositionals: true,
4911
+ allowNegative: true
4912
+ });
4913
+ if (values.help)
4914
+ return "help";
4915
+ if (positionals.length === 0)
4916
+ throw new UsageError(`name the plugin, e.g. mavonengine make:plugin forest
4917
+
4918
+ ${MAKE_PLUGIN_HELP}`);
4919
+ if (positionals.length > 1)
4920
+ throw new UsageError(`expected one plugin name, got ${positionals.length}`);
4921
+ const name = positionals[0].trim();
4922
+ if (!PACKAGE_NAME_RE.test(name))
4923
+ throw new UsageError(`'${name}' is not a package name: use lower case letters, digits and - . _ ~, optionally with a @scope/`);
4924
+ const target = values.target;
4925
+ if (!TARGETS2.includes(target))
4926
+ throw new UsageError(`--target must be one of ${TARGETS2.join(", ")}`);
4927
+ return { cwd: resolve9(cwd, values.cwd ?? "."), name, target, register: values.register, install: values.install };
4928
+ }
4929
+ var terminalIO2 = {
4930
+ run: (command, args, cwd) => runCommand(command, args, cwd, {
4931
+ report: { step: () => {
4932
+ }, output: (chunk) => process10.stdout.write(chunk) }
4933
+ }),
4934
+ write: (text) => process10.stdout.write(text)
4935
+ };
4936
+ async function runMakePluginCommand(options, io = terminalIO2) {
4937
+ const root = findProjectRoot(options.cwd);
4938
+ if (!root)
4939
+ throw new UsageError(`no MavonEngine project found in ${options.cwd} or its parents (looking for a package.json with @mavonengine/core and a dev script)`);
4940
+ const config = readConfig(root);
4941
+ if (config.plugins[options.name])
4942
+ throw new UsageError(`${options.name} is already in ${CONFIG_FILE}`);
4943
+ if (findPackageDir(root, options.name))
4944
+ throw new UsageError(`a package named ${options.name} is already installed, pick another name`);
4945
+ const dir = pluginDirFor(options.name);
4946
+ const engineVersion = installedEngineVersion(root);
4947
+ const files = pluginFiles({ name: options.name, target: options.target, engine: engineVersion ? `>=${engineVersion}` : void 0 });
4948
+ let written;
4949
+ try {
4950
+ written = writeScaffold(join11(root, dir), files);
4951
+ } catch (err) {
4952
+ throw new UsageError(err.message);
4953
+ }
4954
+ io.write(`mavonengine: created ${options.name} in ${dir}/
4955
+ `);
4956
+ for (const path of written)
4957
+ io.write(` ${dir}/${path}
4958
+ `);
4959
+ const pm = detectPackageManager(root);
4960
+ const linked = linkPlugin(root, pm, options.name, dir);
4961
+ if (linked)
4962
+ io.write(` package.json: ${linked}
4963
+ `);
4964
+ if (options.register) {
4965
+ addPluginToConfig(root, options.name);
4966
+ io.write(` ${CONFIG_FILE}: added ${options.name}
4967
+ `);
4968
+ }
4969
+ if (options.install) {
4970
+ io.write(`
4971
+ mavonengine: running '${pm} install' in ${root} to link it
4972
+ `);
4973
+ try {
4974
+ await io.run(pm, ["install"], root);
4975
+ } catch (err) {
4976
+ io.write(`
4977
+ mavonengine: ${err.message}. The plugin is written; run '${pm} install' to link it
4978
+ `);
4979
+ return 1;
4980
+ }
4981
+ }
4982
+ const next = [
4983
+ !options.install && `run '${pm} install' to link it`,
4984
+ !options.register && `add "${options.name}": { "enabled": true } to "plugins" in ${CONFIG_FILE} to load it`,
4985
+ `edit ${dir}/src/ and run 'mavonengine dev'`
4986
+ ].filter(Boolean);
4987
+ io.write(`
4988
+ Next: ${next.join(", then ")}
4989
+ `);
4990
+ return 0;
4991
+ }
4992
+
4993
+ // src/commands/mcp.ts
4994
+ import process11 from "process";
4995
+ import { parseArgs as parseArgs8 } from "util";
4996
+
4997
+ // src/mcp/GameServerClient.ts
4998
+ var GameServerError = class extends Error {
4999
+ };
5000
+ var NET_UNAVAILABLE = "The network debug endpoints are not available: the game server runs with NODE_ENV=production (they are never served there), or it uses a @mavonengine/core release without them";
5001
+ function packetParams(query) {
5002
+ return Object.fromEntries(Object.entries(query).filter(([, value]) => value !== void 0 && value !== "").map(([key, value]) => [key, String(value)]));
5003
+ }
5004
+ var DATABASE_UNAVAILABLE = "The game server doesn't show its database: it runs a @mavonengine/core release without GET /api/game/database";
5005
+ var DATABASE_DENIED = "The database is only shown with the server's admin token, since it holds what players did: pass it with --token (or MAVONENGINE_METRICS_TOKEN), or run the server on this machine without one";
5006
+ var DEV_UNAVAILABLE = "The dev endpoints are not available: the game server runs with NODE_ENV=production (they are never served there), or it uses a @mavonengine/core release without them";
5007
+ var GameServerClient = class {
5008
+ url;
5009
+ clientUrl;
5010
+ base;
5011
+ clientBase;
5012
+ token;
5013
+ timeoutMs;
5014
+ fetchImpl;
5015
+ constructor({ url, clientUrl, token, timeoutMs = 3e3, fetch = globalThis.fetch }) {
5016
+ this.base = new URL(url.endsWith("/") ? url : `${url}/`);
5017
+ this.url = this.base.href;
5018
+ this.clientBase = clientUrl ? new URL(clientUrl.endsWith("/") ? clientUrl : `${clientUrl}/`) : this.base;
5019
+ this.clientUrl = this.clientBase.href;
5020
+ this.token = token;
5021
+ this.timeoutMs = timeoutMs;
5022
+ this.fetchImpl = fetch;
5023
+ }
5024
+ health() {
5025
+ return this.get("api/game/health");
5026
+ }
5027
+ metrics() {
5028
+ return this.get("api/game/metrics");
5029
+ }
5030
+ logs(afterId = 0) {
5031
+ return this.get("api/game/logs", { after: String(afterId) }, "The server does not keep logs (metrics.logBufferSize is 0)");
5032
+ }
5033
+ requests(afterId = 0) {
5034
+ return this.get("api/game/requests", { after: String(afterId) }, "The server does not record requests (metrics.requestLogSize is 0)");
5035
+ }
5036
+ scene() {
5037
+ return this.get("api/game/dev/scene", {}, DEV_UNAVAILABLE);
5038
+ }
5039
+ entities(query = {}) {
5040
+ const params = {};
5041
+ if (query.type)
5042
+ params.type = query.type;
5043
+ if (query.near)
5044
+ params.near = `${query.near.x},${query.near.y},${query.near.z}`;
5045
+ for (const key of ["radius", "limit", "offset"]) {
5046
+ if (query[key] !== void 0)
5047
+ params[key] = String(query[key]);
5048
+ }
5049
+ return this.get("api/game/dev/entities", params, DEV_UNAVAILABLE);
5050
+ }
5051
+ entity(id) {
5052
+ return this.get(`api/game/dev/entities/${encodeURIComponent(id)}`, {}, DEV_UNAVAILABLE);
5053
+ }
5054
+ /** The plugins of the project and whether each runs on the server */
5055
+ plugins() {
5056
+ return this.get("api/game/plugins", {}, "The game server doesn't list its plugins: it runs a @mavonengine/core release without GET /api/game/plugins, or its metrics endpoints are off");
5057
+ }
5058
+ /** Every HTTP endpoint of the server, with who registered it */
5059
+ routes() {
5060
+ return this.get("api/game/routes", {}, "The game server doesn't list its endpoints: it runs a @mavonengine/core release without GET /api/game/routes, or its metrics endpoints are off");
5061
+ }
5062
+ /** The database plugin, the tables with whose they are, their columns and row counts, and the migrations that ran */
5063
+ database() {
5064
+ return this.get("api/game/database", {}, DATABASE_UNAVAILABLE, DATABASE_DENIED);
5065
+ }
5066
+ /** A page of a table's rows */
5067
+ tableRows(table, offset = 0, limit = 50) {
5068
+ return this.get(`api/game/database/tables/${encodeURIComponent(table)}`, { offset: String(offset), limit: String(limit) }, `There is no table "${table}". database_overview lists them`, DATABASE_DENIED);
5069
+ }
5070
+ /** Packets and network events the server recorded, oldest first */
5071
+ packets(query = {}) {
5072
+ return this.get("api/game/dev/net/packets", packetParams(query), NET_UNAVAILABLE);
5073
+ }
5074
+ /** One recorded packet with its payload */
5075
+ packet(id) {
5076
+ return this.get(`api/game/dev/net/packets/${id}`, {}, NET_UNAVAILABLE);
5077
+ }
5078
+ /** Who is sent which entities */
5079
+ sync() {
5080
+ return this.get("api/game/dev/net/sync", {}, NET_UNAVAILABLE);
5081
+ }
5082
+ /** The game tabs open in a browser, through the dev bridge */
5083
+ clients() {
5084
+ return this.bridge("__mavonengine/clients", {});
5085
+ }
5086
+ /**
5087
+ * Ask one tab. `clientId` defaults to the only open tab (or the only one not running the editor)
5088
+ */
5089
+ client(query, params = {}, clientId = "auto") {
5090
+ const defined = Object.fromEntries(Object.entries(params).filter(([, v]) => v !== void 0).map(([k, v]) => [k, String(v)]));
5091
+ const timeoutMs = query === "trace" ? Number(params.durationMs ?? 3e3) + 15e3 : query === "screenshot" ? 15e3 : query === "status" ? 1e4 : 8e3;
5092
+ return this.bridge(`__mavonengine/clients/${encodeURIComponent(clientId)}/${query}`, defined, timeoutMs);
5093
+ }
5094
+ async bridge(path, params, timeoutMs = 5e3) {
5095
+ const target = new URL(path, this.clientBase);
5096
+ for (const [key, value] of Object.entries(params))
5097
+ target.searchParams.set(key, value);
5098
+ let res;
5099
+ try {
5100
+ res = await this.fetchImpl(target, {
5101
+ headers: this.token ? { Authorization: `Bearer ${this.token}` } : {},
5102
+ signal: AbortSignal.timeout(timeoutMs)
5103
+ });
5104
+ } catch (err) {
5105
+ throw new GameServerError(`Can't reach the client dev server at ${this.clientUrl}: ${err.message}. Is it running?`);
5106
+ }
5107
+ const isJson = res.headers.get("content-type")?.includes("application/json");
5108
+ const body = isJson ? await res.json().catch(() => null) : null;
5109
+ if (!isJson || res.status === 404 && !body?.error) {
5110
+ throw new GameServerError(`No dev bridge at ${this.clientUrl}. The game client must be served by Vite in dev with the mavonengine Vite plugin (@mavonengine/core/vite.config). If Vite runs on its own port, pass --client-url, e.g. http://localhost:5173`);
5111
+ }
5112
+ if (res.status === 401 || res.status === 403)
5113
+ throw new GameServerError(`${body?.error ?? "Not allowed"}: pass --token or set MAVONENGINE_METRICS_TOKEN for both the CLI and the dev server`);
5114
+ if (!res.ok)
5115
+ throw new GameServerError(body?.error ?? `Client dev server responded ${res.status} ${res.statusText}`);
5116
+ return body;
5117
+ }
5118
+ async get(path, params = {}, notFound, denied) {
5119
+ const target = new URL(path, this.base);
5120
+ for (const [key, value] of Object.entries(params))
5121
+ target.searchParams.set(key, value);
5122
+ let res;
5123
+ try {
5124
+ res = await this.fetchImpl(target, {
5125
+ headers: this.token ? { Authorization: `Bearer ${this.token}` } : {},
3969
5126
  signal: AbortSignal.timeout(this.timeoutMs)
3970
5127
  });
3971
5128
  } catch (err) {
@@ -4027,8 +5184,8 @@ Options:
4027
5184
  --no-plugin-list Leave out available_plugins and plugin_readme, e.g. offline
4028
5185
  -h, --help Show this help
4029
5186
  `;
4030
- function parseMcpArgs(args, env = process9.env) {
4031
- const { values } = parseArgs6({
5187
+ function parseMcpArgs(args, env = process11.env) {
5188
+ const { values } = parseArgs8({
4032
5189
  args,
4033
5190
  options: {
4034
5191
  "host": { type: "string", default: "localhost" },
@@ -4073,18 +5230,18 @@ function parseMcpArgs(args, env = process9.env) {
4073
5230
  async function runMcpCommand({ client, docsUrl, pluginsUrl }) {
4074
5231
  const [{ StdioServerTransport }, { createMcpServer }, { DocsClient }] = await Promise.all([
4075
5232
  import("@modelcontextprotocol/sdk/server/stdio.js"),
4076
- import("./server-GC2XXFIG.js"),
4077
- import("./docs-WADOFPOK.js")
5233
+ import("./server-JSUVROT5.js"),
5234
+ import("./docs-T42UVONR.js")
4078
5235
  ]);
4079
5236
  const docs = docsUrl ? new DocsClient(docsUrl) : void 0;
4080
5237
  const server = createMcpServer(client, docs, pluginsUrl ? { url: pluginsUrl } : void 0);
4081
5238
  const transport = new StdioServerTransport();
4082
- const closed = new Promise((resolve7) => {
4083
- transport.onclose = resolve7;
4084
- process9.stdin.on("end", resolve7);
5239
+ const closed = new Promise((resolve13) => {
5240
+ transport.onclose = resolve13;
5241
+ process11.stdin.on("end", resolve13);
4085
5242
  });
4086
5243
  await server.connect(transport);
4087
- process9.stderr.write(`mavonengine mcp: reading the game server at ${client.url}
5244
+ process11.stderr.write(`mavonengine mcp: reading the game server at ${client.url}
4088
5245
  `);
4089
5246
  await closed;
4090
5247
  await server.close().catch(() => {
@@ -4094,9 +5251,9 @@ async function runMcpCommand({ client, docsUrl, pluginsUrl }) {
4094
5251
  }
4095
5252
 
4096
5253
  // src/commands/plugins.ts
4097
- import { resolve as resolve6 } from "path";
4098
- import process10 from "process";
4099
- import { parseArgs as parseArgs7 } from "util";
5254
+ import { resolve as resolve10 } from "path";
5255
+ import process12 from "process";
5256
+ import { parseArgs as parseArgs9 } from "util";
4100
5257
  var PLUGINS_HELP = `Usage: mavonengine plugins [options]
4101
5258
 
4102
5259
  List the plugins that are available to install. The list is plugins.json on the main branch
@@ -4111,8 +5268,8 @@ Options:
4111
5268
  --cwd <dir> Look for the project here (default: current directory)
4112
5269
  -h, --help Show this help
4113
5270
  `;
4114
- function parsePluginsArgs(args, cwd = process10.cwd(), env = process10.env) {
4115
- const { values, positionals } = parseArgs7({
5271
+ function parsePluginsArgs(args, cwd = process12.cwd(), env = process12.env) {
5272
+ const { values, positionals } = parseArgs9({
4116
5273
  args,
4117
5274
  options: {
4118
5275
  url: { type: "string" },
@@ -4130,7 +5287,7 @@ function parsePluginsArgs(args, cwd = process10.cwd(), env = process10.env) {
4130
5287
 
4131
5288
  ${PLUGINS_HELP}`);
4132
5289
  return {
4133
- cwd: resolve6(cwd, values.cwd ?? "."),
5290
+ cwd: resolve10(cwd, values.cwd ?? "."),
4134
5291
  url: values.url ?? env[PLUGIN_REGISTRY_ENV] ?? PLUGIN_REGISTRY_URL,
4135
5292
  json: values.json
4136
5293
  };
@@ -4147,7 +5304,7 @@ function projectPlugins(cwd) {
4147
5304
  }
4148
5305
  return states;
4149
5306
  }
4150
- var TARGETS2 = { client: "client", server: "server", both: "client + server" };
5307
+ var TARGETS3 = { client: "client", server: "server", both: "client + server" };
4151
5308
  function formatPlugins(registry, inProject) {
4152
5309
  const { plugins } = registry;
4153
5310
  const lines = [`${plugins.length} plugin${plugins.length === 1 ? "" : "s"} available, from ${registry.url}`, ""];
@@ -4157,7 +5314,7 @@ function formatPlugins(registry, inProject) {
4157
5314
  for (const plugin of plugins) {
4158
5315
  const state = inProject.get(plugin.package);
4159
5316
  const facts = [
4160
- plugin.target ? `runs on ${TARGETS2[plugin.target]}` : void 0,
5317
+ plugin.target ? `runs on ${TARGETS3[plugin.target]}` : void 0,
4161
5318
  plugin.engine ? `@mavonengine/core ${plugin.engine}` : void 0,
4162
5319
  state === "enabled" ? "in this project" : state === "disabled" ? "in this project, disabled" : void 0
4163
5320
  ].filter(Boolean);
@@ -4174,7 +5331,7 @@ function formatPlugins(registry, inProject) {
4174
5331
  return `${lines.join("\n")}
4175
5332
  `;
4176
5333
  }
4177
- async function runPluginsCommand(options, io = { write: (text) => process10.stdout.write(text) }) {
5334
+ async function runPluginsCommand(options, io = { write: (text) => process12.stdout.write(text) }) {
4178
5335
  const registry = await fetchPluginRegistry({ url: options.url, fetch: io.fetch });
4179
5336
  if (options.json) {
4180
5337
  io.write(`${JSON.stringify(registry, null, 2)}
@@ -4185,17 +5342,537 @@ async function runPluginsCommand(options, io = { write: (text) => process10.stdo
4185
5342
  return 0;
4186
5343
  }
4187
5344
 
5345
+ // src/commands/publish.ts
5346
+ import { relative as relative5, resolve as resolve11 } from "path";
5347
+ import process13 from "process";
5348
+ import { parseArgs as parseArgs10 } from "util";
5349
+
5350
+ // ../core/dist/Plugins/publish.js
5351
+ import { copyFileSync, existsSync as existsSync13, mkdirSync as mkdirSync4, readdirSync as readdirSync2, statSync } from "fs";
5352
+ import { dirname as dirname6, join as join12, relative as relative4, sep as sep2 } from "path";
5353
+ var PUBLISHED_DIR = "resources";
5354
+ function publishedDir(root, pkg) {
5355
+ return join12(root, PUBLISHED_DIR, ...pkg.split("/"));
5356
+ }
5357
+ function publishSourceDir(plugin) {
5358
+ const dir = plugin.manifest.publish;
5359
+ if (dir === void 0)
5360
+ return void 0;
5361
+ const full = resolveInside(plugin.dir, dir);
5362
+ if (!full)
5363
+ throw new PluginConfigError(`${plugin.package}: "mavonengine.publish" must be inside the package`);
5364
+ return full;
5365
+ }
5366
+ function filesIn(dir) {
5367
+ const files = [];
5368
+ for (const entry of readdirSync2(dir, { withFileTypes: true })) {
5369
+ const path = join12(dir, entry.name);
5370
+ if (entry.isDirectory())
5371
+ files.push(...filesIn(path));
5372
+ else if (entry.isFile())
5373
+ files.push(path);
5374
+ }
5375
+ return files.sort();
5376
+ }
5377
+ function publishFiles(root, plugin, { force = false } = {}) {
5378
+ const source = publishSourceDir(plugin);
5379
+ if (!source)
5380
+ throw new PluginConfigError(`${plugin.package} has no files to publish`);
5381
+ if (!existsSync13(source) || !statSync(source).isDirectory())
5382
+ throw new PluginConfigError(`${plugin.package}: its publish directory ${relative4(plugin.dir, source)} is missing`);
5383
+ const target = publishedDir(root, plugin.package);
5384
+ return filesIn(source).map((from) => {
5385
+ const path = relative4(source, from).split(sep2).join("/");
5386
+ const to = join12(target, ...path.split("/"));
5387
+ const existed = existsSync13(to);
5388
+ if (existed && !force)
5389
+ return { path, to, status: "kept" };
5390
+ mkdirSync4(dirname6(to), { recursive: true });
5391
+ copyFileSync(from, to);
5392
+ return { path, to, status: existed ? "replaced" : "published" };
5393
+ });
5394
+ }
5395
+
5396
+ // src/commands/publish.ts
5397
+ var PUBLISH_HELP = `Usage: mavonengine asset:publish <package...> [options]
5398
+
5399
+ Copy the files a plugin lets you change, like the mail plugin's layout, into the project's
5400
+ ${PUBLISHED_DIR}/<package>/. The plugin uses your copy from then on, so change it there.
5401
+
5402
+ Files you have already are kept, so publishing again only adds the plugin's new files.
5403
+
5404
+ Options:
5405
+ --force Replace the files you have with the plugin's
5406
+ --cwd <dir> Start looking for the project here (default: current directory)
5407
+ -h, --help Show this help
5408
+ `;
5409
+ function parsePublishArgs(args, cwd = process13.cwd()) {
5410
+ const { values, positionals } = parseArgs10({
5411
+ args,
5412
+ options: {
5413
+ force: { type: "boolean", default: false },
5414
+ cwd: { type: "string" },
5415
+ help: { type: "boolean", short: "h", default: false }
5416
+ },
5417
+ strict: true,
5418
+ allowPositionals: true
5419
+ });
5420
+ if (values.help)
5421
+ return "help";
5422
+ if (positionals.length === 0)
5423
+ throw new UsageError(`name the plugin to publish, e.g. mavonengine asset:publish @mavonengine/mail
5424
+
5425
+ ${PUBLISH_HELP}`);
5426
+ return { cwd: resolve11(cwd, values.cwd ?? "."), packages: positionals, force: values.force };
5427
+ }
5428
+ async function runPublishCommand(options, io = { write: (text) => void process13.stdout.write(text) }) {
5429
+ const root = findProjectRoot(options.cwd);
5430
+ if (!root) {
5431
+ io.write(`No MavonEngine project found from ${options.cwd}. Run this inside one.
5432
+ `);
5433
+ return 1;
5434
+ }
5435
+ let failed = false;
5436
+ for (const pkg of options.packages) {
5437
+ const plugin = (() => {
5438
+ try {
5439
+ return readPluginManifest(root, pkg);
5440
+ } catch (err) {
5441
+ io.write(`${pkg}: ${err.message}
5442
+ `);
5443
+ return null;
5444
+ }
5445
+ })();
5446
+ if (plugin === null) {
5447
+ failed = true;
5448
+ continue;
5449
+ }
5450
+ if (!plugin) {
5451
+ io.write(`${pkg} isn't installed, or is no MavonEngine plugin. Install it with: mavonengine install ${pkg}
5452
+ `);
5453
+ failed = true;
5454
+ continue;
5455
+ }
5456
+ try {
5457
+ const files = publishFiles(root, plugin, { force: options.force });
5458
+ io.write(`${pkg}:
5459
+ `);
5460
+ for (const file of files) {
5461
+ const shown = relative5(root, file.to).split("\\").join("/");
5462
+ io.write(file.status === "kept" ? ` kept ${shown} (you have it already, --force replaces it)
5463
+ ` : ` ${file.status.padEnd(10)} ${shown}
5464
+ `);
5465
+ }
5466
+ if (files.length === 0)
5467
+ io.write(" nothing to publish\n");
5468
+ } catch (err) {
5469
+ if (!(err instanceof PluginConfigError))
5470
+ throw err;
5471
+ io.write(`${err.message}
5472
+ `);
5473
+ failed = true;
5474
+ }
5475
+ }
5476
+ return failed ? 1 : 0;
5477
+ }
5478
+
5479
+ // src/commands/upgrade.ts
5480
+ import { execFileSync as execFileSync2 } from "child_process";
5481
+ import { readFileSync as readFileSync11 } from "fs";
5482
+ import { join as join14, resolve as resolve12 } from "path";
5483
+ import process14 from "process";
5484
+ import { createInterface as createInterface3 } from "readline/promises";
5485
+ import { parseArgs as parseArgs11 } from "util";
5486
+
5487
+ // src/upgrade/diff.ts
5488
+ var NEWLINE_RE2 = /\r?\n/;
5489
+ function lineDiff(before, after, context = 2) {
5490
+ const a = before === void 0 ? [] : splitLines(before);
5491
+ const b = splitLines(after);
5492
+ const lcs = Array.from({ length: a.length + 1 }, () => Array.from({ length: b.length + 1 }).fill(0));
5493
+ for (let i2 = a.length - 1; i2 >= 0; i2--) {
5494
+ for (let j2 = b.length - 1; j2 >= 0; j2--)
5495
+ lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);
5496
+ }
5497
+ const ops = [];
5498
+ let i = 0;
5499
+ let j = 0;
5500
+ while (i < a.length || j < b.length) {
5501
+ if (i < a.length && j < b.length && a[i] === b[j]) {
5502
+ ops.push({ kind: " ", line: a[i++] });
5503
+ j++;
5504
+ } else if (i < a.length && (j === b.length || lcs[i + 1][j] >= lcs[i][j + 1])) {
5505
+ ops.push({ kind: "-", line: a[i++] });
5506
+ } else {
5507
+ ops.push({ kind: "+", line: b[j++] });
5508
+ }
5509
+ }
5510
+ const near = ops.map((_, index) => ops.slice(Math.max(0, index - context), index + context + 1).some((op) => op.kind !== " "));
5511
+ const lines = [];
5512
+ ops.forEach((op, index) => {
5513
+ if (near[index])
5514
+ lines.push(`${op.kind} ${op.line}`.trimEnd());
5515
+ else if (near[index - 1] || index === 0 && ops.length > 1)
5516
+ lines.push(" \u2026");
5517
+ });
5518
+ return lines;
5519
+ }
5520
+ function splitLines(text) {
5521
+ const lines = text.split(NEWLINE_RE2);
5522
+ if (lines.at(-1) === "")
5523
+ lines.pop();
5524
+ return lines;
5525
+ }
5526
+
5527
+ // src/upgrade/plan.ts
5528
+ import { existsSync as existsSync14, readFileSync as readFileSync10 } from "fs";
5529
+ import { join as join13 } from "path";
5530
+ var UpgradeError = class extends Error {
5531
+ };
5532
+ var EXACT_RE = /^v?\d+\.\d+\.\d+(?:-[\w.-]+)?$/;
5533
+ var REGISTRY_SPEC_RE = /^[\s\d.<>=^~xX*|v-]*$/;
5534
+ function installedJson(root, name) {
5535
+ const dir = findPackageDir(root, name);
5536
+ const path = dir && join13(dir, "package.json");
5537
+ if (!path || !existsSync14(path))
5538
+ return void 0;
5539
+ try {
5540
+ return JSON.parse(readFileSync10(path, "utf8"));
5541
+ } catch {
5542
+ return void 0;
5543
+ }
5544
+ }
5545
+ function stable(versions) {
5546
+ return versions.filter((version3) => parseVersion(version3)?.prerelease.length === 0);
5547
+ }
5548
+ function newer(a, than) {
5549
+ const x = a && parseVersion(a);
5550
+ const y = than && parseVersion(than);
5551
+ return !!x && (!y || compareVersions(x, y) > 0);
5552
+ }
5553
+ function newestFitting(packument, fits) {
5554
+ const versions = stable(Object.keys(packument.versions)).filter((version3) => fits(packument.versions[version3]));
5555
+ return maxSatisfying(versions, "*");
5556
+ }
5557
+ async function planUpgrade(root, packageJson, npm, to) {
5558
+ const corePackument = await npm.get("@mavonengine/core");
5559
+ if (!corePackument)
5560
+ throw new UpgradeError(npm.unreachable ?? `${npm.url} doesn't know @mavonengine/core`);
5561
+ const target = to ?? corePackument.latest;
5562
+ if (!target || !corePackument.versions[target])
5563
+ throw new UpgradeError(to ? `@mavonengine/core ${to} isn't published, see 'npm view @mavonengine/core versions'` : `${npm.url} has no latest @mavonengine/core`);
5564
+ const fields = ["dependencies", "devDependencies"];
5565
+ const declared = fields.flatMap((field) => Object.entries(packageJson[field] ?? {}).map(([name, spec]) => ({ name, spec: String(spec), field })));
5566
+ const candidates = declared.filter(({ name }) => name.startsWith("@mavonengine/") || installedJson(root, name)?.mavonengine);
5567
+ const packuments = new Map(await Promise.all(candidates.map(async ({ name }) => [name, name === "@mavonengine/core" ? corePackument : await npm.get(name)])));
5568
+ if (npm.unreachable)
5569
+ throw new UpgradeError(npm.unreachable);
5570
+ const bumps = candidates.map(({ name, spec, field }) => {
5571
+ const json2 = installedJson(root, name);
5572
+ const installed = typeof json2?.version === "string" ? json2.version : void 0;
5573
+ const plugin = !!json2?.mavonengine || !!packuments.get(name)?.versions[packuments.get(name)?.latest ?? ""]?.mavonengine;
5574
+ const bump = { name, field, spec, installed, plugin, exact: EXACT_RE.test(spec.trim()) };
5575
+ if (!REGISTRY_SPEC_RE.test(spec) || !spec.trim())
5576
+ return { ...bump, note: `stays: ${spec} isn't from the registry` };
5577
+ const packument = packuments.get(name);
5578
+ if (!packument)
5579
+ return { ...bump, note: "stays: not on the registry" };
5580
+ let version3;
5581
+ if (name === "@mavonengine/core") {
5582
+ version3 = target;
5583
+ } else if (plugin) {
5584
+ version3 = newestFitting(packument, (v) => {
5585
+ const range = engineRangeOf(v);
5586
+ return !range || validRange(range) && satisfies(target, range);
5587
+ });
5588
+ if (!version3)
5589
+ return { ...bump, blocked: true, note: `no published version supports @mavonengine/core ${target}` };
5590
+ } else {
5591
+ version3 = newestFitting(packument, (v) => {
5592
+ const range = v.peerDependencies?.["@mavonengine/core"];
5593
+ return typeof range !== "string" || !validRange(range) || satisfies(target, range);
5594
+ });
5595
+ }
5596
+ if (!version3 || version3 === installed || name !== "@mavonengine/core" && !newer(version3, installed))
5597
+ return bump;
5598
+ return { ...bump, to: version3 };
5599
+ });
5600
+ return { core: { from: installedJson(root, "@mavonengine/core")?.version, to: target }, bumps };
5601
+ }
5602
+ var DEV_FLAG = { npm: "--save-dev", pnpm: "--save-dev", yarn: "--dev", bun: "--dev" };
5603
+ var EXACT_FLAG = { npm: "--save-exact", pnpm: "--save-exact", yarn: "--exact", bun: "--exact" };
5604
+ function installCommands(pm, bumps) {
5605
+ const groups = /* @__PURE__ */ new Map();
5606
+ for (const bump of bumps) {
5607
+ if (!bump.to)
5608
+ continue;
5609
+ const key = `${bump.field}:${bump.exact}`;
5610
+ if (!groups.has(key))
5611
+ groups.set(key, { field: bump.field, exact: bump.exact, specs: [] });
5612
+ groups.get(key).specs.push(`${bump.name}@${bump.to}`);
5613
+ }
5614
+ return Array.from(groups.values(), ({ field, exact, specs }) => [
5615
+ pm === "npm" ? "install" : "add",
5616
+ ...specs,
5617
+ ...field === "devDependencies" ? [DEV_FLAG[pm]] : [],
5618
+ ...exact ? [EXACT_FLAG[pm]] : []
5619
+ ]);
5620
+ }
5621
+
5622
+ // src/commands/upgrade.ts
5623
+ var UPGRADE_HELP = `Usage: mavonengine upgrade [options]
5624
+
5625
+ Move the MavonEngine project you are in to the latest @mavonengine/core, then migrate it.
5626
+
5627
+ 1. Packages: @mavonengine/core goes to its latest version (or --to), each plugin to its
5628
+ newest version whose "engine" range takes that core, the other @mavonengine packages
5629
+ to their newest. Versions come from the npm registry. A plugin with no version for
5630
+ that core stops the upgrade, unless --force.
5631
+ 2. Migrations: the changes the new core needs in the project's files, from the installed
5632
+ core. Each is shown as a diff first and recorded in ${CONFIG_FILE} once applied.
5633
+ 3. 'mavonengine doctor' on the result.
5634
+
5635
+ Asks before installing and before writing. Refuses to start with uncommitted changes in
5636
+ git, so every change can be looked at and undone.
5637
+
5638
+ Options:
5639
+ --to <version> Move @mavonengine/core to this version instead of the latest
5640
+ --only-migrations Leave the packages alone, only migrate (after installing yourself)
5641
+ --dry-run Show what would happen, change nothing
5642
+ -y, --yes Don't ask
5643
+ --force Upgrade even when a plugin has no version for the new core
5644
+ --allow-dirty Start with uncommitted changes
5645
+ --cwd <dir> Start looking for the project here (default: current directory)
5646
+ -h, --help Show this help
5647
+ `;
5648
+ function parseUpgradeArgs(args, cwd = process14.cwd(), env = process14.env) {
5649
+ const { values, positionals } = parseArgs11({
5650
+ args,
5651
+ options: {
5652
+ "to": { type: "string" },
5653
+ "only-migrations": { type: "boolean", default: false },
5654
+ "dry-run": { type: "boolean", default: false },
5655
+ "yes": { type: "boolean", short: "y", default: false },
5656
+ "force": { type: "boolean", default: false },
5657
+ "allow-dirty": { type: "boolean", default: false },
5658
+ "cwd": { type: "string" },
5659
+ "help": { type: "boolean", short: "h", default: false }
5660
+ },
5661
+ strict: true,
5662
+ allowPositionals: true
5663
+ });
5664
+ if (values.help)
5665
+ return "help";
5666
+ if (positionals.length > 0)
5667
+ throw new UsageError(`unexpected argument '${positionals[0]}'
5668
+
5669
+ ${UPGRADE_HELP}`);
5670
+ if (values.to !== void 0 && !parseVersion(values.to))
5671
+ throw new UsageError(`--to takes a version like 0.0.26, not '${values.to}'`);
5672
+ if (values.to !== void 0 && values["only-migrations"])
5673
+ throw new UsageError("--to and --only-migrations don't go together: --only-migrations leaves the packages alone");
5674
+ return {
5675
+ cwd: resolve12(cwd, values.cwd ?? "."),
5676
+ to: values.to,
5677
+ onlyMigrations: values["only-migrations"],
5678
+ dryRun: values["dry-run"],
5679
+ yes: values.yes,
5680
+ force: values.force,
5681
+ allowDirty: values["allow-dirty"],
5682
+ registry: env.npm_config_registry || NPM_REGISTRY_URL
5683
+ };
5684
+ }
5685
+ function gitStatus(cwd) {
5686
+ try {
5687
+ return execFileSync2("git", ["status", "--porcelain"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
5688
+ } catch {
5689
+ return void 0;
5690
+ }
5691
+ }
5692
+ function confirmOnTerminal2(question) {
5693
+ const rl = createInterface3({ input: process14.stdin, output: process14.stdout });
5694
+ return rl.question(question).then((answer) => ["", "y", "yes"].includes(answer.trim().toLowerCase())).finally(() => rl.close());
5695
+ }
5696
+ var terminalIO3 = {
5697
+ run: (command, args, cwd) => runCommand(command, args, cwd, {
5698
+ report: { step: () => {
5699
+ }, output: (chunk) => process14.stdout.write(chunk) }
5700
+ }),
5701
+ confirm: confirmOnTerminal2,
5702
+ get interactive() {
5703
+ return !!process14.stdin.isTTY && !!process14.stdout.isTTY;
5704
+ },
5705
+ write: (text) => void process14.stdout.write(text),
5706
+ gitStatus,
5707
+ color: !!process14.stdout.isTTY && !process14.env.NO_COLOR
5708
+ };
5709
+ function formatPlan(plan) {
5710
+ const width = Math.max(...plan.bumps.map((bump) => bump.name.length));
5711
+ const from = Math.max(...plan.bumps.map((bump) => (bump.installed ?? "-").length));
5712
+ const line = (bump) => {
5713
+ const head = ` ${bump.blocked ? "\u2717" : bump.to ? "\u2191" : "\xB7"} ${bump.name.padEnd(width)} ${(bump.installed ?? "-").padEnd(from)}`;
5714
+ if (bump.blocked)
5715
+ return `${head} ${bump.note}`;
5716
+ if (bump.to)
5717
+ return `${head} \u2192 ${bump.to}`;
5718
+ return `${head} ${bump.note ?? "stays"}`;
5719
+ };
5720
+ return `Packages, for @mavonengine/core ${plan.core.to}
5721
+ ${plan.bumps.map(line).join("\n")}
5722
+ `;
5723
+ }
5724
+ async function ask(io, options, question, action) {
5725
+ if (options.yes)
5726
+ return true;
5727
+ if (!io.interactive) {
5728
+ io.write(`
5729
+ Nothing ${action === "install" ? "installed" : "written"}: there is no terminal to ask on, run with --yes to ${action}
5730
+ `);
5731
+ return false;
5732
+ }
5733
+ return io.confirm(`
5734
+ ${question} (Y/n) `);
5735
+ }
5736
+ async function runUpgradeCommand(options, io = terminalIO3) {
5737
+ const root = findProjectRoot(options.cwd);
5738
+ if (!root)
5739
+ throw new UsageError(`no MavonEngine project found in ${options.cwd} or its parents (looking for a package.json with @mavonengine/core and a dev script)`);
5740
+ const pm = detectPackageManager(root);
5741
+ const npm = new NpmRegistry({ url: options.registry, fetch: io.fetch });
5742
+ const readPackageJson2 = () => JSON.parse(readFileSync11(join14(root, "package.json"), "utf8"));
5743
+ io.write(`mavonengine upgrade in ${root} (${pm}${options.dryRun ? ", dry run" : ""})
5744
+
5745
+ `);
5746
+ if (!options.dryRun && !options.allowDirty) {
5747
+ const status = (io.gitStatus ?? gitStatus)(root);
5748
+ if (status?.trim()) {
5749
+ io.write(`There are uncommitted changes:
5750
+ ${status.trimEnd().split("\n").map((line) => ` ${line}`).join("\n")}
5751
+
5752
+ Commit or stash them first, so the upgrade's changes can be looked at on their own, or pass --allow-dirty
5753
+ `);
5754
+ return 1;
5755
+ }
5756
+ }
5757
+ if (!options.onlyMigrations) {
5758
+ let plan;
5759
+ try {
5760
+ plan = await planUpgrade(root, readPackageJson2(), npm, options.to);
5761
+ } catch (err) {
5762
+ if (err instanceof UpgradeError) {
5763
+ io.write(`Can't plan the upgrade: ${err.message}
5764
+ `);
5765
+ return 1;
5766
+ }
5767
+ throw err;
5768
+ }
5769
+ io.write(formatPlan(plan));
5770
+ const blocked = plan.bumps.filter((bump) => bump.blocked);
5771
+ if (blocked.length && !options.force) {
5772
+ io.write(`
5773
+ ${blocked.map((bump) => bump.name).join(", ")} would stop working: no version of ${blocked.length === 1 ? "it" : "them"} supports @mavonengine/core ${plan.core.to}. Pick an older core with --to, remove ${blocked.length === 1 ? "it" : "them"}, or pass --force to upgrade anyway
5774
+ `);
5775
+ return 1;
5776
+ }
5777
+ const commands = installCommands(pm, plan.bumps);
5778
+ if (!commands.length) {
5779
+ io.write("\nThe packages are up to date\n");
5780
+ } else {
5781
+ const shown = commands.map((args) => `${pm} ${args.join(" ")}`).join("\n ");
5782
+ if (options.dryRun) {
5783
+ io.write(`
5784
+ Would run:
5785
+ ${shown}
5786
+ `);
5787
+ } else {
5788
+ if (!await ask(io, options, `Install them with:
5789
+ ${shown}
5790
+ ?`, "install"))
5791
+ return 1;
5792
+ for (const args of commands) {
5793
+ io.write(`
5794
+ mavonengine: running '${pm} ${args.join(" ")}'
5795
+ `);
5796
+ await io.run(pm, args, root);
5797
+ }
5798
+ }
5799
+ }
5800
+ }
5801
+ const coreVersion = coreVersionOf(root);
5802
+ if (!coreVersion) {
5803
+ io.write(`
5804
+ @mavonengine/core isn't installed, so there is nothing to migrate: run '${pm} install' first
5805
+ `);
5806
+ return 1;
5807
+ }
5808
+ const { module, from } = await loadMigrations(root);
5809
+ const ctx = { files: new module.ProjectFiles(root), versions: { core: coreVersion, cli: version } };
5810
+ const pending = module.pendingMigrations(ctx);
5811
+ const dryRunNote = options.dryRun && !options.onlyMigrations ? ", for the core installed now; the new core may bring more" : "";
5812
+ io.write(`
5813
+ Migrations, for @mavonengine/core ${coreVersion}${from === "cli" ? " (from the CLI: the installed core has none of its own)" : ""}${dryRunNote}
5814
+ `);
5815
+ let migrated = false;
5816
+ if (!pending.length) {
5817
+ io.write(" none pending\n");
5818
+ } else {
5819
+ const changes = module.applyMigrations(ctx, pending);
5820
+ const width = Math.max(...pending.map((migration) => migration.id.length));
5821
+ for (const migration of pending)
5822
+ io.write(` ${migration.id.padEnd(width)} ${migration.description}
5823
+ `);
5824
+ for (const change of changes) {
5825
+ io.write(`
5826
+ ${change.before === void 0 ? "new " : ""}${change.path}
5827
+ `);
5828
+ io.write(`${lineDiff(change.before, change.after).map((line) => ` ${line}`).join("\n")}
5829
+ `);
5830
+ }
5831
+ if (options.dryRun) {
5832
+ io.write("\nNothing written (--dry-run)\n");
5833
+ return 0;
5834
+ }
5835
+ if (!await ask(io, options, `Write ${changes.length === 1 ? "this change" : `these ${changes.length} changes`}?`, "write the changes"))
5836
+ return 1;
5837
+ const before = JSON.stringify(readPackageJson2());
5838
+ ctx.files.commit();
5839
+ migrated = true;
5840
+ io.write(`
5841
+ mavonengine: migrated ${pending.length === 1 ? "1 migration" : `${pending.length} migrations`}, recorded in ${CONFIG_FILE}
5842
+ `);
5843
+ if (JSON.stringify(readPackageJson2()) !== before) {
5844
+ io.write(`
5845
+ mavonengine: package.json changed, running '${pm} install'
5846
+ `);
5847
+ await io.run(pm, ["install"], root);
5848
+ }
5849
+ }
5850
+ if (options.dryRun)
5851
+ return 0;
5852
+ io.write(`
5853
+ ${migrated ? "Checking the result" : "Checking the project"}: mavonengine doctor
5854
+
5855
+ `);
5856
+ const report = await runDoctor(root, { offline: false, registry: options.registry }, { fetch: io.fetch });
5857
+ io.write(formatReport(report, { color: io.color }));
5858
+ return report.errors ? 1 : 0;
5859
+ }
5860
+
4188
5861
  // src/index.ts
4189
5862
  var HELP = `Usage: mavonengine <command> [options]
4190
5863
 
4191
5864
  Commands:
4192
- create Create a project from the multiplayer template and start it
4193
- dashboard Live terminal dashboard for a running game server
4194
- dev Run the project's dev servers (game server and client)
4195
- install Install packages and register engine plugins in mavonengine.json
4196
- plugins List the plugins that are available to install
4197
- build Build the project for release, with the plugin assets it uses
4198
- mcp MCP server so AI assistants (any MCP client) can inspect a running game server
5865
+ create Create a project from the multiplayer template and start it
5866
+ dashboard Live terminal dashboard for a running game server
5867
+ dev Run the project's dev servers (game server and client)
5868
+ install Install packages and register engine plugins in mavonengine.json
5869
+ plugins List the plugins that are available to install
5870
+ asset:publish Copy a plugin's files you may change, like the mail layout, into the project
5871
+ make:plugin Create a plugin inside the project, linked and registered in mavonengine.json
5872
+ build Build the project for release, with the plugin assets it uses
5873
+ doctor Check Node, the @mavonengine packages, mavonengine.json and the plugins
5874
+ upgrade Move to the latest @mavonengine/core and plugins that fit it, then migrate the project
5875
+ mcp MCP server so AI assistants (any MCP client) can inspect a running game server
4199
5876
 
4200
5877
  Options:
4201
5878
  -h, --help Show help
@@ -4206,18 +5883,18 @@ Run 'mavonengine <command> --help' for command options.
4206
5883
  async function main(argv) {
4207
5884
  const [command, ...args] = argv;
4208
5885
  if (!command || command === "-h" || command === "--help" || command === "help") {
4209
- process11.stdout.write(HELP);
5886
+ process15.stdout.write(HELP);
4210
5887
  return 0;
4211
5888
  }
4212
5889
  if (command === "-v" || command === "--version") {
4213
- process11.stdout.write(`${version}
5890
+ process15.stdout.write(`${version}
4214
5891
  `);
4215
5892
  return 0;
4216
5893
  }
4217
5894
  if (command === "create") {
4218
5895
  const options = parseCreateArgs(args);
4219
5896
  if (options === "help") {
4220
- process11.stdout.write(CREATE_HELP);
5897
+ process15.stdout.write(CREATE_HELP);
4221
5898
  return 0;
4222
5899
  }
4223
5900
  return runCreateCommand(options);
@@ -4225,11 +5902,11 @@ async function main(argv) {
4225
5902
  if (command === "dashboard") {
4226
5903
  const options = parseDashboardArgs(args);
4227
5904
  if (options === "help") {
4228
- process11.stdout.write(DASHBOARD_HELP);
5905
+ process15.stdout.write(DASHBOARD_HELP);
4229
5906
  return 0;
4230
5907
  }
4231
- if (!process11.stdout.isTTY || !process11.stdin.isTTY) {
4232
- process11.stderr.write("mavonengine dashboard needs an interactive terminal\n");
5908
+ if (!process15.stdout.isTTY || !process15.stdin.isTTY) {
5909
+ process15.stderr.write("mavonengine dashboard needs an interactive terminal\n");
4233
5910
  return 1;
4234
5911
  }
4235
5912
  await runDashboard(options);
@@ -4238,7 +5915,7 @@ async function main(argv) {
4238
5915
  if (command === "dev") {
4239
5916
  const options = parseDevArgs(args);
4240
5917
  if (options === "help") {
4241
- process11.stdout.write(DEV_HELP);
5918
+ process15.stdout.write(DEV_HELP);
4242
5919
  return 0;
4243
5920
  }
4244
5921
  return runDevCommand(options);
@@ -4246,7 +5923,7 @@ async function main(argv) {
4246
5923
  if (command === "install" || command === "i" || command === "add") {
4247
5924
  const options = parseInstallArgs(args);
4248
5925
  if (options === "help") {
4249
- process11.stdout.write(INSTALL_HELP);
5926
+ process15.stdout.write(INSTALL_HELP);
4250
5927
  return 0;
4251
5928
  }
4252
5929
  return runInstallCommand(options);
@@ -4254,23 +5931,55 @@ async function main(argv) {
4254
5931
  if (command === "plugins") {
4255
5932
  const options = parsePluginsArgs(args);
4256
5933
  if (options === "help") {
4257
- process11.stdout.write(PLUGINS_HELP);
5934
+ process15.stdout.write(PLUGINS_HELP);
4258
5935
  return 0;
4259
5936
  }
4260
5937
  return runPluginsCommand(options);
4261
5938
  }
5939
+ if (command === "asset:publish") {
5940
+ const options = parsePublishArgs(args);
5941
+ if (options === "help") {
5942
+ process15.stdout.write(PUBLISH_HELP);
5943
+ return 0;
5944
+ }
5945
+ return runPublishCommand(options);
5946
+ }
5947
+ if (command === "make:plugin") {
5948
+ const options = parseMakePluginArgs(args);
5949
+ if (options === "help") {
5950
+ process15.stdout.write(MAKE_PLUGIN_HELP);
5951
+ return 0;
5952
+ }
5953
+ return runMakePluginCommand(options);
5954
+ }
4262
5955
  if (command === "mcp") {
4263
5956
  const options = parseMcpArgs(args);
4264
5957
  if (options === "help") {
4265
- process11.stdout.write(MCP_HELP);
5958
+ process15.stdout.write(MCP_HELP);
4266
5959
  return 0;
4267
5960
  }
4268
5961
  return runMcpCommand(options);
4269
5962
  }
5963
+ if (command === "doctor") {
5964
+ const options = parseDoctorArgs(args);
5965
+ if (options === "help") {
5966
+ process15.stdout.write(DOCTOR_HELP);
5967
+ return 0;
5968
+ }
5969
+ return runDoctorCommand(options);
5970
+ }
5971
+ if (command === "upgrade") {
5972
+ const options = parseUpgradeArgs(args);
5973
+ if (options === "help") {
5974
+ process15.stdout.write(UPGRADE_HELP);
5975
+ return 0;
5976
+ }
5977
+ return runUpgradeCommand(options);
5978
+ }
4270
5979
  if (command === "build") {
4271
5980
  const options = parseBuildArgs(args);
4272
5981
  if (options === "help") {
4273
- process11.stdout.write(BUILD_HELP);
5982
+ process15.stdout.write(BUILD_HELP);
4274
5983
  return 0;
4275
5984
  }
4276
5985
  return runBuildCommand(options);
@@ -4279,9 +5988,9 @@ async function main(argv) {
4279
5988
 
4280
5989
  ${HELP}`);
4281
5990
  }
4282
- main(process11.argv.slice(2)).then((code) => process11.exit(code)).catch((err) => {
5991
+ main(process15.argv.slice(2)).then((code) => process15.exit(code)).catch((err) => {
4283
5992
  const isUsage = err instanceof UsageError || err.code?.startsWith("ERR_PARSE_ARGS");
4284
- process11.stderr.write(`mavonengine: ${err.message}
5993
+ process15.stderr.write(`mavonengine: ${err.message}
4285
5994
  `);
4286
- process11.exit(isUsage ? 2 : 1);
5995
+ process15.exit(isUsage ? 2 : 1);
4287
5996
  });