@mizius/minecraft 0.0.0-stage → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +159 -3
- package/artifacts/minecraft-control-1.21.10.jar +0 -0
- package/artifacts/minecraft-control-1.21.11.jar +0 -0
- package/artifacts/minecraft-control-1.21.4.jar +0 -0
- package/artifacts/minecraft-control-1.21.5.jar +0 -0
- package/artifacts/minecraft-control-1.21.6.jar +0 -0
- package/artifacts/minecraft-control-1.21.7.jar +0 -0
- package/artifacts/minecraft-control-1.21.8.jar +0 -0
- package/artifacts/minecraft-control-1.21.9.jar +0 -0
- package/artifacts/minecraft-control-26.1.1.jar +0 -0
- package/artifacts/minecraft-control-26.1.2.jar +0 -0
- package/artifacts/minecraft-control-26.1.jar +0 -0
- package/artifacts/minecraft-control-26.2.jar +0 -0
- package/artifacts/minecraft-control-26.3.jar +0 -0
- package/compatibility.json +109 -0
- package/dist/core.js +70 -0
- package/dist/download.js +99 -0
- package/dist/index.js +302 -0
- package/dist/install.js +360 -0
- package/dist/launch.js +165 -0
- package/dist/process.js +149 -0
- package/dist/update.js +376 -0
- package/package.json +40 -4
- package/skills/minecraft/SKILL.md +64 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { parseArgs } from 'node:util';
|
|
6
|
+
import { access, copyFile, mkdir, writeFile } from 'node:fs/promises';
|
|
7
|
+
import { readManifest } from './core.js';
|
|
8
|
+
import { command as controlCommand, controlReady, controlUrl, launch, stop, validateControlPort } from './launch.js';
|
|
9
|
+
import { acquireLock, running } from './process.js';
|
|
10
|
+
import { attemptAutomaticUpdate, relaunchCli, updateCli } from './update.js';
|
|
11
|
+
function describe(record) {
|
|
12
|
+
return { pid: record.identity.pid, version: record.version, instance: record.instance, log: record.log, port: record.port };
|
|
13
|
+
}
|
|
14
|
+
const packageRoot = fileURLToPath(new URL('../', import.meta.url));
|
|
15
|
+
const help = `Minecraft command line
|
|
16
|
+
|
|
17
|
+
minecraft versions [--json]
|
|
18
|
+
minecraft update [--json]
|
|
19
|
+
minecraft launch [version] [--username Agent] [--port 8765] [--foreground] [--json]
|
|
20
|
+
minecraft status [--json]
|
|
21
|
+
minecraft stop [--json]
|
|
22
|
+
minecraft control state [--json]
|
|
23
|
+
minecraft control screenshot [--output <file>] [--json]
|
|
24
|
+
minecraft control record start [--fps 10] [--json]
|
|
25
|
+
minecraft control record stop [--json]
|
|
26
|
+
minecraft control join <server-address> [--json]
|
|
27
|
+
minecraft control click <x> <y> [--button left|right|middle] [--action press|hold|release] [--json]
|
|
28
|
+
minecraft control move <x> <y> [--json]
|
|
29
|
+
minecraft control drag <x1> <y1> <x2> <y2> [--button left|right|middle] [--duration-ms 250] [--json]
|
|
30
|
+
minecraft control scroll <amount> [--json]
|
|
31
|
+
minecraft control key <key-name-or-code> [--action press|hold|release] [--json]
|
|
32
|
+
minecraft control type <text> [--json]
|
|
33
|
+
minecraft control execute <command> [--json]
|
|
34
|
+
minecraft control logs [query] [--limit 100] [--json]
|
|
35
|
+
minecraft control batch <json-array> [--json]
|
|
36
|
+
minecraft skill path
|
|
37
|
+
minecraft skill install --dir <skills-directory>
|
|
38
|
+
|
|
39
|
+
The managed client requires Windows or Linux x64. The command endpoint runs inside the game client.
|
|
40
|
+
Use mizius_minecraft_home to select a different managed directory.
|
|
41
|
+
`;
|
|
42
|
+
function integer(value, label) {
|
|
43
|
+
const parsed = Number(value);
|
|
44
|
+
if (value === undefined || !Number.isInteger(parsed))
|
|
45
|
+
throw new Error(`${label} must be an integer.`);
|
|
46
|
+
return parsed;
|
|
47
|
+
}
|
|
48
|
+
function coordinate(value, label) {
|
|
49
|
+
const parsed = Number(value);
|
|
50
|
+
if (value === undefined || !Number.isFinite(parsed))
|
|
51
|
+
throw new Error(`${label} must be a number.`);
|
|
52
|
+
return parsed;
|
|
53
|
+
}
|
|
54
|
+
function requireClientPlatform() {
|
|
55
|
+
if (!['win32', 'linux'].includes(process.platform) || process.arch !== 'x64')
|
|
56
|
+
throw new Error('Managed Minecraft currently requires Windows or Linux x64.');
|
|
57
|
+
}
|
|
58
|
+
function managedRoot() {
|
|
59
|
+
const base = process.env.mizius_minecraft_home ?? (process.platform === 'linux'
|
|
60
|
+
? path.join(process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share'), 'mizius', 'Minecraft')
|
|
61
|
+
: process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'mizius', 'Minecraft'));
|
|
62
|
+
if (!base)
|
|
63
|
+
throw new Error('LOCALAPPDATA is unavailable. Set mizius_minecraft_home to a managed directory.');
|
|
64
|
+
return path.resolve(base);
|
|
65
|
+
}
|
|
66
|
+
async function sendCommand(root, name, args = {}) {
|
|
67
|
+
requireClientPlatform();
|
|
68
|
+
const record = await running(root);
|
|
69
|
+
if (!record)
|
|
70
|
+
throw new Error('Minecraft is not running. Run minecraft launch first.');
|
|
71
|
+
const url = controlUrl(record.port);
|
|
72
|
+
await controlReady(url);
|
|
73
|
+
const timeoutMs = name === 'screenshot' ? 30_000 : name === 'record' ? 125_000 : 35_000;
|
|
74
|
+
return controlCommand(name, args, url, timeoutMs);
|
|
75
|
+
}
|
|
76
|
+
async function main() {
|
|
77
|
+
const { positionals, values } = parseArgs({ allowPositionals: true, strict: true, options: {
|
|
78
|
+
json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
|
|
79
|
+
username: { type: 'string' }, dir: { type: 'string' }, port: { type: 'string' }, foreground: { type: 'boolean' },
|
|
80
|
+
output: { type: 'string' }, button: { type: 'string' }, action: { type: 'string' },
|
|
81
|
+
'duration-ms': { type: 'string' }, limit: { type: 'string' }, fps: { type: 'string' },
|
|
82
|
+
} });
|
|
83
|
+
if (values.help || positionals.length === 0) {
|
|
84
|
+
console.log(help);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const [topLevel, second, ...remaining] = positionals;
|
|
88
|
+
const isControl = topLevel === 'control';
|
|
89
|
+
const commandName = isControl ? second : topLevel;
|
|
90
|
+
const argument = isControl ? remaining[0] : second;
|
|
91
|
+
const rest = isControl ? remaining.slice(1) : remaining;
|
|
92
|
+
const output = (value) => console.log(JSON.stringify(value, null, values.json ? undefined : 2));
|
|
93
|
+
if (commandName === 'skill') {
|
|
94
|
+
if (positionals.length !== 2)
|
|
95
|
+
throw new Error('Use minecraft skill path or minecraft skill install --dir <skills-directory>.');
|
|
96
|
+
const source = path.join(packageRoot, 'skills', 'minecraft', 'SKILL.md');
|
|
97
|
+
if (argument === 'path') {
|
|
98
|
+
console.log(path.dirname(source));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (argument !== 'install' || !values.dir)
|
|
102
|
+
throw new Error('Use minecraft skill install --dir <skills-directory>.');
|
|
103
|
+
const directory = path.resolve(values.dir, 'minecraft');
|
|
104
|
+
await mkdir(directory, { recursive: true });
|
|
105
|
+
await copyFile(source, path.join(directory, 'SKILL.md'));
|
|
106
|
+
output({ installed: directory });
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (commandName === 'versions') {
|
|
110
|
+
if (positionals.length !== 1)
|
|
111
|
+
throw new Error('Use minecraft versions.');
|
|
112
|
+
const manifest = await readManifest(packageRoot);
|
|
113
|
+
output({ defaultVersion: manifest.defaultVersion, versions: Object.keys(manifest.versions) });
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
if (isControl ? !['state', 'screenshot', 'record', 'join', 'click', 'move', 'drag', 'scroll', 'key', 'type', 'execute', 'logs', 'batch'].includes(commandName ?? '') : !['launch', 'status', 'stop', 'update'].includes(commandName ?? '')) {
|
|
117
|
+
throw new Error(isControl ? `Unknown control command ${commandName}. Run minecraft --help.` : `Unknown command ${commandName}. Run minecraft --help.`);
|
|
118
|
+
}
|
|
119
|
+
requireClientPlatform();
|
|
120
|
+
if (!isControl && commandName === 'update') {
|
|
121
|
+
if (positionals.length !== 1)
|
|
122
|
+
throw new Error('Use minecraft update.');
|
|
123
|
+
output(await updateCli(packageRoot, {
|
|
124
|
+
progress: message => console.error(message),
|
|
125
|
+
acquireLock: () => acquireLock(os.tmpdir()),
|
|
126
|
+
}));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const root = managedRoot();
|
|
130
|
+
if (commandName === 'launch') {
|
|
131
|
+
if (rest.length)
|
|
132
|
+
throw new Error('Use minecraft launch [version].');
|
|
133
|
+
const port = values.port === undefined ? 8765 : Number(values.port);
|
|
134
|
+
validateControlPort(port);
|
|
135
|
+
const release = await acquireLock(root);
|
|
136
|
+
let updated = false;
|
|
137
|
+
try {
|
|
138
|
+
if (!(await running(root))) {
|
|
139
|
+
const attempt = await attemptAutomaticUpdate(packageRoot, { progress: message => console.error(message) });
|
|
140
|
+
if (attempt.error) {
|
|
141
|
+
if (attempt.fatal)
|
|
142
|
+
throw attempt.error;
|
|
143
|
+
console.error(`Automatic update skipped. ${attempt.error.message}`);
|
|
144
|
+
}
|
|
145
|
+
updated = attempt.result?.updated ?? false;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
await release();
|
|
150
|
+
}
|
|
151
|
+
if (updated) {
|
|
152
|
+
const entrypoint = process.argv[1];
|
|
153
|
+
if (!entrypoint)
|
|
154
|
+
throw new Error('Could not locate the updated CLI entrypoint.');
|
|
155
|
+
process.exitCode = await relaunchCli(entrypoint, process.execArgv, process.argv.slice(2));
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
output(describe(await launch(root, packageRoot, argument, values.username ?? 'Agent', message => console.error(message), port, !values.foreground)));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (commandName === 'stop') {
|
|
162
|
+
if (argument !== undefined)
|
|
163
|
+
throw new Error('Use minecraft stop.');
|
|
164
|
+
output(await stop(root));
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (commandName === 'status') {
|
|
168
|
+
if (argument !== undefined)
|
|
169
|
+
throw new Error('Use minecraft status.');
|
|
170
|
+
try {
|
|
171
|
+
await access(root);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
output({ running: false, ready: false });
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
const record = await running(root);
|
|
178
|
+
let ready = false;
|
|
179
|
+
if (record) {
|
|
180
|
+
try {
|
|
181
|
+
await controlReady(controlUrl(record.port));
|
|
182
|
+
ready = true;
|
|
183
|
+
}
|
|
184
|
+
catch { /* The process may still be starting. */ }
|
|
185
|
+
}
|
|
186
|
+
output({ running: !!record, ready, ...(record ? describe(record) : {}) });
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
if (commandName === 'state') {
|
|
190
|
+
if (argument !== undefined)
|
|
191
|
+
throw new Error('Use minecraft control state.');
|
|
192
|
+
output(await sendCommand(root, 'state'));
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (commandName === 'batch') {
|
|
196
|
+
if (argument === undefined || rest.length)
|
|
197
|
+
throw new Error('Use minecraft control batch <json-array>.');
|
|
198
|
+
let actions;
|
|
199
|
+
try {
|
|
200
|
+
actions = JSON.parse(argument);
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
throw new Error('The batch argument must be valid JSON.');
|
|
204
|
+
}
|
|
205
|
+
if (!Array.isArray(actions))
|
|
206
|
+
throw new Error('The batch argument must be a JSON array.');
|
|
207
|
+
output(await sendCommand(root, 'batch', { actions }));
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (commandName === 'screenshot') {
|
|
211
|
+
if (argument !== undefined)
|
|
212
|
+
throw new Error('Use minecraft control screenshot [--output <file>].');
|
|
213
|
+
const result = await sendCommand(root, 'screenshot');
|
|
214
|
+
if (result.mimeType !== 'image/png' || typeof result.data !== 'string')
|
|
215
|
+
throw new Error('The game did not return a PNG screenshot.');
|
|
216
|
+
const file = path.resolve(values.output ?? `minecraft-screenshot-${new Date().toISOString().replaceAll(':', '-')}.png`);
|
|
217
|
+
await writeFile(file, Buffer.from(result.data, 'base64'));
|
|
218
|
+
output({ screenshot: file, mimeType: result.mimeType });
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (commandName === 'record') {
|
|
222
|
+
if (argument === 'start' && !rest.length) {
|
|
223
|
+
if (values.output !== undefined)
|
|
224
|
+
throw new Error('Recordings are saved under the managed Minecraft instance.');
|
|
225
|
+
const fps = values.fps === undefined ? 10 : integer(values.fps, 'fps');
|
|
226
|
+
if (fps < 1 || fps > 20)
|
|
227
|
+
throw new Error('fps must be between 1 and 20.');
|
|
228
|
+
output(await sendCommand(root, 'record', { action: 'start', fps }));
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (argument === 'stop' && !rest.length && values.fps === undefined && values.output === undefined) {
|
|
232
|
+
output(await sendCommand(root, 'record', { action: 'stop' }));
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
throw new Error('Use minecraft control record start [--fps 10] or minecraft control record stop.');
|
|
236
|
+
}
|
|
237
|
+
if (commandName === 'join') {
|
|
238
|
+
if (!argument || rest.length)
|
|
239
|
+
throw new Error('Use minecraft control join <server-address>.');
|
|
240
|
+
output(await sendCommand(root, 'join', { ip: argument }));
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
if (commandName === 'click') {
|
|
244
|
+
if (rest.length !== 1)
|
|
245
|
+
throw new Error('Use minecraft control click <x> <y>.');
|
|
246
|
+
output(await sendCommand(root, 'click', { x: coordinate(argument, 'x'), y: coordinate(rest[0], 'y'), button: values.button ?? 'left', action: values.action ?? 'press' }));
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (commandName === 'move') {
|
|
250
|
+
if (rest.length !== 1)
|
|
251
|
+
throw new Error('Use minecraft control move <x> <y>.');
|
|
252
|
+
output(await sendCommand(root, 'move', { x: coordinate(argument, 'x'), y: coordinate(rest[0], 'y') }));
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
if (commandName === 'drag') {
|
|
256
|
+
if (rest.length !== 3)
|
|
257
|
+
throw new Error('Use minecraft control drag <x1> <y1> <x2> <y2>.');
|
|
258
|
+
output(await sendCommand(root, 'drag', {
|
|
259
|
+
from: { x: coordinate(argument, 'x1'), y: coordinate(rest[0], 'y1') },
|
|
260
|
+
to: { x: coordinate(rest[1], 'x2'), y: coordinate(rest[2], 'y2') },
|
|
261
|
+
button: values.button ?? 'left',
|
|
262
|
+
...(values['duration-ms'] === undefined ? {} : { duration_ms: integer(values['duration-ms'], 'duration-ms') }),
|
|
263
|
+
}));
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
if (commandName === 'scroll') {
|
|
267
|
+
if (rest.length)
|
|
268
|
+
throw new Error('Use minecraft control scroll <amount>.');
|
|
269
|
+
output(await sendCommand(root, 'scroll', { amount: coordinate(argument, 'amount') }));
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
if (commandName === 'key') {
|
|
273
|
+
if (!argument || rest.length)
|
|
274
|
+
throw new Error('Use minecraft control key <key-name-or-code>.');
|
|
275
|
+
const key = /^\d+$/.test(argument) ? integer(argument, 'key') : argument;
|
|
276
|
+
output(await sendCommand(root, 'key', { key, action: values.action ?? 'press' }));
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (commandName === 'type') {
|
|
280
|
+
if (argument === undefined)
|
|
281
|
+
throw new Error('Use minecraft control type <text>.');
|
|
282
|
+
output(await sendCommand(root, 'type', { text: [argument, ...rest].join(' ') }));
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (commandName === 'execute') {
|
|
286
|
+
if (argument === undefined)
|
|
287
|
+
throw new Error('Use minecraft control execute <command>.');
|
|
288
|
+
output(await sendCommand(root, 'execute', { command: [argument, ...rest].join(' ') }));
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
if (commandName === 'logs') {
|
|
292
|
+
if (rest.length > 1)
|
|
293
|
+
throw new Error('Use minecraft control logs [query] [--limit 100].');
|
|
294
|
+
output(await sendCommand(root, 'logs', { queries: argument ? [argument] : [], limit: values.limit === undefined ? 100 : integer(values.limit, 'limit') }));
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
main().catch(error => {
|
|
299
|
+
const json = process.argv.includes('--json');
|
|
300
|
+
console.error(json ? JSON.stringify({ error: error instanceof Error ? error.message : String(error) }) : `Error: ${error instanceof Error ? error.message : String(error)}`);
|
|
301
|
+
process.exitCode = 1;
|
|
302
|
+
});
|
package/dist/install.js
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, rename, rm, stat } from 'node:fs/promises';
|
|
3
|
+
import { arch, platform, release } from 'node:os';
|
|
4
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import AdmZip from 'adm-zip';
|
|
6
|
+
import { x as extractTar } from 'tar';
|
|
7
|
+
import { atomicWrite, download, fetchJson, parallel, readJson } from './download.js';
|
|
8
|
+
export function safePath(root, name) {
|
|
9
|
+
// Also reject Windows drive letters and backslash traversal on other hosts.
|
|
10
|
+
if (name.includes(':') || name.includes('\0'))
|
|
11
|
+
throw new Error(`Unsafe archive path ${name}`);
|
|
12
|
+
const destination = resolve(root, name.replaceAll('\\', '/'));
|
|
13
|
+
const part = relative(resolve(root), destination);
|
|
14
|
+
if (part === '..' || part.startsWith(`..${sep}`) || isAbsolute(part)) {
|
|
15
|
+
throw new Error(`Unsafe archive path ${name}`);
|
|
16
|
+
}
|
|
17
|
+
return destination;
|
|
18
|
+
}
|
|
19
|
+
export async function extractZip(archive, destination, exclusions = []) {
|
|
20
|
+
const zip = new AdmZip(archive);
|
|
21
|
+
for (const entry of zip.getEntries()) {
|
|
22
|
+
const path = safePath(destination, entry.entryName);
|
|
23
|
+
// ZIP symlinks can otherwise turn a later entry into a write outside the destination.
|
|
24
|
+
if (((entry.header.attr >>> 16) & 0xf000) === 0xa000)
|
|
25
|
+
throw new Error(`Archive contains a symbolic link ${entry.entryName}`);
|
|
26
|
+
if (exclusions.some(prefix => entry.entryName.startsWith(prefix)))
|
|
27
|
+
continue;
|
|
28
|
+
let ancestor = path;
|
|
29
|
+
while (true) {
|
|
30
|
+
try {
|
|
31
|
+
if ((await lstat(ancestor)).isSymbolicLink())
|
|
32
|
+
throw new Error(`Archive destination contains a symbolic link ${ancestor}`);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (error.code !== 'ENOENT')
|
|
36
|
+
throw error;
|
|
37
|
+
}
|
|
38
|
+
const parent = dirname(ancestor);
|
|
39
|
+
if (parent === ancestor)
|
|
40
|
+
break;
|
|
41
|
+
ancestor = parent;
|
|
42
|
+
}
|
|
43
|
+
if (entry.isDirectory)
|
|
44
|
+
await mkdir(path, { recursive: true });
|
|
45
|
+
else
|
|
46
|
+
await atomicWrite(path, entry.getData());
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function compareVersion(a, b) {
|
|
50
|
+
const aa = a.split('.').map(Number);
|
|
51
|
+
const bb = b.split('.').map(Number);
|
|
52
|
+
for (let i = 0; i < Math.max(aa.length, bb.length); i++) {
|
|
53
|
+
const delta = (aa[i] ?? 0) - (bb[i] ?? 0);
|
|
54
|
+
if (delta)
|
|
55
|
+
return delta;
|
|
56
|
+
}
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
59
|
+
export function allowed(rules) {
|
|
60
|
+
if (!rules)
|
|
61
|
+
return true;
|
|
62
|
+
let result = false;
|
|
63
|
+
for (const rule of rules) {
|
|
64
|
+
const os = rule.os;
|
|
65
|
+
if (os?.name && os.name !== (platform() === 'win32' ? 'windows' : platform()))
|
|
66
|
+
continue;
|
|
67
|
+
if (os?.arch && !['x86_64', 'amd64', 'x64'].includes(os.arch))
|
|
68
|
+
continue;
|
|
69
|
+
if (os?.version && !new RegExp(os.version).test(release()))
|
|
70
|
+
continue;
|
|
71
|
+
if (os?.versionRange?.min && compareVersion(release(), os.versionRange.min) < 0)
|
|
72
|
+
continue;
|
|
73
|
+
if (os?.versionRange?.max && compareVersion(release(), os.versionRange.max) > 0)
|
|
74
|
+
continue;
|
|
75
|
+
if (Object.entries(rule.features ?? {}).some(([, enabled]) => enabled))
|
|
76
|
+
continue;
|
|
77
|
+
result = rule.action === 'allow';
|
|
78
|
+
}
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
export function argumentsFor(arguments_, variables) {
|
|
82
|
+
return arguments_.flatMap(argument => typeof argument === 'string'
|
|
83
|
+
? [argument]
|
|
84
|
+
: allowed(argument.rules) ? [argument.value].flat() : []).map(argument => argument.replace(/\$\{([^}]+)\}/g, (_match, name) => {
|
|
85
|
+
if (!(name in variables))
|
|
86
|
+
throw new Error(`Unsupported launch variable ${name}`);
|
|
87
|
+
return variables[name];
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
export function mavenPath(coordinate) {
|
|
91
|
+
const [name, extension = 'jar'] = coordinate.split('@');
|
|
92
|
+
const [group, artifact, version, classifier] = name.split(':');
|
|
93
|
+
if (!group || !artifact || !version)
|
|
94
|
+
throw new Error(`Invalid Maven coordinate ${coordinate}`);
|
|
95
|
+
return `${group.replaceAll('.', '/')}/${artifact}/${version}/${artifact}-${version}${classifier ? `-${classifier}` : ''}.${extension}`;
|
|
96
|
+
}
|
|
97
|
+
async function cachedMetadata(path, fetchValue) {
|
|
98
|
+
try {
|
|
99
|
+
const cached = await readJson(path);
|
|
100
|
+
if (createHash('sha256').update(cached.json).digest('hex') === cached.sha256) {
|
|
101
|
+
return JSON.parse(cached.json);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (!(error instanceof SyntaxError) && error.code !== 'ENOENT')
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
const value = await fetchValue();
|
|
109
|
+
const json = JSON.stringify(value);
|
|
110
|
+
await atomicWrite(path, JSON.stringify({ json, sha256: createHash('sha256').update(json).digest('hex') }));
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
async function libraryArtifact(library, root) {
|
|
114
|
+
if (library.downloads?.artifact)
|
|
115
|
+
return library.downloads.artifact;
|
|
116
|
+
const path = mavenPath(library.name);
|
|
117
|
+
const url = new URL(path, library.url ?? 'https://libraries.minecraft.net/').href;
|
|
118
|
+
let sha1 = library.sha1;
|
|
119
|
+
if (!sha1 && !library.sha256) {
|
|
120
|
+
sha1 = await cachedMetadata(safePath(join(root, 'checksums'), `${path}.json`), async () => {
|
|
121
|
+
const response = await fetch(`${url}.sha1`, { signal: AbortSignal.timeout(60_000) });
|
|
122
|
+
if (!response.ok)
|
|
123
|
+
throw new Error(`Missing checksum for ${library.name}`);
|
|
124
|
+
return (await response.text()).trim().split(/\s+/)[0];
|
|
125
|
+
});
|
|
126
|
+
if (!/^[0-9a-f]{40}$/i.test(sha1 ?? ''))
|
|
127
|
+
throw new Error(`Invalid checksum for ${library.name}`);
|
|
128
|
+
}
|
|
129
|
+
return { path, url, ...(sha1 ? { sha1 } : {}),
|
|
130
|
+
...(library.sha256 ? { sha256: library.sha256 } : {}),
|
|
131
|
+
...(library.size !== undefined ? { size: library.size } : {}) };
|
|
132
|
+
}
|
|
133
|
+
/** Publish a complete runtime while retaining the old directory if publication fails. */
|
|
134
|
+
export async function publishRuntime(root, major, temporary) {
|
|
135
|
+
if (!Number.isSafeInteger(major) || major < 8)
|
|
136
|
+
throw new Error(`Invalid Java major version ${major}`);
|
|
137
|
+
const runtimeRoot = safePath(resolve(root), 'runtime');
|
|
138
|
+
const runtime = safePath(runtimeRoot, `java-${major}`);
|
|
139
|
+
const source = resolve(temporary);
|
|
140
|
+
if (dirname(source) !== runtimeRoot || !source.startsWith(`${runtime}.`) || !source.endsWith('.tmp')) {
|
|
141
|
+
throw new Error('Runtime staging directory is outside the managed runtime directory');
|
|
142
|
+
}
|
|
143
|
+
const quarantine = safePath(runtimeRoot, `java-${major}.${randomUUID()}.old`);
|
|
144
|
+
await mkdir(runtimeRoot, { recursive: true });
|
|
145
|
+
if ((await lstat(runtimeRoot)).isSymbolicLink())
|
|
146
|
+
throw new Error(`Managed runtime directory is a symbolic link ${runtimeRoot}`);
|
|
147
|
+
let replaced = false;
|
|
148
|
+
try {
|
|
149
|
+
const existing = await lstat(runtime);
|
|
150
|
+
if (existing.isSymbolicLink())
|
|
151
|
+
throw new Error(`Managed runtime is a symbolic link ${runtime}`);
|
|
152
|
+
await rename(runtime, quarantine);
|
|
153
|
+
replaced = true;
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
if (error.code !== 'ENOENT')
|
|
157
|
+
throw error;
|
|
158
|
+
}
|
|
159
|
+
try {
|
|
160
|
+
await rename(source, runtime);
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
if (replaced) {
|
|
164
|
+
try {
|
|
165
|
+
await rename(quarantine, runtime);
|
|
166
|
+
}
|
|
167
|
+
catch (restoreError) {
|
|
168
|
+
throw new Error(`Runtime publication failed. Previous runtime remains at ${quarantine}`, {
|
|
169
|
+
cause: new AggregateError([error, restoreError]),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
if (replaced)
|
|
176
|
+
await rm(quarantine, { recursive: true, force: true });
|
|
177
|
+
}
|
|
178
|
+
export async function extractJavaTar(archive, destination) {
|
|
179
|
+
let executable;
|
|
180
|
+
let validationError;
|
|
181
|
+
await extractTar({
|
|
182
|
+
file: archive, cwd: destination, strict: true, preserveOwner: false,
|
|
183
|
+
filter(name, entry) {
|
|
184
|
+
if (validationError)
|
|
185
|
+
return false;
|
|
186
|
+
try {
|
|
187
|
+
safePath(destination, name);
|
|
188
|
+
if (!('type' in entry))
|
|
189
|
+
return false;
|
|
190
|
+
if (entry.type === 'SymbolicLink' || entry.type === 'Link') {
|
|
191
|
+
if (!entry.linkpath)
|
|
192
|
+
throw new Error('Java archive contains an empty link');
|
|
193
|
+
safePath(destination, entry.type === 'Link' ? entry.linkpath : join(dirname(name), entry.linkpath));
|
|
194
|
+
}
|
|
195
|
+
if (/^[^/]+\/bin\/java$/.test(name) && entry.type === 'File')
|
|
196
|
+
executable = name;
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
// tar's streaming filter does not turn thrown errors into promise rejections.
|
|
201
|
+
validationError = error;
|
|
202
|
+
return false;
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
if (validationError)
|
|
207
|
+
throw validationError;
|
|
208
|
+
return executable;
|
|
209
|
+
}
|
|
210
|
+
async function installJava(root, major, progress) {
|
|
211
|
+
if (!Number.isSafeInteger(major) || major < 8)
|
|
212
|
+
throw new Error(`Invalid Java major version ${major}`);
|
|
213
|
+
const runtime = join(root, 'runtime', `java-${major}`);
|
|
214
|
+
const marker = join(runtime, 'installed.json');
|
|
215
|
+
try {
|
|
216
|
+
const installed = await readJson(marker);
|
|
217
|
+
if (!installed || typeof installed.executable !== 'string')
|
|
218
|
+
throw new SyntaxError('Invalid Java installation marker');
|
|
219
|
+
const java = safePath(runtime, platform() === 'win32' ? installed.executable.replace(/(^|[\\/])java\.exe$/i, '$1javaw.exe') : installed.executable);
|
|
220
|
+
if ((await stat(java)).isFile())
|
|
221
|
+
return java;
|
|
222
|
+
}
|
|
223
|
+
catch (error) {
|
|
224
|
+
if (!(error instanceof SyntaxError) && error.code !== 'ENOENT')
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
progress(`Installing Java ${major}`);
|
|
228
|
+
const assets = await fetchJson(`https://api.adoptium.net/v3/assets/latest/${major}/hotspot?architecture=x64&image_type=jre&os=${platform() === 'win32' ? 'windows' : 'linux'}&vendor=eclipse`);
|
|
229
|
+
const asset = assets[0]?.binary.package;
|
|
230
|
+
const windows = platform() === 'win32';
|
|
231
|
+
const extension = windows ? '.zip' : '.tar.gz';
|
|
232
|
+
if (!asset || !asset.name.endsWith(extension))
|
|
233
|
+
throw new Error(`No ${platform()} x64 Java ${major} runtime is available`);
|
|
234
|
+
const archive = join(root, 'cache', `${asset.checksum}${extension}`);
|
|
235
|
+
await download(archive, { url: asset.link, sha256: asset.checksum, size: asset.size });
|
|
236
|
+
const temporary = `${runtime}.${randomUUID()}.tmp`;
|
|
237
|
+
await mkdir(temporary, { recursive: true });
|
|
238
|
+
try {
|
|
239
|
+
let executable;
|
|
240
|
+
if (windows) {
|
|
241
|
+
await extractZip(archive, temporary);
|
|
242
|
+
executable = new AdmZip(archive).getEntries().find(entry => /^[^/]+\/bin\/javaw\.exe$/.test(entry.entryName))?.entryName;
|
|
243
|
+
}
|
|
244
|
+
else {
|
|
245
|
+
executable = await extractJavaTar(archive, temporary);
|
|
246
|
+
}
|
|
247
|
+
if (!executable)
|
|
248
|
+
throw new Error('Java runtime archive does not contain a Java executable');
|
|
249
|
+
await atomicWrite(join(temporary, 'installed.json'), JSON.stringify({ executable, checksum: asset.checksum }));
|
|
250
|
+
await publishRuntime(root, major, temporary);
|
|
251
|
+
return safePath(runtime, executable);
|
|
252
|
+
}
|
|
253
|
+
finally {
|
|
254
|
+
await rm(temporary, { recursive: true, force: true });
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
export async function install(root, version, compatibility, progress) {
|
|
258
|
+
if (!['win32', 'linux'].includes(platform()) || arch() !== 'x64')
|
|
259
|
+
throw new Error('Managed Minecraft currently requires Windows or Linux x64');
|
|
260
|
+
if (!/^[a-zA-Z0-9._+-]+$/.test(version) || !/^[a-zA-Z0-9._+-]+$/.test(compatibility.loader)) {
|
|
261
|
+
throw new Error('Invalid Minecraft or Fabric version');
|
|
262
|
+
}
|
|
263
|
+
root = resolve(root);
|
|
264
|
+
const instance = join(root, 'instances', version);
|
|
265
|
+
await mkdir(join(instance, 'mods'), { recursive: true });
|
|
266
|
+
progress(`Reading Minecraft ${version} and Fabric ${compatibility.loader} metadata`);
|
|
267
|
+
const entry = await cachedMetadata(join(root, 'versions', version, 'source.json'), async () => {
|
|
268
|
+
const manifest = await fetchJson('https://piston-meta.mojang.com/mc/game/version_manifest_v2.json');
|
|
269
|
+
const entry = manifest.versions.find(candidate => candidate.id === version);
|
|
270
|
+
if (!entry)
|
|
271
|
+
throw new Error(`Minecraft ${version} is absent from Mojang's version manifest`);
|
|
272
|
+
return entry;
|
|
273
|
+
});
|
|
274
|
+
const metadata = join(root, 'versions', version, `${version}.json`);
|
|
275
|
+
await download(metadata, entry);
|
|
276
|
+
const vanilla = await readJson(metadata);
|
|
277
|
+
const fabric = await cachedMetadata(join(root, 'versions', version, `fabric-${compatibility.loader}.json`), () => fetchJson(`https://meta.fabricmc.net/v2/versions/loader/${encodeURIComponent(version)}/${encodeURIComponent(compatibility.loader)}/profile/json`));
|
|
278
|
+
const java = await installJava(root, Math.max(compatibility.java, vanilla.javaVersion?.majorVersion ?? 0), progress);
|
|
279
|
+
const assets = join(root, 'assets');
|
|
280
|
+
const libraries = join(root, 'libraries');
|
|
281
|
+
const natives = join(instance, 'natives');
|
|
282
|
+
await mkdir(natives, { recursive: true });
|
|
283
|
+
const client = join(root, 'versions', version, `${version}.jar`);
|
|
284
|
+
progress('Installing Minecraft client and libraries');
|
|
285
|
+
await download(client, vanilla.downloads.client);
|
|
286
|
+
const embeddedVersion = JSON.parse(new AdmZip(client).readAsText('version.json'));
|
|
287
|
+
const optionsDataVersion = embeddedVersion.world_version;
|
|
288
|
+
if (!Number.isSafeInteger(optionsDataVersion) || optionsDataVersion < 1446) {
|
|
289
|
+
throw new Error('Minecraft client contains an invalid options data version');
|
|
290
|
+
}
|
|
291
|
+
// Child coordinates replace inherited versions of the same Maven artifact.
|
|
292
|
+
const merged = new Map();
|
|
293
|
+
for (const library of [...vanilla.libraries, ...fabric.libraries]) {
|
|
294
|
+
const [group, name, , classifier] = library.name.split(':');
|
|
295
|
+
merged.set(`${group}:${name}:${classifier ?? ''}`, library);
|
|
296
|
+
}
|
|
297
|
+
const activeLibraries = [...merged.values()].filter(library => allowed(library.rules));
|
|
298
|
+
const classpath = new Array(activeLibraries.length).fill('');
|
|
299
|
+
const nativeArchives = new Array(activeLibraries.length);
|
|
300
|
+
await parallel(activeLibraries.map((library, index) => ({ library, index })), async ({ library, index }) => {
|
|
301
|
+
if (library.downloads?.artifact || !library.downloads) {
|
|
302
|
+
const artifact = await libraryArtifact(library, root);
|
|
303
|
+
const path = safePath(libraries, artifact.path ?? mavenPath(library.name));
|
|
304
|
+
await download(path, artifact);
|
|
305
|
+
classpath[index] = path;
|
|
306
|
+
}
|
|
307
|
+
const classifier = library.natives?.[platform() === 'win32' ? 'windows' : 'linux']?.replace('${arch}', '64');
|
|
308
|
+
if (classifier) {
|
|
309
|
+
const artifact = library.downloads?.classifiers?.[classifier];
|
|
310
|
+
if (!artifact)
|
|
311
|
+
throw new Error(`Missing native library ${library.name} ${classifier}`);
|
|
312
|
+
const path = safePath(libraries, artifact.path ?? mavenPath(`${library.name}:${classifier}`));
|
|
313
|
+
await download(path, artifact);
|
|
314
|
+
nativeArchives[index] = { path, exclude: library.extract?.exclude ?? ['META-INF/'] };
|
|
315
|
+
}
|
|
316
|
+
});
|
|
317
|
+
for (const archive of nativeArchives)
|
|
318
|
+
if (archive)
|
|
319
|
+
await extractZip(archive.path, natives, archive.exclude);
|
|
320
|
+
classpath.push(client);
|
|
321
|
+
progress('Installing Minecraft assets');
|
|
322
|
+
const assetIndex = safePath(join(assets, 'indexes'), `${vanilla.assetIndex.id}.json`);
|
|
323
|
+
await download(assetIndex, vanilla.assetIndex);
|
|
324
|
+
const index = await readJson(assetIndex);
|
|
325
|
+
const objects = [...new Map(Object.values(index.objects).map(object => [object.hash, object])).values()];
|
|
326
|
+
let completed = 0;
|
|
327
|
+
await parallel(objects, async (object) => {
|
|
328
|
+
if (!/^[0-9a-f]{40}$/.test(object.hash))
|
|
329
|
+
throw new Error('Invalid Minecraft asset hash');
|
|
330
|
+
const suffix = `${object.hash.slice(0, 2)}/${object.hash}`;
|
|
331
|
+
await download(safePath(join(assets, 'objects'), suffix), { url: `https://resources.download.minecraft.net/${suffix}`, sha1: object.hash, size: object.size });
|
|
332
|
+
completed++;
|
|
333
|
+
if (completed % 250 === 0)
|
|
334
|
+
progress(`Installed ${completed} of ${objects.length} assets`);
|
|
335
|
+
});
|
|
336
|
+
const logging = vanilla.logging?.client;
|
|
337
|
+
let logArgument = [];
|
|
338
|
+
if (logging) {
|
|
339
|
+
const path = safePath(join(assets, 'log_configs'), logging.file.id);
|
|
340
|
+
await download(path, logging.file);
|
|
341
|
+
logArgument = [logging.argument.replace('${path}', path)];
|
|
342
|
+
}
|
|
343
|
+
const variables = {
|
|
344
|
+
version_name: fabric.id, version_type: vanilla.type, game_directory: instance,
|
|
345
|
+
assets_root: assets, assets_index_name: vanilla.assetIndex.id, natives_directory: natives,
|
|
346
|
+
launcher_name: 'minecraft-cli', launcher_version: '1.0', classpath: classpath.filter(Boolean).join(platform() === 'win32' ? ';' : ':'),
|
|
347
|
+
classpath_separator: platform() === 'win32' ? ';' : ':', library_directory: libraries, auth_access_token: '0',
|
|
348
|
+
auth_xuid: '', clientid: '', user_type: 'legacy', user_properties: '{}',
|
|
349
|
+
};
|
|
350
|
+
return {
|
|
351
|
+
java, instance, versionId: fabric.id, optionsDataVersion: optionsDataVersion,
|
|
352
|
+
launch(username, uuid, port = 8765, background = true) {
|
|
353
|
+
const values = { ...variables, auth_player_name: username, auth_uuid: uuid };
|
|
354
|
+
return ['-Xmx4G', `-Dminecraft.control.port=${port}`, `-Dminecraft.control.background=${background}`,
|
|
355
|
+
...argumentsFor(vanilla.arguments.jvm, values), ...argumentsFor(fabric.arguments?.jvm ?? [], values),
|
|
356
|
+
...logArgument, fabric.mainClass,
|
|
357
|
+
...argumentsFor(vanilla.arguments.game, values), ...argumentsFor(fabric.arguments?.game ?? [], values)];
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
}
|