-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathlaunch.ts
833 lines (769 loc) · 28.6 KB
/
launch.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
import { open, openEntryReadStream, walkEntriesGenerator } from '@xmcl/unzip'
import { ChildProcess, SpawnOptions, spawn } from 'child_process'
import { randomUUID } from 'crypto'
import { EventEmitter } from 'events'
import { createWriteStream, existsSync } from 'fs'
import { link, mkdir, readFile, writeFile } from 'fs/promises'
import { EOL } from 'os'
import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'path'
import { pipeline } from 'stream'
import { promisify } from 'util'
import { MinecraftFolder } from './folder'
import { Platform, getPlatform } from './platform'
import { checksum, validateSha1 } from './utils'
import { ResolvedLibrary, ResolvedVersion, Version } from './version'
function format(template: string, args: any) {
return template.replace(/\$\{(.*?)}/g, (key) => {
const value = args[key.substring(2).substring(0, key.length - 3)]
return value || key
})
}
export const DEFAULT_EXTRA_JVM_ARGS = Object.freeze([
'-Xmx2G',
'-XX:+UnlockExperimentalVMOptions',
'-XX:+UseG1GC',
'-XX:G1NewSizePercent=20',
'-XX:G1ReservePercent=20',
'-XX:MaxGCPauseMillis=50',
'-XX:G1HeapRegionSize=32M',
])
export interface EnabledFeatures {
[featureName: string]: object | boolean | undefined
// eslint-disable-next-line camelcase
has_custom_resolution?: { resolution_width: string; resolution_height: string }
// eslint-disable-next-line camelcase
is_demo_user?: boolean
}
/**
* General launch option, used to generate launch arguments.
* @see {@link generateArguments}
* @see {@link launch}
*/
export interface LaunchOption {
/**
* User selected game profile. For game display name &
*/
gameProfile?: {
name: string
id: string
}
accessToken?: string
userType?: 'mojang' | 'legacy'
properties?: object
launcherName?: string
launcherBrand?: string
/**
* Overwrite the version name of the current version.
* If this is absent, it will use version name from resolved version.
*/
versionName?: string
/**
* Overwrite the version type of the current version.
* If this is absent, it will use version type from resolved version.
*
* Some people use this to show fantastic message on the welcome screen.
*/
versionType?: string
/**
* The full path of launched game icon
* Currently, this only supported on MacOS
*/
gameIcon?: string
/**
* The launched game name
* Currently, this only supported on MacOS
*/
gameName?: string
/**
* The path of parent directory of saves/logs/configs/mods/resourcepacks
*/
gamePath: string
/**
* The path of parent directory of assets/libraries
*/
resourcePath?: string
/**
* The java executable file path. (Not the java home directory!)
*/
javaPath: string
/**
* Min memory, this will add a jvm flag -Xms to the command result
*/
minMemory?: number
/**
* Min memory, this will add a jvm flag -Xmx to the command result
*/
maxMemory?: number
/**
* The version of launched Minecraft. Can be either resolved version or version string
*/
version: string | ResolvedVersion
/**
* Directly launch to a server
*/
server?: { ip: string; port?: number }
/**
* Resolution. This will add --height & --width or --fullscreen to the java arguments
*/
resolution?: { width?: number; height?: number; fullscreen?: true }
/**
* Extra jvm options. This will append after to generated options.
* If this is empty, the `DEFAULT_EXTRA_JVM_ARGS` will be used.
*/
extraJVMArgs?: string[]
/**
* Extra program arguments. This will append after to generated options.
*/
extraMCArgs?: string[]
/**
* Prepend command before java command.
*/
prependCommand?: string | string[]
/**
* Assign the spawn options to the process.
*
* If you try to set `{ shell: true }`, you might want to make all argument rounded with "".
* The `launch` function will do it for you, but if you want to spawn process by yourself, remember to do that.
*/
extraExecOption?: SpawnOptions
isDemo?: boolean
/**
* Native directory. It's .minecraft/versions/<version>/<version>-natives by default.
* You can replace this by your self.
*/
nativeRoot?: string
/**
* Enable features. Not really in used...
*/
features?: EnabledFeatures
/**
* Support yushi's yggdrasil agent https://github.com/to2mbn/authlib-injector/wiki
*/
yggdrasilAgent?: {
/**
* The jar file path of the authlib-injector
*/
jar: string
/**
* The auth server host
*/
server: string
/**
* The prefetched base64
*/
prefetched?: string
}
/**
* Add `-Dfml.ignoreInvalidMinecraftCertificates=true` to jvm argument
*/
ignoreInvalidMinecraftCertificates?: boolean
/**
* Add `-Dfml.ignorePatchDiscrepancies=true` to jvm argument
*/
ignorePatchDiscrepancies?: boolean
/**
* Add extra classpaths
*/
extraClassPaths?: string[]
/**
* The platform of this launch will run. By default, it will fetch the current machine info if this is absent.
*/
platform?: Platform
/**
* Use hash assets index. This will use the assets index hash as the assets index name.
*/
useHashAssetsIndex?: boolean
/**
* The launcher precheck functions. These will run before it run.
*
* This property is only used for `launch` function. The `generateArguments` function won't use this!
* @see {@link launch}
* @see {@link generateArguments}
*/
prechecks?: LaunchPrecheck[]
/**
* The spawn process function. Used for spawn the java process at the end.
*
* By default, it will be the spawn function from "child_process" module. You can use this option to change the 3rd party spawn like [cross-spawn](https://www.npmjs.com/package/cross-spawn)
*/
spawn?: (command: string, args?: ReadonlyArray<string>, options?: SpawnOptions) => ChildProcess
}
/**
* The function to check the game status before the game launched. Will be used in `launch` function.
* @see {@link launch}
*/
export interface LaunchPrecheck {
(resourcePath: MinecraftFolder, version: ResolvedVersion, option: LaunchOption): Promise<void>
}
/**
* Thrown when the version jar is corrupted. This interface only used in `LaunchPrecheck.checkVersion`
* @see {@link LaunchPrecheck.checkVersion}
*/
export interface CorruptedVersionJarError {
error: 'CorruptedVersionJar'
version: string
}
/**
* Thrown when the libraries jar is corrupted. This interface only used in `LaunchPrecheck.checkLibraries`
* @see {@link LaunchPrecheck.checkLibraries}
*/
export interface MissingLibrariesError {
error: 'MissingLibraries'
libraries: ResolvedLibrary[]
version: ResolvedVersion
}
// eslint-disable-next-line @typescript-eslint/no-namespace
export namespace LaunchPrecheck {
/**
* The default launch precheck. It will check version jar, libraries and natives.
*/
export const DEFAULT_PRECHECKS: readonly LaunchPrecheck[] = Object.freeze([checkVersion, checkLibraries, checkNatives, linkAssets])
/**
* @deprecated
*/
export const Default = LaunchPrecheck.DEFAULT_PRECHECKS
/**
* Link assets to the assets/virtual/legacy.
*/
export async function linkAssets(resource: MinecraftFolder, version: ResolvedVersion, option: LaunchOption) {
if (version.assets !== 'legacy' && !version.assets.startsWith('pre-')) {
return
}
const assetsIndexPath = resource.getAssetsIndex(version.assets)
const buf = await readFile(assetsIndexPath)
const assetsIndex: { objects: Record<string, { hash: string; size: number }> } = JSON.parse(buf.toString())
const virtualPath = resource.getPath('assets/virtual/' + version.assets)
await mkdir(virtualPath, { recursive: true }).catch(() => { })
const dirs = Object.keys(assetsIndex.objects)
.map((path) => dirname(join(virtualPath, path)))
.reduce((a, b) => a.add(b), new Set<string>())
await Promise.all([...dirs].map((dir) => mkdir(dir, { recursive: true })))
for (const [path, { hash }] of Object.entries(assetsIndex.objects)) {
const assetPath = resource.getAsset(hash)
const targetPath = join(virtualPath, path)
await link(assetPath, targetPath).catch((e) => {
if (e.code !== 'EEXIST') { throw e }
})
}
}
/**
* Quick check if Minecraft version jar is corrupted
* @throws {@link CorruptedVersionJarError}
*/
export async function checkVersion(resource: MinecraftFolder, version: ResolvedVersion, option: LaunchOption) {
const jarPath = resource.getVersionJar(version.minecraftVersion)
if (version.downloads.client?.sha1) {
if (!await validateSha1(jarPath, version.downloads.client.sha1)) {
throw Object.assign(new Error(`Corrupted Version jar ${jarPath}. Either the file not reachable or the file sha1 not matched!`), {
error: 'CorruptedVersionJar',
version: version.minecraftVersion,
} as CorruptedVersionJarError)
}
}
}
/**
* Quick check if there are missed libraries.
* @throws {@link MissingLibrariesError}
*/
export async function checkLibraries(resource: MinecraftFolder, version: ResolvedVersion, option: LaunchOption) {
const validMask = await Promise.all(version.libraries
.map((lib) => validateSha1(resource.getLibraryByPath(lib.download.path), lib.download.sha1)))
const corruptedLibs = version.libraries.filter((_, index) => !validMask[index])
if (corruptedLibs.length > 0) {
throw Object.assign(new Error(`Missing ${corruptedLibs.length} libraries! Either the file not reachable or the file sha1 not matched!`), {
error: 'MissingLibraries',
libraries: corruptedLibs,
version,
} as MissingLibrariesError)
}
}
/**
* Ensure the native are correctly extracted in place.
*
* It will check native root located in {@link LaunchOption.nativeRoot} if it's presented.
* Or, it will use the `<version-id>-native` under version folder as native root to check.
*
* This will automatically extract native if there is not native extracted.
*
* @param resource The minecraft directory to extract native
* @param option If the native root presented here, it will use the root here.
*/
export async function checkNatives(resource: MinecraftFolder, version: ResolvedVersion, option: LaunchOption) {
const native: string = option.nativeRoot || resource.getNativesRoot(version.id)
await mkdir(native, { recursive: true }).catch((e) => {
if (e.code !== 'EEXIST') { throw e }
})
const natives = version.libraries.filter((lib) => lib.isNative || lib.classifier.startsWith('natives'))
const checksumFile = join(native, '.json')
const includedLibs = natives.map((n) => n.name).sort()
interface ChecksumFile { entries: CheckEntry[]; libraries: string[] }
interface CheckEntry { file: string; sha1: string; name: string }
const checksumFileObject: ChecksumFile = await readFile(checksumFile, 'utf-8').then(JSON.parse).catch((e) => undefined)
let shaEntries: CheckEntry[] | undefined
if (checksumFileObject && checksumFileObject.libraries) {
// only if the lib not change
// consider the case of os changed or java changed
if (checksumFileObject.libraries.sort().every((v, i) => v === includedLibs[i])) {
shaEntries = checksumFileObject.entries
}
}
const extractedNatives: CheckEntry[] = []
async function extractJar(n: ResolvedLibrary | undefined) {
if (!n) { return }
const excluded: string[] = n.extractExclude || []
const platform = option.platform || getPlatform()
const containsExcludes = (p: string) => excluded.filter((s) => p.startsWith(s)).length === 0
const notInMetaInf = (p: string) => p.indexOf('META-INF/') === -1
const notSha1AndNotGit = (p: string) => !(p.endsWith('.sha1') || p.endsWith('.git'))
const isSatisfyPlaform = (p: string) => {
if (p.indexOf('/') === -1) { return true }
const [os, arch] = p.split('/')
const platformArch = arch === 'ia32' ? 'x86' : arch
return os === platform.name && platformArch === platform.arch
}
const from = resource.getLibraryByPath(n.download.path)
const promises: Promise<void>[] = []
const zip = await open(from, { lazyEntries: true, autoClose: false })
for await (const entry of walkEntriesGenerator(zip)) {
if (
containsExcludes(entry.fileName) &&
notInMetaInf(entry.fileName) &&
notSha1AndNotGit(entry.fileName) &&
!entry.fileName.endsWith('/') &&
isSatisfyPlaform(entry.fileName)
) {
const fileName = basename(entry.fileName)
const dest = join(native, fileName)
if (fileName.indexOf('/') !== -1) {
await mkdir(dirname(dest), {
recursive: true,
}).catch((e) => { })
}
extractedNatives.push({ file: fileName, name: n.name, sha1: '' })
promises.push(promisify(pipeline)(await openEntryReadStream(zip, entry), createWriteStream(dest)))
}
}
await Promise.all(promises)
}
if (shaEntries) {
const validEntries: { [name: string]: boolean } = {}
for (const entry of shaEntries) {
if (typeof entry.file !== 'string') { continue }
const file = join(native, entry.file)
const valid = await validateSha1(file, entry.sha1, true)
if (valid) {
validEntries[entry.name] = true
}
}
const missingNatives = natives.filter((n) => !validEntries[n.name])
if (missingNatives.length !== 0) {
await Promise.all(missingNatives.map(extractJar))
}
} else {
await Promise.all(natives.map(extractJar))
const entries = await Promise.all(extractedNatives.map(async (n) => ({
...n,
sha1: await checksum(join(native, n.file), 'sha1'),
})))
const fileContent = JSON.stringify({
entries,
libraries: includedLibs,
})
await writeFile(checksumFile, fileContent)
}
}
}
export interface BaseServerOptions {
/**
* Java executable.
*/
javaPath: string
/**
* No gui for the server launch
*/
nogui?: boolean
minMemory?: number
maxMemory?: number
extraJVMArgs?: string[]
extraMCArgs?: string[]
extraExecOption?: SpawnOptions
prependCommand?: string | string[]
/**
* The spawn process function. Used for spawn the java process at the end. By default, it will be the spawn function from "child_process" module. You can use this option to change the 3rd party spawn like [cross-spawn](https://www.npmjs.com/package/cross-spawn)
*/
spawn?: (command: string, args?: ReadonlyArray<string>, options?: SpawnOptions) => ChildProcess
}
/**
* This is the case you provide the server jar execution path.
*/
export interface ServerOptions extends BaseServerOptions {
/**
* The minecraft server exectuable jar file.
*
* This is the case like you are launching forge server.
*/
serverExectuableJarPath?: string
mainClass?: string
classPath?: string[]
}
export async function launchServer(options: ServerOptions) {
const args = generateArgumentsServer(options)
const spawnOption = { env: process.env, ...options.extraExecOption }
return (options.spawn ?? spawn)(args[0], args.slice(1), spawnOption)
}
/**
* The Minecraft process watcher. You can inspect Minecraft launch state by this.
*
* Generally, there are several cases after you call `launch` and get `ChildProcess` object
*
* 1. child process fire an error, no real process start.
* 2. child process started, but game crash (code is not 0).
* 3. cihld process started, game normally exit (code is 0).
*/
export interface MinecraftProcessWatcher extends EventEmitter {
/**
* Fire when the process DOESN'T start at all, like "java not found".
*
* The minecraft-kill or minecraft-exit will NOT fire after this fired.
*/
on(event: 'error', listener: (error: any) => void): this
/**
* Fire after Minecraft process exit.
*/
on(event: 'minecraft-exit', listener: (event: {
/**
* The code of the process exit. This is the nodejs child process "exit" event arg.
*/
code: number
/**
* The signal of the process exit. This is the nodejs child process "exit" event arg.
*/
signal: string
/**
* The crash report content
*/
crashReport: string
/**
* The location of the crash report
*/
crashReportLocation: string
}) => void): this
/**
* Fire around the time when Minecraft window appeared in screen.
*
* Since the Minecraft window will take time to init, this event fire when it capture some keywords from stdout.
*/
on(event: 'minecraft-window-ready', listener: () => void): this
}
/**
* Create a process watcher for a minecraft process.
*
* It will watch the stdout and the error event of the process to detect error and minecraft state.
* @param process The Minecraft process
* @param emitter The event emitter which will emit usefule event
*/
export function createMinecraftProcessWatcher(process: ChildProcess, emitter: EventEmitter = new EventEmitter()): MinecraftProcessWatcher {
let crashReport = ''
let crashReportLocation = ''
let waitForReady = true
process.on('error', (e) => {
emitter.emit('error', e)
})
process.on('exit', (code, signal) => {
emitter.emit('minecraft-exit', {
code,
signal,
crashReport,
crashReportLocation,
})
})
process.stdout?.on('data', (s) => {
const string = s.toString()
if (string.indexOf('---- Minecraft Crash Report ----') !== -1) {
crashReport = string
} else if (string.indexOf('Crash report saved to:') !== -1) {
crashReportLocation = string.substring(string.indexOf('Crash report saved to:') + 'Crash report saved to: #@!@# '.length)
crashReportLocation = crashReportLocation.replace(EOL, '').trim()
} else if (waitForReady && (string.indexOf('Missing metadata in pack') !== -1 || string.indexOf('Registering resource reload listener') !== -1 || string.indexOf('Reloading ResourceManager') !== -1 || string.indexOf('LWJGL Version: ') !== -1 || string.indexOf('OpenAL initialized.') !== -1)) {
waitForReady = false
emitter.emit('minecraft-window-ready')
} else if (waitForReady && (string.indexOf(' Preparing level ') !== -1)) {
waitForReady = false
emitter.emit('minecraft-window-ready')
} else if (string.indexOf('Failed to start the minecraft server') !== -1) {
crashReport = string
}
})
return emitter
}
/**
* Launch the minecraft as a child process. This function use spawn to create child process. To use an alternative way, see function generateArguments.
*
* By default, it will use the `LauncherPrecheck.Default` to pre-check:
* - It will also check if the runtime libs are completed, and will extract native libs if needed.
* - It might throw exception when the version jar is missing/checksum not matched.
* - It might throw if the libraries/natives are missing.
*
* If you DON'T want such precheck, and you want to change it. You can assign the `prechecks` property in launch
*
* ```ts
* launch({ ...otherOptions, prechecks: yourPrechecks });
* ```
*
* @param options The detail options for this launching.
* @see [ChildProcess](https://nodejs.org/api/child_process.html)
* @see [spawn](https://nodejs.org/api/spawn.html)
* @see {@link generateArguments}
* @see {@link createMinecraftProcessWatcher}
* @throws {@link CorruptedVersionJarError}
* @throws {@link MissingLibrariesError}
*/
export async function launch(options: LaunchOption): Promise<ChildProcess> {
const gamePath = !isAbsolute(options.gamePath) ? resolve(options.gamePath) : options.gamePath
const resourcePath = options.resourcePath || gamePath
const version = typeof options.version === 'string' ? await Version.parse(resourcePath, options.version) : options.version
let args = await generateArguments({ ...options, version, gamePath, resourcePath })
const minecraftFolder = MinecraftFolder.from(resourcePath)
const prechecks = options.prechecks || LaunchPrecheck.DEFAULT_PRECHECKS
await Promise.all(prechecks.map((f) => f(minecraftFolder, version, options)))
const spawnOption = { cwd: options.gamePath, ...options.extraExecOption }
if (options.extraExecOption?.shell) {
args = args.map((a) => `"${a}"`)
}
// fix the ENOTFOUND if cwd does not existed.
if (!existsSync(gamePath)) {
await mkdir(gamePath)
}
return (options.spawn ?? spawn)(args[0], args.slice(1), spawnOption)
}
function unshiftPrependCommand(cmd: string[], prependCommand?: string[] | string) {
if (prependCommand) {
if (typeof prependCommand === 'string') {
if (prependCommand.trim().length > 0) {
cmd.push(prependCommand.trim())
}
} else {
for (const c of prependCommand) {
const trimmed = c.trim()
if (trimmed.length > 0) {
cmd.unshift(trimmed)
}
}
}
}
}
/**
* Generate the argument for server
*/
export function generateArgumentsServer(options: ServerOptions, _delimiter: string = delimiter, _sep: string = sep) {
const { javaPath, minMemory, maxMemory, extraJVMArgs = [], extraMCArgs = [], extraExecOption = {} } = options
const cmd = [
javaPath,
]
if (minMemory) {
cmd.push(`-Xms${(minMemory)}M`)
}
if (maxMemory) {
cmd.push(`-Xmx${(maxMemory)}M`)
}
cmd.push(
...extraJVMArgs,
)
if (options.classPath && options.classPath.length > 0) {
cmd.push('-cp', options.classPath.map(v => v.replaceAll(sep, _sep)).join(_delimiter))
}
if (options.serverExectuableJarPath) {
cmd.push('-jar', options.serverExectuableJarPath.replaceAll(sep, _sep))
} else if (options.mainClass) {
cmd.push(options.mainClass)
}
cmd.push(...extraMCArgs)
if (options.nogui) {
cmd.push('nogui')
}
unshiftPrependCommand(cmd, options.prependCommand)
return cmd
}
/**
* Generate the arguments array by options. This function is useful if you want to launch the process by yourself.
*
* This function will **NOT** check if the runtime libs are completed, and **WONT'T** check or extract native libs.
*
* If you want to ensure native. Please see {@link LaunchPrecheck.checkNatives}.
*
* @param options The launch options.
* @throws TypeError if options does not fully fulfill the requirement
*/
export async function generateArguments(options: LaunchOption) {
if (!options.version) { throw new TypeError('Version cannot be null!') }
if (!options.isDemo) { options.isDemo = false }
const currentPlatform = options.platform ?? getPlatform()
const gamePath = !isAbsolute(options.gamePath) ? resolve(options.gamePath) : options.gamePath
const resourcePath = options.resourcePath || gamePath
const version = typeof options.version === 'string' ? await Version.parse(resourcePath, options.version) : options.version
const mc = MinecraftFolder.from(resourcePath)
const cmd: string[] = []
const { id = randomUUID().replace(/-/g, ''), name = 'Steve' } = options.gameProfile || {}
const accessToken = options.accessToken || randomUUID().replace(/-/g, '')
const properties = options.properties || {}
const userType = options.userType || 'msa'
const features = options.features || {}
const jvmArguments = normalizeArguments(version.arguments.jvm, currentPlatform, features)
const gameArguments = normalizeArguments(version.arguments.game, currentPlatform, features)
const featureValues = Object.values(features).filter((f) => typeof f === 'object').reduce((a: any, b: any) => ({ ...a, ...b }), {})
const launcherName = options.launcherName || 'Launcher'
const launcherBrand = options.launcherBrand || '0.0.1'
const nativeRoot = options.nativeRoot || mc.getNativesRoot(version.id)
let gameIcon = options.gameIcon
if (!gameIcon) {
const index = mc.getAssetsIndex(version.assets)
const indexContent = await readFile(index, { encoding: 'utf-8' }).then((b) => JSON.parse(b.toString()), () => ({}))
if ('icons/minecraft.icns' in indexContent) {
gameIcon = mc.getAsset(indexContent['icons/minecraft.icns'].hash)
} else if ('minecraft/icons/minecraft.icns' in indexContent) {
gameIcon = mc.getAsset(indexContent['minecraft/icons/minecraft.icns'].hash)
} else {
gameIcon = ''
}
}
const gameName = options.gameName || 'Minecraft'
cmd.push(options.javaPath)
if (currentPlatform.name === 'osx') {
cmd.push(`-Xdock:name=${gameName}`)
if (gameIcon) {
cmd.push(`-Xdock:icon=${gameIcon}`)
}
}
if (options.minMemory) {
cmd.push(`-Xms${(options.minMemory)}M`)
}
if (options.maxMemory) {
cmd.push(`-Xmx${(options.maxMemory)}M`)
}
if (options.ignoreInvalidMinecraftCertificates) {
cmd.push('-Dfml.ignoreInvalidMinecraftCertificates=true')
}
if (options.ignorePatchDiscrepancies) {
cmd.push('-Dfml.ignorePatchDiscrepancies=true')
}
if (options.yggdrasilAgent) {
cmd.push(`-javaagent:${options.yggdrasilAgent.jar}=${options.yggdrasilAgent.server}`)
cmd.push('-Dauthlibinjector.side=client')
if (options.yggdrasilAgent.prefetched) {
cmd.push(`-Dauthlibinjector.yggdrasil.prefetched=${options.yggdrasilAgent.prefetched}`)
}
}
const jvmOptions = {
natives_directory: nativeRoot,
launcher_name: launcherName,
launcher_version: launcherBrand,
game_directory: gamePath,
classpath: [
...version.libraries.filter((lib) => !lib.isNative).map((lib) => mc.getLibraryByPath(lib.download.path)),
mc.getVersionJar(version.minecraftVersion),
...(options.extraClassPaths || []),
].join(delimiter),
library_directory: mc.getPath('libraries'),
classpath_separator: delimiter,
version_name: version.minecraftVersion,
...featureValues,
}
if (version.logging && version.logging.client) {
const client = version.logging.client
const argument = client.argument
const filePath = mc.getLogConfig(client.file.id)
if (existsSync(filePath)) {
// eslint-disable-next-line no-template-curly-in-string
jvmArguments.push(argument.replace('${path}', filePath))
}
}
cmd.push(...jvmArguments.map((arg) => format(arg, jvmOptions)))
if (!cmd.some(v => v.startsWith('-DlibraryDirectory'))) {
cmd.push('-DlibraryDirectory=' + mc.getPath('libraries'))
}
// add extra jvm args
if (options.extraJVMArgs instanceof Array) {
if (options.extraJVMArgs.some((v) => typeof v !== 'string')) {
throw new TypeError('Require extraJVMArgs be all string!')
}
cmd.push(...options.extraJVMArgs)
} else {
// if options object already has `maxMemory` property, exclude the "-Xmx2G" option from the default extra jvm args
if (options.maxMemory) {
cmd.push(...DEFAULT_EXTRA_JVM_ARGS.filter((v) => v !== '-Xmx2G'))
} else {
cmd.push(...DEFAULT_EXTRA_JVM_ARGS)
}
}
cmd.push(version.mainClass)
const assetsDir = join(resourcePath, 'assets')
const resolution = options.resolution
const versionName = options.versionName || version.id
const versionType = options.versionType || version.type
const mcOptions = {
version_name: versionName,
version_type: versionType,
assets_root: assetsDir,
game_assets: join(assetsDir, 'virtual', version.assets),
assets_index_name: options.useHashAssetsIndex ? version.assetIndex?.sha1 ?? version.assets : version.assets,
auth_session: accessToken,
game_directory: gamePath,
auth_player_name: name,
auth_uuid: id,
auth_access_token: accessToken,
user_properties: JSON.stringify(properties),
user_type: userType,
resolution_width: -1,
resolution_height: -1,
...featureValues,
}
if (resolution) {
mcOptions.resolution_width = resolution.width
mcOptions.resolution_height = resolution.height
}
cmd.push(...gameArguments.map((arg) => format(arg, mcOptions)))
if (options.extraMCArgs) {
cmd.push(...options.extraMCArgs)
}
if (options.server) {
cmd.push('--server', options.server.ip)
if (options.server.port) {
cmd.push('--port', options.server.port.toString())
}
}
if (options.resolution && !cmd.find((a) => a === '--width')) {
if (options.resolution.fullscreen) {
cmd.push('--fullscreen')
} else {
if (options.resolution.height) {
cmd.push('--height', options.resolution.height.toString())
}
if (options.resolution.width) {
cmd.push('--width', options.resolution.width.toString())
}
}
}
unshiftPrependCommand(cmd, options.prependCommand)
return cmd
}
/**
* Truely normalize the launch argument.
*/
function normalizeArguments(args: Version.LaunchArgument[], platform: Platform, features: EnabledFeatures): string[] {
return args.map((arg) => {
if (typeof arg === 'string') {
return arg
}
if (!Version.checkAllowed(arg.rules || [], platform, Object.keys(features))) {
return ''
}
return arg.value
}).reduce<string[]>((result, cur) => {
if (cur instanceof Array) {
result.push(...cur)
} else if (cur) {
result.push(cur)
}
return result
}, [])
}