ogi-addon 1.9.3 → 1.9.5

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.
Files changed (58) hide show
  1. package/build/Configuration-CdRZbO6z.d.mts +21 -0
  2. package/build/Configuration-WeOm-F0_.d.cts +21 -0
  3. package/build/ConfigurationBuilder-BSuJ4rSI.cjs +302 -0
  4. package/build/ConfigurationBuilder-BSuJ4rSI.cjs.map +1 -0
  5. package/build/ConfigurationBuilder-BbZDA_xx.d.mts +132 -0
  6. package/build/ConfigurationBuilder-CfHLKMTO.d.cts +132 -0
  7. package/build/EventResponse-CQhmdz3C.d.mts +430 -0
  8. package/build/EventResponse-D1c-Df5W.d.cts +430 -0
  9. package/build/EventResponse.cjs +55 -79
  10. package/build/EventResponse.cjs.map +1 -1
  11. package/build/EventResponse.d.cts +2 -45
  12. package/build/EventResponse.d.mts +2 -0
  13. package/build/EventResponse.mjs +58 -0
  14. package/build/EventResponse.mjs.map +1 -0
  15. package/build/SearchEngine-CRQWXfo6.d.mts +22 -0
  16. package/build/SearchEngine-DBSUNM4A.d.cts +22 -0
  17. package/build/SearchEngine.cjs +0 -19
  18. package/build/SearchEngine.d.cts +2 -20
  19. package/build/SearchEngine.d.mts +2 -0
  20. package/build/SearchEngine.mjs +1 -0
  21. package/build/config/Configuration.cjs +56 -370
  22. package/build/config/Configuration.cjs.map +1 -1
  23. package/build/config/Configuration.d.cts +3 -20
  24. package/build/config/Configuration.d.mts +3 -0
  25. package/build/config/Configuration.mjs +52 -0
  26. package/build/config/Configuration.mjs.map +1 -0
  27. package/build/config/ConfigurationBuilder.cjs +9 -292
  28. package/build/config/ConfigurationBuilder.d.cts +2 -130
  29. package/build/config/ConfigurationBuilder.d.mts +2 -0
  30. package/build/config/ConfigurationBuilder.mjs +221 -0
  31. package/build/config/ConfigurationBuilder.mjs.map +1 -0
  32. package/build/main.cjs +510 -1074
  33. package/build/main.cjs.map +1 -1
  34. package/build/main.d.cts +5 -387
  35. package/build/main.d.mts +5 -0
  36. package/build/main.mjs +510 -0
  37. package/build/main.mjs.map +1 -0
  38. package/package.json +9 -9
  39. package/src/config/Configuration.ts +18 -7
  40. package/src/main.ts +4 -3
  41. package/{tsup.config.js → tsdown.config.js} +2 -1
  42. package/build/EventResponse.d.ts +0 -45
  43. package/build/EventResponse.js +0 -62
  44. package/build/EventResponse.js.map +0 -1
  45. package/build/SearchEngine.cjs.map +0 -1
  46. package/build/SearchEngine.d.ts +0 -20
  47. package/build/SearchEngine.js +0 -1
  48. package/build/SearchEngine.js.map +0 -1
  49. package/build/config/Configuration.d.ts +0 -20
  50. package/build/config/Configuration.js +0 -329
  51. package/build/config/Configuration.js.map +0 -1
  52. package/build/config/ConfigurationBuilder.cjs.map +0 -1
  53. package/build/config/ConfigurationBuilder.d.ts +0 -130
  54. package/build/config/ConfigurationBuilder.js +0 -251
  55. package/build/config/ConfigurationBuilder.js.map +0 -1
  56. package/build/main.d.ts +0 -387
  57. package/build/main.js +0 -1045
  58. package/build/main.js.map +0 -1
package/build/main.js DELETED
@@ -1,1045 +0,0 @@
1
- // src/main.ts
2
- import ws from "ws";
3
- import events from "node:events";
4
-
5
- // src/config/ConfigurationBuilder.ts
6
- import z, { ZodError } from "zod";
7
- var configValidation = z.object({
8
- name: z.string().min(1),
9
- displayName: z.string().min(1),
10
- description: z.string().min(1)
11
- });
12
- var ConfigurationBuilder = class {
13
- options = [];
14
- /**
15
- * Add a number option to the configuration builder and return the builder for chaining. You must provide a name, display name, and description for the option.
16
- * @param option { (option: NumberOption) => NumberOption }
17
- * @returns
18
- */
19
- addNumberOption(option) {
20
- let newOption = new NumberOption();
21
- newOption = option(newOption);
22
- this.options.push(newOption);
23
- return this;
24
- }
25
- /**
26
- * Add a string option to the configuration builder and return the builder for chaining. You must provide a name, display name, and description for the option.
27
- * @param option { (option: StringOption) => StringOption }
28
- */
29
- addStringOption(option) {
30
- let newOption = new StringOption();
31
- newOption = option(newOption);
32
- this.options.push(newOption);
33
- return this;
34
- }
35
- /**
36
- * Add a boolean option to the configuration builder and return the builder for chaining. You must provide a name, display name, and description for the option.
37
- * @param option { (option: BooleanOption) => BooleanOption }
38
- */
39
- addBooleanOption(option) {
40
- let newOption = new BooleanOption();
41
- newOption = option(newOption);
42
- this.options.push(newOption);
43
- return this;
44
- }
45
- build(includeFunctions) {
46
- let config = {};
47
- this.options.forEach((option) => {
48
- if (!includeFunctions) {
49
- option = JSON.parse(JSON.stringify(option));
50
- const optionData = configValidation.safeParse(option);
51
- if (!optionData.success) {
52
- throw new ZodError(optionData.error.errors);
53
- }
54
- config[option.name] = option;
55
- } else {
56
- config[option.name] = option;
57
- }
58
- });
59
- return config;
60
- }
61
- };
62
- var ConfigurationOption = class {
63
- name = "";
64
- defaultValue = "";
65
- displayName = "";
66
- description = "";
67
- type = "unset";
68
- /**
69
- * Set the name of the option. **REQUIRED**
70
- * @param name {string} The name of the option. This is used to reference the option in the configuration file.
71
- */
72
- setName(name) {
73
- this.name = name;
74
- return this;
75
- }
76
- /**
77
- * Set the display name of the option. This is used to show the user a human readable version of what the option is. **REQUIRED**
78
- * @param displayName {string} The display name of the option.
79
- * @returns
80
- */
81
- setDisplayName(displayName) {
82
- this.displayName = displayName;
83
- return this;
84
- }
85
- /**
86
- * Set the description of the option. This is to show the user a brief description of what this option does. **REQUIRED**
87
- * @param description {string} The description of the option.
88
- * @returns
89
- */
90
- setDescription(description) {
91
- this.description = description;
92
- return this;
93
- }
94
- /**
95
- * Validation code for the option. This is called when the user provides input to the option. If the validation fails, the user will be prompted to provide input again.
96
- * @param input {unknown} The input to validate
97
- */
98
- validate(input) {
99
- throw new Error("Validation code not implemented. Value: " + input);
100
- }
101
- };
102
- var StringOption = class extends ConfigurationOption {
103
- allowedValues = [];
104
- minTextLength = 0;
105
- maxTextLength = Number.MAX_SAFE_INTEGER;
106
- defaultValue = "";
107
- inputType = "text";
108
- type = "string";
109
- /**
110
- * Set the allowed values for the string. If the array is empty, any value is allowed. When provided, the client will act like this option is a dropdown.
111
- * @param allowedValues {string[]} An array of allowed values for the string. If the array is empty, any value is allowed.
112
- */
113
- setAllowedValues(allowedValues) {
114
- this.allowedValues = allowedValues;
115
- return this;
116
- }
117
- /**
118
- * Set the default value for the string. This value will be used if the user does not provide a value. **HIGHLY RECOMMENDED**
119
- * @param defaultValue {string} The default value for the string.
120
- */
121
- setDefaultValue(defaultValue) {
122
- this.defaultValue = defaultValue;
123
- return this;
124
- }
125
- /**
126
- * Set the minimum text length for the string. If the user provides a string that is less than this value, the validation will fail.
127
- * @param minTextLength {number} The minimum text length for the string.
128
- */
129
- setMinTextLength(minTextLength) {
130
- this.minTextLength = minTextLength;
131
- return this;
132
- }
133
- /**
134
- * Set the maximum text length for the string. If the user provides a string that is greater than this value, the validation will fail.
135
- * @param maxTextLength {number} The maximum text length for the string.
136
- */
137
- setMaxTextLength(maxTextLength) {
138
- this.maxTextLength = maxTextLength;
139
- return this;
140
- }
141
- /**
142
- * Set the input type for the string. This will change how the client renders the input.
143
- * @param inputType {'text' | 'file' | 'password' | 'folder'} The input type for the string.
144
- */
145
- setInputType(inputType) {
146
- this.inputType = inputType;
147
- return this;
148
- }
149
- validate(input) {
150
- if (typeof input !== "string") {
151
- return [false, "Input is not a string"];
152
- }
153
- if (this.allowedValues.length === 0 && input.length !== 0)
154
- return [true, ""];
155
- if (input.length < this.minTextLength || input.length > this.maxTextLength) {
156
- return [
157
- false,
158
- "Input is not within the text length " + this.minTextLength + " and " + this.maxTextLength + " characters (currently " + input.length + " characters)"
159
- ];
160
- }
161
- return [
162
- this.allowedValues.includes(input),
163
- "Input is not an allowed value"
164
- ];
165
- }
166
- };
167
- var NumberOption = class extends ConfigurationOption {
168
- min = 0;
169
- max = Number.MAX_SAFE_INTEGER;
170
- defaultValue = 0;
171
- type = "number";
172
- inputType = "number";
173
- /**
174
- * Set the minimum value for the number. If the user provides a number that is less than this value, the validation will fail.
175
- * @param min {number} The minimum value for the number.
176
- */
177
- setMin(min) {
178
- this.min = min;
179
- return this;
180
- }
181
- /**
182
- * Set the input type for the number. This will change how the client renders the input.
183
- * @param type {'range' | 'number'} The input type for the number.
184
- */
185
- setInputType(type) {
186
- this.inputType = type;
187
- return this;
188
- }
189
- /**
190
- * Set the maximum value for the number. If the user provides a number that is greater than this value, the validation will fail.
191
- * @param max {number} The maximum value for the number.
192
- */
193
- setMax(max) {
194
- this.max = max;
195
- return this;
196
- }
197
- /**
198
- * Set the default value for the number. This value will be used if the user does not provide a value. **HIGHLY RECOMMENDED**
199
- * @param defaultValue {number} The default value for the number.
200
- */
201
- setDefaultValue(defaultValue) {
202
- this.defaultValue = defaultValue;
203
- return this;
204
- }
205
- validate(input) {
206
- if (isNaN(Number(input))) {
207
- return [false, "Input is not a number"];
208
- }
209
- if (Number(input) < this.min || Number(input) > this.max) {
210
- return [
211
- false,
212
- "Input is not within the range of " + this.min + " and " + this.max
213
- ];
214
- }
215
- return [true, ""];
216
- }
217
- };
218
- var BooleanOption = class extends ConfigurationOption {
219
- type = "boolean";
220
- defaultValue = false;
221
- /**
222
- * Set the default value for the boolean. This value will be used if the user does not provide a value. **HIGHLY RECOMMENDED**
223
- * @param defaultValue {boolean} The default value for the boolean.
224
- */
225
- setDefaultValue(defaultValue) {
226
- this.defaultValue = defaultValue;
227
- return this;
228
- }
229
- validate(input) {
230
- if (typeof input !== "boolean") {
231
- return [false, "Input is not a boolean"];
232
- }
233
- return [true, ""];
234
- }
235
- };
236
-
237
- // src/config/Configuration.ts
238
- var Configuration = class {
239
- storedConfigTemplate;
240
- definiteConfig = {};
241
- constructor(configTemplate) {
242
- this.storedConfigTemplate = configTemplate;
243
- }
244
- updateConfig(config, validate = true) {
245
- this.definiteConfig = config;
246
- if (validate) {
247
- const result = this.validateConfig();
248
- return result;
249
- }
250
- return [true, {}];
251
- }
252
- // provides falsey or truthy value, and an error message if falsey
253
- validateConfig() {
254
- const erroredKeys = /* @__PURE__ */ new Map();
255
- for (const key in this.storedConfigTemplate) {
256
- if (this.definiteConfig[key] === null || this.definiteConfig[key] === void 0) {
257
- console.warn(
258
- "Option " + key + " is not defined. Using default value Value: " + this.storedConfigTemplate[key].defaultValue
259
- );
260
- this.definiteConfig[key] = this.storedConfigTemplate[key].defaultValue;
261
- }
262
- if (this.storedConfigTemplate[key].type !== typeof this.definiteConfig[key]) {
263
- throw new Error("Option " + key + " is not of the correct type");
264
- }
265
- const result = this.storedConfigTemplate[key].validate(
266
- this.definiteConfig[key]
267
- );
268
- if (!result[0]) {
269
- erroredKeys.set(key, result[1]);
270
- }
271
- }
272
- for (const key in this.definiteConfig) {
273
- if (this.storedConfigTemplate[key] === void 0) {
274
- delete this.definiteConfig[key];
275
- console.warn(
276
- "Option " + key + " is not defined in the configuration template. Removing from config."
277
- );
278
- }
279
- }
280
- if (erroredKeys.size > 0) {
281
- return [false, Object.fromEntries(erroredKeys)];
282
- }
283
- return [true, Object.fromEntries(erroredKeys)];
284
- }
285
- getStringValue(optionName) {
286
- if (!this.definiteConfig[optionName] === null) {
287
- throw new Error("Option " + optionName + " is not defined");
288
- }
289
- if (typeof this.definiteConfig[optionName] !== "string") {
290
- throw new Error("Option " + optionName + " is not a string");
291
- }
292
- return this.definiteConfig[optionName];
293
- }
294
- getNumberValue(optionName) {
295
- if (!this.definiteConfig[optionName] === null) {
296
- throw new Error("Option " + optionName + " is not defined");
297
- }
298
- if (typeof this.definiteConfig[optionName] !== "number") {
299
- throw new Error("Option " + optionName + " is not a number");
300
- }
301
- return this.definiteConfig[optionName];
302
- }
303
- getBooleanValue(optionName) {
304
- if (this.definiteConfig[optionName] === null) {
305
- throw new Error("Option " + optionName + " is not defined");
306
- }
307
- if (typeof this.definiteConfig[optionName] !== "boolean") {
308
- throw new Error("Option " + optionName + " is not a boolean");
309
- }
310
- return this.definiteConfig[optionName];
311
- }
312
- };
313
-
314
- // src/EventResponse.ts
315
- var EventResponse = class {
316
- data = void 0;
317
- deffered = false;
318
- resolved = false;
319
- progress = 0;
320
- logs = [];
321
- failed = void 0;
322
- onInputAsked;
323
- constructor(onInputAsked) {
324
- this.onInputAsked = onInputAsked;
325
- }
326
- defer(promise) {
327
- this.deffered = true;
328
- if (promise) {
329
- promise();
330
- }
331
- }
332
- /**
333
- * Resolve the event with data. This acts like a promise resolve, and will stop the event from being processed further. **You must always call this method when you are done with the event.**
334
- * @param data {T}
335
- */
336
- resolve(data) {
337
- this.resolved = true;
338
- this.data = data;
339
- }
340
- /**
341
- * Completes the event and resolves it, but does not return any data. **You must always call this method when you are done with the event.**
342
- */
343
- complete() {
344
- this.resolved = true;
345
- }
346
- fail(message) {
347
- this.resolved = true;
348
- this.failed = message;
349
- }
350
- /**
351
- * Logs a message to the event. This is useful for debugging and logging information to the user.
352
- * @param message {string}
353
- */
354
- log(message) {
355
- this.logs.push(message);
356
- }
357
- /**
358
- * Send a screen to the client to ask for input. Use the `ConfigurationBuilder` system to build the screen. Once sent to the user, the addon cannot change the screen.
359
- * @async
360
- * @param name {string}
361
- * @param description {string}
362
- * @param screen {ConfigurationBuilder}
363
- * @returns {Promise<{ [key: string]: boolean | string | number }>}
364
- */
365
- async askForInput(name, description, screen) {
366
- if (!this.onInputAsked) {
367
- throw new Error("No input asked callback");
368
- }
369
- return await this.onInputAsked(screen, name, description);
370
- }
371
- };
372
-
373
- // src/main.ts
374
- import Fuse from "fuse.js";
375
-
376
- // package.json
377
- var package_default = {
378
- name: "ogi-addon",
379
- module: "./build/main.js",
380
- type: "module",
381
- main: "./build/main.cjs",
382
- version: "1.9.3",
383
- exports: {
384
- ".": {
385
- import: {
386
- default: "./build/main.js",
387
- types: "./build/main.d.ts"
388
- },
389
- require: {
390
- default: "./build/main.cjs",
391
- types: "./build/main.d.cts"
392
- }
393
- },
394
- "./config": {
395
- import: {
396
- default: "./build/config/Configuration.js",
397
- types: "./build/config/Configuration.d.ts"
398
- },
399
- require: {
400
- default: "./build/config/Configuration.cjs",
401
- types: "./build/config/Configuration.d.cts"
402
- }
403
- }
404
- },
405
- typings: "./build/main.d.ts",
406
- author: {
407
- name: "Nat3z",
408
- email: "me@nat3z.com",
409
- url: "https://nat3z.com/"
410
- },
411
- repository: {
412
- type: "git",
413
- url: "https://github.com/Nat3z/OpenGameInstaller",
414
- directory: "packages/ogi-addon"
415
- },
416
- dependencies: {
417
- "fuse.js": "^7.1.0",
418
- ws: "^8.4.0",
419
- zod: "^3.23.8"
420
- },
421
- scripts: {
422
- "auto-build": "tsc -w",
423
- build: "tsup --config tsup.config.js",
424
- release: "bun run build && npm publish",
425
- "release-beta": "bun run build && npm publish --tag future"
426
- },
427
- devDependencies: {
428
- "@types/minimatch": "^6.0.0",
429
- "@types/node": "^20.14.12",
430
- "@types/ws": "^8.4.0",
431
- prettier: "^3.6.0",
432
- tsup: "^8.2.3",
433
- typescript: "^5.0.0"
434
- }
435
- };
436
-
437
- // src/main.ts
438
- import { exec, spawn } from "node:child_process";
439
- import fs from "node:fs";
440
- import { z as z2 } from "zod";
441
- var defaultPort = 7654;
442
- var VERSION = package_default.version;
443
- var OGIAddon = class {
444
- eventEmitter = new events.EventEmitter();
445
- addonWSListener;
446
- addonInfo;
447
- config = new Configuration({});
448
- eventsAvailable = [];
449
- registeredConnectEvent = false;
450
- constructor(addonInfo) {
451
- this.addonInfo = addonInfo;
452
- this.addonWSListener = new OGIAddonWSListener(this, this.eventEmitter);
453
- }
454
- /**
455
- * Register an event listener for the addon. (See EventListenerTypes)
456
- * @param event {OGIAddonEvent}
457
- * @param listener {EventListenerTypes[OGIAddonEvent]}
458
- */
459
- on(event, listener) {
460
- this.eventEmitter.on(event, listener);
461
- this.eventsAvailable.push(event);
462
- if (!this.registeredConnectEvent) {
463
- this.addonWSListener.eventEmitter.once("connect", () => {
464
- this.addonWSListener.send("flag", {
465
- flag: "events-available",
466
- value: this.eventsAvailable
467
- });
468
- });
469
- this.registeredConnectEvent = true;
470
- }
471
- }
472
- emit(event, ...args) {
473
- this.eventEmitter.emit(event, ...args);
474
- }
475
- /**
476
- * Notify the client using a notification. Provide the type of notification, the message, and an ID.
477
- * @param notification {Notification}
478
- */
479
- notify(notification) {
480
- this.addonWSListener.send("notification", [notification]);
481
- }
482
- /**
483
- * Get the app details for a given appID and storefront.
484
- * @param appID {number}
485
- * @param storefront {string}
486
- * @returns {Promise<StoreData>}
487
- */
488
- async getAppDetails(appID, storefront) {
489
- const id = this.addonWSListener.send("get-app-details", {
490
- appID,
491
- storefront
492
- });
493
- return await this.addonWSListener.waitForResponseFromServer(id);
494
- }
495
- async searchGame(query, storefront) {
496
- const id = this.addonWSListener.send("search-app-name", {
497
- query,
498
- storefront
499
- });
500
- return await this.addonWSListener.waitForResponseFromServer(id);
501
- }
502
- /**
503
- * Notify the OGI Addon Server that you are performing a background task. This can be used to help users understand what is happening in the background.
504
- * @param id {string}
505
- * @param progress {number}
506
- * @param logs {string[]}
507
- */
508
- async task() {
509
- const id = Math.random().toString(36).substring(7);
510
- const progress = 0;
511
- const logs = [];
512
- const task = new CustomTask(this.addonWSListener, id, progress, logs);
513
- this.addonWSListener.send("task-update", {
514
- id,
515
- progress,
516
- logs,
517
- finished: false,
518
- failed: void 0
519
- });
520
- return task;
521
- }
522
- /**
523
- * Extract a file using 7-Zip on Windows, unzip on Linux/Mac.
524
- * @param path {string}
525
- * @param outputPath {string}
526
- * @param type {'unrar' | 'unzip'}
527
- * @returns {Promise<void>}
528
- */
529
- async extractFile(path, outputPath, type) {
530
- return new Promise((resolve, reject) => {
531
- if (!fs.existsSync(outputPath)) {
532
- fs.mkdirSync(outputPath, { recursive: true });
533
- }
534
- if (type === "unzip") {
535
- if (process.platform === "win32") {
536
- const s7ZipPath = '"C:\\Program Files\\7-Zip\\7z.exe"';
537
- exec(
538
- `${s7ZipPath} x "${path}" -o"${outputPath}"`,
539
- (err, stdout, stderr) => {
540
- if (err) {
541
- console.error(err);
542
- console.log(stderr);
543
- reject(new Error("Failed to extract ZIP file"));
544
- return;
545
- }
546
- console.log(stdout);
547
- console.log(stderr);
548
- resolve();
549
- }
550
- );
551
- } else {
552
- const unzipProcess = spawn(
553
- "unzip",
554
- [
555
- "-o",
556
- // overwrite files without prompting
557
- path,
558
- "-d",
559
- // specify output directory
560
- outputPath
561
- ],
562
- {
563
- env: {
564
- ...process.env,
565
- UNZIP_DISABLE_ZIPBOMB_DETECTION: "TRUE"
566
- }
567
- }
568
- );
569
- unzipProcess.stdout.on("data", (data) => {
570
- console.log(`[unzip stdout]: ${data}`);
571
- });
572
- unzipProcess.stderr.on("data", (data) => {
573
- console.error(`[unzip stderr]: ${data}`);
574
- });
575
- unzipProcess.on("close", (code) => {
576
- if (code !== 0) {
577
- console.error(`unzip process exited with code ${code}`);
578
- reject(new Error("Failed to extract ZIP file"));
579
- return;
580
- }
581
- resolve();
582
- });
583
- }
584
- } else if (type === "unrar") {
585
- if (process.platform === "win32") {
586
- const s7ZipPath = '"C:\\Program Files\\7-Zip\\7z.exe"';
587
- exec(
588
- `${s7ZipPath} x "${path}" -o"${outputPath}"`,
589
- (err, stdout, stderr) => {
590
- if (err) {
591
- console.error(err);
592
- console.log(stderr);
593
- reject(new Error("Failed to extract RAR file"));
594
- return;
595
- }
596
- console.log(stdout);
597
- console.log(stderr);
598
- resolve();
599
- }
600
- );
601
- } else {
602
- const unrarProcess = spawn("unrar", ["x", "-y", path, outputPath]);
603
- unrarProcess.stdout.on("data", (data) => {
604
- console.log(`[unrar stdout]: ${data}`);
605
- });
606
- unrarProcess.stderr.on("data", (data) => {
607
- console.error(`[unrar stderr]: ${data}`);
608
- });
609
- unrarProcess.on("close", (code) => {
610
- if (code !== 0) {
611
- console.error(`unrar process exited with code ${code}`);
612
- reject(new Error("Failed to extract RAR file"));
613
- return;
614
- }
615
- resolve();
616
- });
617
- }
618
- } else {
619
- reject(new Error("Unknown extraction type"));
620
- }
621
- });
622
- }
623
- };
624
- var CustomTask = class {
625
- id;
626
- progress;
627
- logs;
628
- finished = false;
629
- ws;
630
- failed = void 0;
631
- constructor(ws2, id, progress, logs) {
632
- this.id = id;
633
- this.progress = progress;
634
- this.logs = logs;
635
- this.ws = ws2;
636
- }
637
- log(log) {
638
- this.logs.push(log);
639
- this.update();
640
- }
641
- finish() {
642
- this.finished = true;
643
- this.update();
644
- }
645
- fail(message) {
646
- this.failed = message;
647
- this.update();
648
- }
649
- setProgress(progress) {
650
- this.progress = progress;
651
- this.update();
652
- }
653
- update() {
654
- this.ws.send("task-update", {
655
- id: this.id,
656
- progress: this.progress,
657
- logs: this.logs,
658
- finished: this.finished,
659
- failed: this.failed
660
- });
661
- }
662
- };
663
- var SearchTool = class {
664
- fuse;
665
- constructor(items, keys, options = {
666
- threshold: 0.3,
667
- includeScore: true
668
- }) {
669
- this.fuse = new Fuse(items, {
670
- keys,
671
- ...options
672
- });
673
- }
674
- search(query, limit = 10) {
675
- return this.fuse.search(query).slice(0, limit).map((result) => result.item);
676
- }
677
- addItems(items) {
678
- items.map((item) => this.fuse.add(item));
679
- }
680
- };
681
- var ZodLibraryInfo = z2.object({
682
- name: z2.string(),
683
- version: z2.string(),
684
- cwd: z2.string(),
685
- appID: z2.number(),
686
- launchExecutable: z2.string(),
687
- launchArguments: z2.string().optional(),
688
- capsuleImage: z2.string(),
689
- storefront: z2.string(),
690
- addonsource: z2.string(),
691
- coverImage: z2.string(),
692
- titleImage: z2.string().optional()
693
- });
694
- var OGIAddonWSListener = class {
695
- socket;
696
- eventEmitter;
697
- addon;
698
- constructor(ogiAddon, eventEmitter) {
699
- if (process.argv[process.argv.length - 1].split("=")[0] !== "--addonSecret") {
700
- throw new Error(
701
- "No secret provided. This usually happens because the addon was not started by the OGI Addon Server."
702
- );
703
- }
704
- this.addon = ogiAddon;
705
- this.eventEmitter = eventEmitter;
706
- this.socket = new ws("ws://localhost:" + defaultPort);
707
- this.socket.on("open", () => {
708
- console.log("Connected to OGI Addon Server");
709
- console.log("OGI Addon Server Version:", VERSION);
710
- this.send("authenticate", {
711
- ...this.addon.addonInfo,
712
- secret: process.argv[process.argv.length - 1].split("=")[1],
713
- ogiVersion: VERSION
714
- });
715
- let configBuilder = new ConfigurationBuilder();
716
- this.eventEmitter.emit("configure", configBuilder);
717
- this.send("configure", configBuilder.build(false));
718
- this.addon.config = new Configuration(configBuilder.build(true));
719
- const configListener = (event) => {
720
- if (event === void 0) return;
721
- let data;
722
- if (typeof event === "string") {
723
- data = event;
724
- } else if (event instanceof Buffer) {
725
- data = event.toString();
726
- } else if (event && typeof event.data === "string") {
727
- data = event.data;
728
- } else if (event && event.data instanceof Buffer) {
729
- data = event.data.toString();
730
- } else {
731
- data = event.toString();
732
- }
733
- const message = JSON.parse(data);
734
- if (message.event === "config-update") {
735
- console.log("Config update received");
736
- this.socket.off("message", configListener);
737
- this.eventEmitter.emit(
738
- "connect",
739
- new EventResponse((screen, name, description) => {
740
- return this.userInputAsked(
741
- screen,
742
- name,
743
- description,
744
- this.socket
745
- );
746
- })
747
- );
748
- }
749
- };
750
- this.socket.on("message", configListener);
751
- });
752
- this.socket.on("error", (error) => {
753
- if (error.message.includes("Failed to connect")) {
754
- throw new Error(
755
- "OGI Addon Server is not running/is unreachable. Please start the server and try again."
756
- );
757
- }
758
- console.error("An error occurred:", error);
759
- });
760
- this.socket.on("close", (code, reason) => {
761
- if (code === 1008) {
762
- console.error("Authentication failed:", reason);
763
- return;
764
- }
765
- this.eventEmitter.emit("disconnect", reason);
766
- console.log("Disconnected from OGI Addon Server");
767
- console.error(reason.toString());
768
- this.eventEmitter.emit("exit");
769
- this.socket.close();
770
- });
771
- this.registerMessageReceiver();
772
- }
773
- async userInputAsked(configBuilt, name, description, socket) {
774
- const config = configBuilt.build(false);
775
- const id = Math.random().toString(36).substring(7);
776
- if (!socket) {
777
- return {};
778
- }
779
- socket.send(
780
- JSON.stringify({
781
- event: "input-asked",
782
- args: {
783
- config,
784
- name,
785
- description
786
- },
787
- id
788
- })
789
- );
790
- return await this.waitForResponseFromServer(id);
791
- }
792
- registerMessageReceiver() {
793
- this.socket.on("message", async (data) => {
794
- const message = JSON.parse(data);
795
- switch (message.event) {
796
- case "config-update":
797
- const result = this.addon.config.updateConfig(message.args);
798
- if (!result[0]) {
799
- this.respondToMessage(
800
- message.id,
801
- {
802
- success: false,
803
- error: result[1]
804
- },
805
- void 0
806
- );
807
- } else {
808
- this.respondToMessage(message.id, { success: true }, void 0);
809
- }
810
- break;
811
- case "search":
812
- let searchResultEvent = new EventResponse(
813
- (screen, name, description) => this.userInputAsked(screen, name, description, this.socket)
814
- );
815
- this.eventEmitter.emit("search", message.args, searchResultEvent);
816
- const searchResult = await this.waitForEventToRespond(searchResultEvent);
817
- this.respondToMessage(
818
- message.id,
819
- searchResult.data,
820
- searchResultEvent
821
- );
822
- break;
823
- case "setup": {
824
- let setupEvent = new EventResponse(
825
- (screen, name, description) => this.userInputAsked(screen, name, description, this.socket)
826
- );
827
- this.eventEmitter.emit("setup", message.args, setupEvent);
828
- const interval = setInterval(() => {
829
- if (setupEvent.resolved) {
830
- clearInterval(interval);
831
- return;
832
- }
833
- this.send("defer-update", {
834
- logs: setupEvent.logs,
835
- deferID: message.args.deferID,
836
- progress: setupEvent.progress,
837
- failed: setupEvent.failed
838
- });
839
- }, 100);
840
- const setupResult = await this.waitForEventToRespond(setupEvent);
841
- this.respondToMessage(message.id, setupResult.data, setupEvent);
842
- break;
843
- }
844
- case "library-search":
845
- let librarySearchEvent = new EventResponse(
846
- (screen, name, description) => this.userInputAsked(screen, name, description, this.socket)
847
- );
848
- this.eventEmitter.emit(
849
- "library-search",
850
- message.args,
851
- librarySearchEvent
852
- );
853
- const librarySearchResult = await this.waitForEventToRespond(librarySearchEvent);
854
- this.respondToMessage(
855
- message.id,
856
- librarySearchResult.data,
857
- librarySearchEvent
858
- );
859
- break;
860
- case "game-details":
861
- let gameDetailsEvent = new EventResponse(
862
- (screen, name, description) => this.userInputAsked(screen, name, description, this.socket)
863
- );
864
- if (this.eventEmitter.listenerCount("game-details") === 0) {
865
- this.respondToMessage(
866
- message.id,
867
- {
868
- error: "No event listener for game-details"
869
- },
870
- gameDetailsEvent
871
- );
872
- break;
873
- }
874
- this.eventEmitter.emit(
875
- "game-details",
876
- message.args,
877
- gameDetailsEvent
878
- );
879
- const gameDetailsResult = await this.waitForEventToRespond(gameDetailsEvent);
880
- this.respondToMessage(
881
- message.id,
882
- gameDetailsResult.data,
883
- gameDetailsEvent
884
- );
885
- break;
886
- case "check-for-updates":
887
- let checkForUpdatesEvent = new EventResponse(
888
- (screen, name, description) => this.userInputAsked(screen, name, description, this.socket)
889
- );
890
- this.eventEmitter.emit(
891
- "check-for-updates",
892
- message.args,
893
- checkForUpdatesEvent
894
- );
895
- const checkForUpdatesResult = await this.waitForEventToRespond(checkForUpdatesEvent);
896
- this.respondToMessage(
897
- message.id,
898
- checkForUpdatesResult.data,
899
- checkForUpdatesEvent
900
- );
901
- break;
902
- case "request-dl":
903
- let requestDLEvent = new EventResponse(
904
- (screen, name, description) => this.userInputAsked(screen, name, description, this.socket)
905
- );
906
- if (this.eventEmitter.listenerCount("request-dl") === 0) {
907
- this.respondToMessage(
908
- message.id,
909
- {
910
- error: "No event listener for request-dl"
911
- },
912
- requestDLEvent
913
- );
914
- break;
915
- }
916
- this.eventEmitter.emit(
917
- "request-dl",
918
- message.args.appID,
919
- message.args.info,
920
- requestDLEvent
921
- );
922
- const requestDLResult = await this.waitForEventToRespond(requestDLEvent);
923
- if (requestDLEvent.failed) {
924
- this.respondToMessage(message.id, void 0, requestDLEvent);
925
- break;
926
- }
927
- if (requestDLEvent.data === void 0 || requestDLEvent.data?.downloadType === "request") {
928
- throw new Error(
929
- "Request DL event did not return a valid result. Please ensure that the event does not resolve with another `request` download type."
930
- );
931
- }
932
- this.respondToMessage(
933
- message.id,
934
- requestDLResult.data,
935
- requestDLEvent
936
- );
937
- break;
938
- case "catalog":
939
- let catalogEvent = new EventResponse();
940
- this.eventEmitter.emit("catalog", catalogEvent);
941
- const catalogResult = await this.waitForEventToRespond(catalogEvent);
942
- this.respondToMessage(message.id, catalogResult.data, catalogEvent);
943
- break;
944
- case "task-run": {
945
- let taskRunEvent = new EventResponse(
946
- (screen, name, description) => this.userInputAsked(screen, name, description, this.socket)
947
- );
948
- this.eventEmitter.emit("task-run", message.args, taskRunEvent);
949
- const interval = setInterval(() => {
950
- if (taskRunEvent.resolved) {
951
- clearInterval(interval);
952
- return;
953
- }
954
- this.send("defer-update", {
955
- logs: taskRunEvent.logs,
956
- deferID: message.args.deferID,
957
- progress: taskRunEvent.progress,
958
- failed: taskRunEvent.failed
959
- });
960
- }, 100);
961
- const taskRunResult = await this.waitForEventToRespond(taskRunEvent);
962
- this.respondToMessage(message.id, taskRunResult.data, taskRunEvent);
963
- break;
964
- }
965
- }
966
- });
967
- }
968
- waitForEventToRespond(event) {
969
- return new Promise((resolve, reject) => {
970
- const dataGet = setInterval(() => {
971
- if (event.resolved) {
972
- resolve(event);
973
- clearTimeout(timeout);
974
- }
975
- }, 5);
976
- const timeout = setTimeout(() => {
977
- if (event.deffered) {
978
- clearInterval(dataGet);
979
- const interval = setInterval(() => {
980
- if (event.resolved) {
981
- clearInterval(interval);
982
- resolve(event);
983
- }
984
- }, 100);
985
- } else {
986
- reject("Event did not respond in time");
987
- }
988
- }, 5e3);
989
- });
990
- }
991
- respondToMessage(messageID, response, originalEvent) {
992
- this.socket.send(
993
- JSON.stringify({
994
- event: "response",
995
- id: messageID,
996
- args: response,
997
- statusError: originalEvent ? originalEvent.failed : void 0
998
- })
999
- );
1000
- console.log("dispatched response to " + messageID);
1001
- }
1002
- waitForResponseFromServer(messageID) {
1003
- return new Promise((resolve) => {
1004
- const waiter = (data) => {
1005
- const message = JSON.parse(data);
1006
- if (message.event !== "response") {
1007
- this.socket.once("message", waiter);
1008
- return;
1009
- }
1010
- console.log("received response from " + messageID);
1011
- if (message.id === messageID) {
1012
- resolve(message.args);
1013
- } else {
1014
- this.socket.once("message", waiter);
1015
- }
1016
- };
1017
- this.socket.once("message", waiter);
1018
- });
1019
- }
1020
- send(event, args) {
1021
- const id = Math.random().toString(36).substring(7);
1022
- this.socket.send(
1023
- JSON.stringify({
1024
- event,
1025
- args,
1026
- id
1027
- })
1028
- );
1029
- return id;
1030
- }
1031
- close() {
1032
- this.socket.close();
1033
- }
1034
- };
1035
- export {
1036
- Configuration,
1037
- ConfigurationBuilder,
1038
- CustomTask,
1039
- EventResponse,
1040
- SearchTool,
1041
- VERSION,
1042
- ZodLibraryInfo,
1043
- OGIAddon as default
1044
- };
1045
- //# sourceMappingURL=main.js.map