@aifivem/lib 0.0.0-stage → 0.6.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/package.json +34 -4
- package/src/client/action.ts +38 -0
- package/src/client/adminWorld.ts +95 -0
- package/src/client/appearance.ts +29 -0
- package/src/client/areaFollower.ts +41 -0
- package/src/client/blip.ts +79 -0
- package/src/client/cache.ts +66 -0
- package/src/client/callback.ts +70 -0
- package/src/client/controls.ts +73 -0
- package/src/client/entities.ts +83 -0
- package/src/client/entity.ts +26 -0
- package/src/client/fuel.ts +18 -0
- package/src/client/gestures.ts +18 -0
- package/src/client/headshot.ts +26 -0
- package/src/client/hud.ts +24 -0
- package/src/client/index.ts +131 -0
- package/src/client/inventory.ts +117 -0
- package/src/client/keyHints.ts +13 -0
- package/src/client/keybind.ts +163 -0
- package/src/client/localPed.ts +169 -0
- package/src/client/location.ts +54 -0
- package/src/client/mdt.ts +10 -0
- package/src/client/medical.ts +28 -0
- package/src/client/membership.ts +41 -0
- package/src/client/menu/dialogs.ts +77 -0
- package/src/client/menu/minigames.ts +79 -0
- package/src/client/menu/requests.ts +65 -0
- package/src/client/modelScan/def.ts +29 -0
- package/src/client/modelScan/objectIndex.ts +41 -0
- package/src/client/modelScan/scan.ts +69 -0
- package/src/client/modelScan/scanner.ts +164 -0
- package/src/client/netEvent.ts +40 -0
- package/src/client/notify.ts +14 -0
- package/src/client/nuiScreen.ts +87 -0
- package/src/client/player/anim.ts +98 -0
- package/src/client/player/fade.ts +17 -0
- package/src/client/player/player.ts +80 -0
- package/src/client/player/teleport.ts +87 -0
- package/src/client/playerData.ts +83 -0
- package/src/client/players.ts +44 -0
- package/src/client/points/interact.ts +144 -0
- package/src/client/points/modelHost.ts +117 -0
- package/src/client/points/modelPoint.ts +181 -0
- package/src/client/points/point.ts +159 -0
- package/src/client/points/points.ts +170 -0
- package/src/client/points/targets/adapter.ts +40 -0
- package/src/client/points/targets/interactTarget.ts +45 -0
- package/src/client/points/targets/optionShape.ts +22 -0
- package/src/client/points/targets/oxTarget.ts +42 -0
- package/src/client/points/targets/qbTarget.ts +71 -0
- package/src/client/points/targets/targets.ts +20 -0
- package/src/client/preview.ts +51 -0
- package/src/client/progress.ts +132 -0
- package/src/client/prompt.ts +26 -0
- package/src/client/prop.ts +79 -0
- package/src/client/radial.ts +16 -0
- package/src/client/raycast.ts +48 -0
- package/src/client/scriptCamera.ts +167 -0
- package/src/client/seatbelt.ts +18 -0
- package/src/client/shot.ts +29 -0
- package/src/client/streaming.ts +91 -0
- package/src/client/tickLoop.ts +18 -0
- package/src/client/vehicleKeys.ts +14 -0
- package/src/client/vehicleProps.ts +107 -0
- package/src/client/vehicles.ts +46 -0
- package/src/client/waypoint.ts +10 -0
- package/src/client/world.ts +10 -0
- package/src/client/zoneEngine.ts +174 -0
- package/src/client/zones.ts +161 -0
- package/src/fivem/byResource.ts +146 -0
- package/src/fivem/callbackNames.ts +12 -0
- package/src/fivem/exports.ts +70 -0
- package/src/fivem/index.ts +13 -0
- package/src/fivem/locale.ts +57 -0
- package/src/fivem/playerData.ts +13 -0
- package/src/fivem/scheduler/every.ts +101 -0
- package/src/fivem/scheduler/group.ts +97 -0
- package/src/fivem/scheduler/scheduler.ts +77 -0
- package/src/fivem/state/entityState.ts +75 -0
- package/src/fivem/state/globalState.ts +80 -0
- package/src/fivem/state/mirror.ts +47 -0
- package/src/fivem/state/playerState.ts +60 -0
- package/src/server/admin/descriptions.ts +57 -0
- package/src/server/admin/edit.ts +127 -0
- package/src/server/admin/jsonSchema.ts +156 -0
- package/src/server/admin/panel.ts +167 -0
- package/src/server/admin/panelFiles.ts +128 -0
- package/src/server/admin/patch.ts +46 -0
- package/src/server/admin/validate.ts +147 -0
- package/src/server/appearance.ts +28 -0
- package/src/server/areaStream/areaStream.ts +141 -0
- package/src/server/areaStream/followers.ts +154 -0
- package/src/server/areaStream/grid.ts +74 -0
- package/src/server/areaStream/options.ts +16 -0
- package/src/server/banking.ts +15 -0
- package/src/server/bans.ts +47 -0
- package/src/server/billing.ts +20 -0
- package/src/server/buckets.ts +12 -0
- package/src/server/callback.ts +112 -0
- package/src/server/characters.ts +129 -0
- package/src/server/command/addCommand.ts +83 -0
- package/src/server/command/command.ts +116 -0
- package/src/server/command/commandSet.ts +74 -0
- package/src/server/dataFile.ts +81 -0
- package/src/server/database.ts +117 -0
- package/src/server/definitions.ts +65 -0
- package/src/server/dispatch.ts +13 -0
- package/src/server/doors.ts +15 -0
- package/src/server/ems.ts +15 -0
- package/src/server/fuel.ts +15 -0
- package/src/server/garages.ts +34 -0
- package/src/server/gate.ts +148 -0
- package/src/server/index.ts +165 -0
- package/src/server/inventory.ts +106 -0
- package/src/server/jobs.ts +42 -0
- package/src/server/log.ts +21 -0
- package/src/server/mdt.ts +12 -0
- package/src/server/medical.ts +16 -0
- package/src/server/minigameFor.ts +65 -0
- package/src/server/money.ts +70 -0
- package/src/server/netEntity.ts +19 -0
- package/src/server/netEvent.ts +58 -0
- package/src/server/notify.ts +17 -0
- package/src/server/online/mirror.ts +176 -0
- package/src/server/online/online.ts +190 -0
- package/src/server/pending.ts +70 -0
- package/src/server/phone.ts +22 -0
- package/src/server/players.ts +197 -0
- package/src/server/position.ts +31 -0
- package/src/server/primeTime.ts +7 -0
- package/src/server/prison.ts +15 -0
- package/src/server/progressFor.ts +62 -0
- package/src/server/proximity.ts +98 -0
- package/src/server/rateLimit.ts +53 -0
- package/src/server/state.ts +45 -0
- package/src/server/stress.ts +25 -0
- package/src/server/vehicle/nearby.ts +66 -0
- package/src/server/vehicle/plate.ts +14 -0
- package/src/server/vehicle/spawn.ts +125 -0
- package/src/server/vehicle/vehicleType.ts +50 -0
- package/src/server/vehicleKeys.ts +23 -0
- package/src/server/watchers.ts +46 -0
- package/src/server/world.ts +16 -0
- package/src/shared/access.ts +94 -0
- package/src/shared/action.ts +28 -0
- package/src/shared/blipStyle.ts +26 -0
- package/src/shared/clock.ts +22 -0
- package/src/shared/format.ts +36 -0
- package/src/shared/grid.ts +20 -0
- package/src/shared/index.ts +179 -0
- package/src/shared/lang.ts +39 -0
- package/src/shared/placePed.ts +96 -0
- package/src/shared/random.ts +11 -0
- package/src/shared/read.ts +60 -0
- package/src/shared/records.ts +148 -0
- package/src/shared/spec.ts +20 -0
- package/src/shared/strict.ts +70 -0
- package/src/shared/vec.ts +48 -0
- package/src/shared/vehicleProps.ts +138 -0
- package/src/shared/wait.ts +27 -0
- package/src/shared/zone.ts +144 -0
- package/README.md +0 -3
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_CALLBACK_TIMEOUT,
|
|
3
|
+
requestEvent,
|
|
4
|
+
responseEvent,
|
|
5
|
+
} from "../fivem/callbackNames";
|
|
6
|
+
import { createLogger } from "../shared";
|
|
7
|
+
import {
|
|
8
|
+
ClientGate,
|
|
9
|
+
type ClientInputOptions,
|
|
10
|
+
type ParsedInputOptions,
|
|
11
|
+
} from "./gate";
|
|
12
|
+
|
|
13
|
+
const log = createLogger(GetCurrentResourceName());
|
|
14
|
+
const resource = GetCurrentResourceName();
|
|
15
|
+
const REFUSED = Symbol("refused");
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Answers a client's `triggerServerCallback(name, ...)`. The call passes the same gate as `onClientEvent` (real
|
|
19
|
+
* player, rate 20/s by default, guards, `args` parser, optional lock); a refused call is answered with a failure,
|
|
20
|
+
* so the client's promise rejects at once. Forms as `onClientEvent`: `(name, handler, options?)` without arguments,
|
|
21
|
+
* `(name, { args, ... }, handler)` with them. The handler's return value (or resolved promise) is sent back.
|
|
22
|
+
*/
|
|
23
|
+
export function onClientCallback(
|
|
24
|
+
name: string,
|
|
25
|
+
handler: (source: number) => unknown,
|
|
26
|
+
options?: ClientInputOptions,
|
|
27
|
+
): void;
|
|
28
|
+
export function onClientCallback<const A extends readonly unknown[]>(
|
|
29
|
+
name: string,
|
|
30
|
+
options: ParsedInputOptions<A>,
|
|
31
|
+
handler: (source: number, ...args: A) => unknown,
|
|
32
|
+
): void;
|
|
33
|
+
export function onClientCallback(
|
|
34
|
+
name: string,
|
|
35
|
+
first: ((source: number) => unknown) | ParsedInputOptions<readonly unknown[]>,
|
|
36
|
+
second?:
|
|
37
|
+
| ClientInputOptions
|
|
38
|
+
| ((source: number, ...args: readonly unknown[]) => unknown),
|
|
39
|
+
): void {
|
|
40
|
+
const [handler, options] =
|
|
41
|
+
typeof first === "function"
|
|
42
|
+
? [first, (second ?? {}) as ClientInputOptions]
|
|
43
|
+
: [
|
|
44
|
+
second as (source: number, ...args: readonly unknown[]) => unknown,
|
|
45
|
+
first,
|
|
46
|
+
];
|
|
47
|
+
const gate = new ClientGate(name, options, 20);
|
|
48
|
+
|
|
49
|
+
onNet(
|
|
50
|
+
requestEvent(name),
|
|
51
|
+
async (caller: unknown, id: unknown, ...raw: unknown[]) => {
|
|
52
|
+
const source = Number(globalThis.source);
|
|
53
|
+
if (
|
|
54
|
+
typeof caller !== "string" ||
|
|
55
|
+
caller.length > 64 ||
|
|
56
|
+
typeof id !== "number"
|
|
57
|
+
)
|
|
58
|
+
return;
|
|
59
|
+
const args = gate.check(source, raw);
|
|
60
|
+
if (!args) return emitNet(responseEvent(caller), source, id, false, null);
|
|
61
|
+
try {
|
|
62
|
+
const result = await gate.run(source, REFUSED, () =>
|
|
63
|
+
handler(source, ...args),
|
|
64
|
+
);
|
|
65
|
+
if (result === REFUSED)
|
|
66
|
+
emitNet(responseEvent(caller), source, id, false, null);
|
|
67
|
+
else emitNet(responseEvent(caller), source, id, true, result ?? null);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
log.error(`callback ${name} failed for ${source}`, error);
|
|
70
|
+
emitNet(responseEvent(caller), source, id, false, null);
|
|
71
|
+
}
|
|
72
|
+
},
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface Pending {
|
|
77
|
+
source: number;
|
|
78
|
+
resolve: (value: unknown) => void;
|
|
79
|
+
reject: (error: Error) => void;
|
|
80
|
+
timer: ReturnType<typeof setTimeout>;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const pending = new Map<number, Pending>();
|
|
84
|
+
let nextId = 0;
|
|
85
|
+
|
|
86
|
+
onNet(responseEvent(resource), (id: unknown, ok: unknown, result: unknown) => {
|
|
87
|
+
const entry = typeof id === "number" ? pending.get(id) : undefined;
|
|
88
|
+
// Only the player we asked may answer.
|
|
89
|
+
if (!entry || entry.source !== Number(globalThis.source)) return;
|
|
90
|
+
pending.delete(id as number);
|
|
91
|
+
clearTimeout(entry.timer);
|
|
92
|
+
if (ok === true) entry.resolve(result);
|
|
93
|
+
else entry.reject(new Error("client callback failed"));
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
/** Asks one player's client (`onServerCallback(name, ...)` there) and resolves with its answer (unknown: parse it). */
|
|
97
|
+
export function triggerClientCallback(
|
|
98
|
+
name: string,
|
|
99
|
+
source: number,
|
|
100
|
+
args: unknown[] = [],
|
|
101
|
+
timeoutMs = DEFAULT_CALLBACK_TIMEOUT,
|
|
102
|
+
): Promise<unknown> {
|
|
103
|
+
const id = ++nextId;
|
|
104
|
+
return new Promise((resolve, reject) => {
|
|
105
|
+
const timer = setTimeout(() => {
|
|
106
|
+
pending.delete(id);
|
|
107
|
+
reject(new Error(`client callback ${name} timed out for ${source}`));
|
|
108
|
+
}, timeoutMs);
|
|
109
|
+
pending.set(id, { source, resolve, reject, timer });
|
|
110
|
+
emitNet(requestEvent(name), source, resource, id, ...args);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CORE,
|
|
3
|
+
type CharacterInfoPatch,
|
|
4
|
+
type CharacterResult,
|
|
5
|
+
type CharacterSearchPage,
|
|
6
|
+
type MembersPage,
|
|
7
|
+
type OfflineCharacter,
|
|
8
|
+
type StoredCharacter,
|
|
9
|
+
} from "@aifivem/shared";
|
|
10
|
+
import { resourceExport } from "../fivem/exports";
|
|
11
|
+
|
|
12
|
+
const core = resourceExport(CORE.resource);
|
|
13
|
+
|
|
14
|
+
/** A callback export as a promise (no promise crosses a resource boundary; the lib wraps it on the caller's side). */
|
|
15
|
+
const ask = <T>(call: (done: (value: T) => void) => void): Promise<T> =>
|
|
16
|
+
new Promise((resolve) => call(resolve));
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Characters by id through ai-core, loaded or not: a loaded one goes through its live state (memory, deltas), a
|
|
20
|
+
* stored one is changed in the DB while ai-core holds it (it cannot load meanwhile). Writes answer `{ ok }` or
|
|
21
|
+
* `{ ok: false, error }` with an ai-core lang key.
|
|
22
|
+
*/
|
|
23
|
+
export const characters = {
|
|
24
|
+
/**
|
|
25
|
+
* Moves a stored character's spawn point (a sleeping body that was carried away); ai-core writes it once no load
|
|
26
|
+
* or unload save holds the character. False when the character is loaded or the values are wrong.
|
|
27
|
+
*/
|
|
28
|
+
setOfflinePosition: (
|
|
29
|
+
charId: number,
|
|
30
|
+
position: { x: number; y: number; z: number; heading?: number },
|
|
31
|
+
): boolean => core.SetOfflinePosition(charId, position),
|
|
32
|
+
/** Info, money, jobs, gangs, metadata and position of a character; null when unknown or deleted. */
|
|
33
|
+
get: (charId: number): Promise<OfflineCharacter | null> =>
|
|
34
|
+
ask((done) => core.GetOfflineCharacter(charId, done)),
|
|
35
|
+
/**
|
|
36
|
+
* Characters by a typed text, loaded or not: first / last name prefixes ("first last" too), citizenid, fivem /
|
|
37
|
+
* license / discord id; 25 a page, newest first (`cursor` = the last page's `next`).
|
|
38
|
+
*/
|
|
39
|
+
search: (text: string, cursor?: number): Promise<CharacterSearchPage> =>
|
|
40
|
+
ask((done) => core.SearchCharacters(text, done, cursor)),
|
|
41
|
+
/** The characters of an account id or of every account with a license (`license:abc` or `abc`). */
|
|
42
|
+
ofUser: (user: number | string): Promise<StoredCharacter[]> =>
|
|
43
|
+
ask((done) => core.GetCharactersOfUser(user, done)),
|
|
44
|
+
/** Holders of a job, loaded or not, a page at a time (`after` = the last page's `next`). */
|
|
45
|
+
jobMembers: (
|
|
46
|
+
job: string,
|
|
47
|
+
after?: number,
|
|
48
|
+
limit?: number,
|
|
49
|
+
): Promise<MembersPage> =>
|
|
50
|
+
ask((done) => core.GetJobMembers(job, done, after, limit)),
|
|
51
|
+
/** Whether anyone holds a job, loaded or not (one row is read). */
|
|
52
|
+
hasJobMember: async (job: string): Promise<boolean> =>
|
|
53
|
+
(await ask<MembersPage>((done) => core.GetJobMembers(job, done, undefined, 1)))
|
|
54
|
+
.members.length > 0,
|
|
55
|
+
gangMembers: (
|
|
56
|
+
gang: string,
|
|
57
|
+
after?: number,
|
|
58
|
+
limit?: number,
|
|
59
|
+
): Promise<MembersPage> =>
|
|
60
|
+
ask((done) => core.GetGangMembers(gang, done, after, limit)),
|
|
61
|
+
/** Money of a character loaded or not, with a ledger row (`reason` defaults to the calling resource). */
|
|
62
|
+
addMoney: (
|
|
63
|
+
charId: number,
|
|
64
|
+
account: string,
|
|
65
|
+
amount: number,
|
|
66
|
+
reason?: string,
|
|
67
|
+
): Promise<CharacterResult> =>
|
|
68
|
+
ask((done) => core.AddOfflineMoney(charId, account, amount, reason, done)),
|
|
69
|
+
/** Refused below zero unless the account type allows it. */
|
|
70
|
+
removeMoney: (
|
|
71
|
+
charId: number,
|
|
72
|
+
account: string,
|
|
73
|
+
amount: number,
|
|
74
|
+
reason?: string,
|
|
75
|
+
): Promise<CharacterResult> =>
|
|
76
|
+
ask((done) =>
|
|
77
|
+
core.RemoveOfflineMoney(charId, account, amount, reason, done),
|
|
78
|
+
),
|
|
79
|
+
setMoney: (
|
|
80
|
+
charId: number,
|
|
81
|
+
account: string,
|
|
82
|
+
amount: number,
|
|
83
|
+
reason?: string,
|
|
84
|
+
): Promise<CharacterResult> =>
|
|
85
|
+
ask((done) => core.SetOfflineMoney(charId, account, amount, reason, done)),
|
|
86
|
+
/** Adds or regrades a job under the panel's job rules. */
|
|
87
|
+
setJob: (
|
|
88
|
+
charId: number,
|
|
89
|
+
job: string,
|
|
90
|
+
grade: number,
|
|
91
|
+
): Promise<CharacterResult> =>
|
|
92
|
+
ask((done) => core.SetOfflineJob(charId, job, grade, done)),
|
|
93
|
+
removeJob: (charId: number, job: string): Promise<CharacterResult> =>
|
|
94
|
+
ask((done) => core.RemoveOfflineJob(charId, job, done)),
|
|
95
|
+
setGang: (
|
|
96
|
+
charId: number,
|
|
97
|
+
gang: string,
|
|
98
|
+
grade: number,
|
|
99
|
+
): Promise<CharacterResult> =>
|
|
100
|
+
ask((done) => core.SetOfflineGang(charId, gang, grade, done)),
|
|
101
|
+
removeGang: (charId: number, gang: string): Promise<CharacterResult> =>
|
|
102
|
+
ask((done) => core.RemoveOfflineGang(charId, gang, done)),
|
|
103
|
+
/** One metadata value (null removes it). */
|
|
104
|
+
setMeta: (
|
|
105
|
+
charId: number,
|
|
106
|
+
key: string,
|
|
107
|
+
value: unknown,
|
|
108
|
+
): Promise<CharacterResult> =>
|
|
109
|
+
ask((done) => core.SetOfflineMeta(charId, key, value, done)),
|
|
110
|
+
/** Name, birth date, nationality, sex (sex only while not loaded), each checked like the creation form. */
|
|
111
|
+
setInfo: (
|
|
112
|
+
charId: number,
|
|
113
|
+
patch: CharacterInfoPatch,
|
|
114
|
+
): Promise<CharacterResult> =>
|
|
115
|
+
ask((done) => core.SetCharacterInfo(charId, patch, done)),
|
|
116
|
+
/** Soft delete; refused while the character is loaded. */
|
|
117
|
+
remove: (charId: number, by?: number | string): Promise<CharacterResult> =>
|
|
118
|
+
ask((done) => core.DeleteCharacter(charId, by, done)),
|
|
119
|
+
/** Seconds played by a loaded player (server id) or a character, loaded or not; null when unknown. */
|
|
120
|
+
playTime: (target: number | { charId: number }): Promise<number | null> =>
|
|
121
|
+
ask((done) => core.GetPlayTime(target, done)),
|
|
122
|
+
/** Writes a loaded player's position and metadata now; false when not loaded. */
|
|
123
|
+
save: (source: number): Promise<boolean> =>
|
|
124
|
+
ask((done) => core.SavePlayer(source, done)),
|
|
125
|
+
/** Turns a loaded player's paycheck off or on until the character unloads; false when not loaded. */
|
|
126
|
+
setPaycheck: (source: number, on: boolean): boolean =>
|
|
127
|
+
core.SetPaycheckEnabled(source, on),
|
|
128
|
+
isPaid: (source: number): boolean => core.IsPaycheckEnabled(source),
|
|
129
|
+
};
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { ADMIN, type CommandParam } from "@aifivem/shared";
|
|
2
|
+
import { Command } from "./command";
|
|
3
|
+
import { commands } from "./commandSet";
|
|
4
|
+
|
|
5
|
+
type Value<P extends CommandParam> = P["type"] extends "number" | "playerId"
|
|
6
|
+
? number
|
|
7
|
+
: string;
|
|
8
|
+
|
|
9
|
+
/** The handler's `args`: one value per param by name, `undefined` for a missing optional one. */
|
|
10
|
+
export type CommandArgs<P extends readonly CommandParam[]> = {
|
|
11
|
+
[K in P[number] as K["name"]]: K["optional"] extends true
|
|
12
|
+
? Value<K> | undefined
|
|
13
|
+
: Value<K>;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export interface CommandOptions<P extends readonly CommandParam[]> {
|
|
17
|
+
/** Lang text: what the command does (chat suggestion, admin panel). */
|
|
18
|
+
help?: string;
|
|
19
|
+
/** Parsed and checked in order before the handler runs; a `longString` takes the rest of the line and comes last. */
|
|
20
|
+
params?: P;
|
|
21
|
+
/**
|
|
22
|
+
* Who may use it (checked on the server, the console always may): false (default) everyone; true ai-core admins
|
|
23
|
+
* (ACE `ai.admin`); an ace (`ai.admin`) or principal (`group.admin`, `ai.job.police`) or a list of them: players
|
|
24
|
+
* allowed any. ai-core grants `command.<name>` to listed principals; `command.<name>` always allows (server.cfg, txAdmin).
|
|
25
|
+
*/
|
|
26
|
+
restricted?: boolean | string | string[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** `source` is 0 for the server console; `raw` is the whole typed line. A thrown error or rejection is logged. */
|
|
30
|
+
export type CommandHandler<P extends readonly CommandParam[]> = (
|
|
31
|
+
source: number,
|
|
32
|
+
args: CommandArgs<P>,
|
|
33
|
+
raw: string,
|
|
34
|
+
) => unknown;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Registers a server command (an array name adds aliases). Arguments are parsed and checked against `params` before
|
|
38
|
+
* the handler runs; wrong input shows the error and the usage line to the player. The permission is checked here
|
|
39
|
+
* with ACE (`restricted`), chat suggestions go only to players allowed to use it, and ai-core's panel lists it.
|
|
40
|
+
*
|
|
41
|
+
* addCommand("tp", { help: t("CMD_TP"), restricted: true, params: [{ name: "id", type: "playerId" }] }, (src, { id }) => ...);
|
|
42
|
+
*/
|
|
43
|
+
export function addCommand<
|
|
44
|
+
const P extends readonly CommandParam[] = readonly [],
|
|
45
|
+
>(
|
|
46
|
+
name: string | string[],
|
|
47
|
+
options: CommandOptions<P>,
|
|
48
|
+
handler: CommandHandler<P>,
|
|
49
|
+
): void {
|
|
50
|
+
const names = (Array.isArray(name) ? name : [name]).map((n) =>
|
|
51
|
+
n.toLowerCase(),
|
|
52
|
+
);
|
|
53
|
+
if (names.length === 0) throw new Error("addCommand needs a name");
|
|
54
|
+
const restricted = options.restricted ?? false;
|
|
55
|
+
const aces =
|
|
56
|
+
restricted === false
|
|
57
|
+
? null
|
|
58
|
+
: restricted === true
|
|
59
|
+
? [ADMIN.ace]
|
|
60
|
+
: Array.isArray(restricted)
|
|
61
|
+
? [...restricted]
|
|
62
|
+
: [restricted];
|
|
63
|
+
const command = new Command(
|
|
64
|
+
names,
|
|
65
|
+
options.params ?? [],
|
|
66
|
+
options.help ?? "",
|
|
67
|
+
aces,
|
|
68
|
+
handler as (
|
|
69
|
+
source: number,
|
|
70
|
+
args: Record<string, unknown>,
|
|
71
|
+
raw: string,
|
|
72
|
+
) => unknown,
|
|
73
|
+
);
|
|
74
|
+
// Registered unrestricted: the permission is ours (ACE list + `command.<name>`), so a refusal can say why.
|
|
75
|
+
for (const n of names)
|
|
76
|
+
RegisterCommand(
|
|
77
|
+
n,
|
|
78
|
+
(source: number, raw: string[], line: string) =>
|
|
79
|
+
command.run(Number(source), n, raw, line),
|
|
80
|
+
false,
|
|
81
|
+
);
|
|
82
|
+
commands.add(command);
|
|
83
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CORE,
|
|
3
|
+
type CommandInfo,
|
|
4
|
+
type CommandParam,
|
|
5
|
+
type NotificationKind,
|
|
6
|
+
} from "@aifivem/shared";
|
|
7
|
+
import { createLogger, formatText } from "../../shared";
|
|
8
|
+
import { loadLocaleTexts } from "../../fivem/locale";
|
|
9
|
+
import { notify } from "../notify";
|
|
10
|
+
|
|
11
|
+
const resource = GetCurrentResourceName();
|
|
12
|
+
const log = createLogger(resource);
|
|
13
|
+
|
|
14
|
+
// The error texts are ai-core's (generic words), in the `ai:locale` language; loaded on the first error.
|
|
15
|
+
let texts: Record<string, string> | null = null;
|
|
16
|
+
const t = (key: string, ...args: Array<string | number>): string =>
|
|
17
|
+
formatText((texts ??= loadLocaleTexts(CORE.resource))[key] ?? key, args);
|
|
18
|
+
|
|
19
|
+
/** A command answer: an ai-core notification for a player, a console line for the server. */
|
|
20
|
+
function reply(source: number, text: string, kind: NotificationKind): void {
|
|
21
|
+
if (source > 0) notify(source, text, kind);
|
|
22
|
+
else log.info(text);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class Command {
|
|
26
|
+
readonly info: CommandInfo;
|
|
27
|
+
private readonly usage: string;
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
names: string[],
|
|
31
|
+
private readonly params: readonly CommandParam[],
|
|
32
|
+
help: string,
|
|
33
|
+
aces: string[] | null,
|
|
34
|
+
private readonly handler: (
|
|
35
|
+
source: number,
|
|
36
|
+
args: Record<string, unknown>,
|
|
37
|
+
raw: string,
|
|
38
|
+
) => unknown,
|
|
39
|
+
) {
|
|
40
|
+
this.info = { names, help, params: params.map((p) => ({ ...p })), aces };
|
|
41
|
+
this.usage = [
|
|
42
|
+
`/${names[0]}`,
|
|
43
|
+
...params.map((p) => (p.optional ? `[${p.name}]` : `<${p.name}>`)),
|
|
44
|
+
].join(" ");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Whether `source` may run it under `name` (the console always may). */
|
|
48
|
+
allowed(source: number, name: string): boolean {
|
|
49
|
+
const aces = this.info.aces;
|
|
50
|
+
if (source <= 0 || !aces) return true;
|
|
51
|
+
const player = String(source);
|
|
52
|
+
return (
|
|
53
|
+
aces.some((ace) => IsPlayerAceAllowed(player, ace)) ||
|
|
54
|
+
Boolean(IsPlayerAceAllowed(player, `command.${name}`))
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
suggestion(name: string): {
|
|
59
|
+
name: string;
|
|
60
|
+
help: string;
|
|
61
|
+
params: Array<{ name: string; help: string }>;
|
|
62
|
+
} {
|
|
63
|
+
return {
|
|
64
|
+
name: `/${name}`,
|
|
65
|
+
help: this.info.help,
|
|
66
|
+
params: this.params.map((p) => ({ name: p.name, help: p.help ?? "" })),
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
run(source: number, name: string, raw: string[], line: string): void {
|
|
71
|
+
if (!this.allowed(source, name))
|
|
72
|
+
return reply(source, t("COMMAND_NOT_ALLOWED"), "error");
|
|
73
|
+
const args = this.parse(raw);
|
|
74
|
+
if (typeof args === "string") {
|
|
75
|
+
reply(source, args, "error");
|
|
76
|
+
return reply(source, t("COMMAND_USAGE", this.usage), "info");
|
|
77
|
+
}
|
|
78
|
+
const fail = (error: unknown) =>
|
|
79
|
+
log.error(`command /${name} failed`, error);
|
|
80
|
+
try {
|
|
81
|
+
const result = this.handler(source, args, line);
|
|
82
|
+
if (result instanceof Promise) result.catch(fail);
|
|
83
|
+
} catch (error) {
|
|
84
|
+
fail(error);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The checked values by param name, or the error text to show. */
|
|
89
|
+
private parse(raw: string[]): Record<string, unknown> | string {
|
|
90
|
+
const args: Record<string, unknown> = {};
|
|
91
|
+
for (const [i, param] of this.params.entries()) {
|
|
92
|
+
const token =
|
|
93
|
+
param.type === "longString"
|
|
94
|
+
? raw.slice(i).join(" ").trim()
|
|
95
|
+
: (raw[i] ?? "");
|
|
96
|
+
if (token === "") {
|
|
97
|
+
if (!param.optional) return t("COMMAND_MISSING", param.name);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (param.type === "number" || param.type === "playerId") {
|
|
101
|
+
const value = Number(token);
|
|
102
|
+
if (!Number.isFinite(value)) return t("COMMAND_NUMBER", param.name);
|
|
103
|
+
if (
|
|
104
|
+
param.type === "playerId" &&
|
|
105
|
+
(!Number.isInteger(value) ||
|
|
106
|
+
value <= 0 ||
|
|
107
|
+
!GetPlayerName(String(value)))
|
|
108
|
+
)
|
|
109
|
+
return t("COMMAND_PLAYER", token);
|
|
110
|
+
args[param.name] = value;
|
|
111
|
+
} else args[param.name] = token;
|
|
112
|
+
if (param.type === "longString") break;
|
|
113
|
+
}
|
|
114
|
+
return args;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { CORE } from "@aifivem/shared";
|
|
2
|
+
import { optionalExport } from "../../fivem/exports";
|
|
3
|
+
import type { Command } from "./command";
|
|
4
|
+
|
|
5
|
+
const resource = GetCurrentResourceName();
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* This resource's commands: announces them to ai-core (one call per tick of additions) and keeps each player's chat
|
|
9
|
+
* suggestions as a delta of the commands they may use (sent when a character loads, after job or gang changes, and
|
|
10
|
+
* to everyone online when commands are added; removed for everyone when the resource stops).
|
|
11
|
+
*/
|
|
12
|
+
class CommandSet {
|
|
13
|
+
private readonly list: Command[] = [];
|
|
14
|
+
private readonly sent = new Map<number, Set<string>>();
|
|
15
|
+
private announced = 0;
|
|
16
|
+
private queued = false;
|
|
17
|
+
private listening = false;
|
|
18
|
+
|
|
19
|
+
add(command: Command): void {
|
|
20
|
+
if (!this.listening) this.listen();
|
|
21
|
+
this.list.push(command);
|
|
22
|
+
if (this.queued) return;
|
|
23
|
+
this.queued = true;
|
|
24
|
+
setImmediate(() => this.flush());
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Sends `source` the suggestions they gained and removes the ones they lost. */
|
|
28
|
+
refresh(source: number): void {
|
|
29
|
+
const before = this.sent.get(source);
|
|
30
|
+
const now = new Set<string>();
|
|
31
|
+
const add: Array<ReturnType<Command["suggestion"]>> = [];
|
|
32
|
+
for (const command of this.list) {
|
|
33
|
+
for (const name of command.info.names) {
|
|
34
|
+
if (!command.allowed(source, name)) continue;
|
|
35
|
+
now.add(name);
|
|
36
|
+
if (!before?.has(name)) add.push(command.suggestion(name));
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
this.sent.set(source, now);
|
|
40
|
+
if (add.length) emitNet("chat:addSuggestions", source, add);
|
|
41
|
+
if (before)
|
|
42
|
+
for (const name of before)
|
|
43
|
+
if (!now.has(name))
|
|
44
|
+
emitNet("chat:removeSuggestion", source, `/${name}`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private flush(): void {
|
|
48
|
+
this.queued = false;
|
|
49
|
+
optionalExport(CORE.resource)?.RegisterCommands(
|
|
50
|
+
resource,
|
|
51
|
+
this.list.slice(this.announced).map((c) => c.info),
|
|
52
|
+
);
|
|
53
|
+
this.announced = this.list.length;
|
|
54
|
+
for (const player of getPlayers()) this.refresh(Number(player));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
private listen(): void {
|
|
58
|
+
this.listening = true;
|
|
59
|
+
const refresh = (source: number) => this.refresh(Number(source));
|
|
60
|
+
on(CORE.playerLoadedEvent, refresh);
|
|
61
|
+
// Job and gang grades are ACL principals: a command restricted to `ai.job.police` follows them.
|
|
62
|
+
on(CORE.jobsChangedEvent, refresh);
|
|
63
|
+
on(CORE.gangsChangedEvent, refresh);
|
|
64
|
+
on("playerDropped", () => this.sent.delete(Number(globalThis.source)));
|
|
65
|
+
on("onResourceStop", (name: string) => {
|
|
66
|
+
if (name !== resource) return;
|
|
67
|
+
for (const command of this.list)
|
|
68
|
+
for (const n of command.info.names)
|
|
69
|
+
emitNet("chat:removeSuggestion", -1, `/${n}`);
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export const commands = new CommandSet();
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { copyFile, mkdir, rename, writeFile } from "node:fs/promises";
|
|
2
|
+
import { isRecord, withoutSchemaKey, type Logger } from "../shared";
|
|
3
|
+
|
|
4
|
+
/** Bursts of admin edits are written once they settle. */
|
|
5
|
+
const WRITE_DELAY_MS = 250;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Admin-edited content of a resource in `data/<name>.json` (content goes with git; player data stays in the DB).
|
|
9
|
+
* The server is the only reader and writer: it reads the file once at start and keeps the truth in memory.
|
|
10
|
+
* A write goes to a temp file that then replaces the real one (a crash never leaves half a file), the previous
|
|
11
|
+
* file is kept as `.bak`, and a broken file falls back to it at start.
|
|
12
|
+
*/
|
|
13
|
+
export class DataFile {
|
|
14
|
+
private writes: Promise<void> = Promise.resolve();
|
|
15
|
+
private pending: unknown = undefined;
|
|
16
|
+
private timer: ReturnType<typeof setTimeout> | null = null;
|
|
17
|
+
|
|
18
|
+
/** `"$schema"` written as the file's first key (`./schemas/<name>.schema.json`), never part of the data. */
|
|
19
|
+
schemaRef: string | null = null;
|
|
20
|
+
|
|
21
|
+
constructor(
|
|
22
|
+
private readonly resource: string,
|
|
23
|
+
private readonly name: string,
|
|
24
|
+
private readonly log: Logger,
|
|
25
|
+
) {}
|
|
26
|
+
|
|
27
|
+
/** Whether the file on disk names its schema (`"$schema"`). */
|
|
28
|
+
hasSchemaRef(): boolean {
|
|
29
|
+
return (LoadResourceFile(this.resource, this.path) ?? "").includes(
|
|
30
|
+
'"$schema"',
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The parsed file (or its backup when it is broken); null when neither exists. */
|
|
35
|
+
read(): unknown {
|
|
36
|
+
for (const path of [this.path, `${this.path}.bak`]) {
|
|
37
|
+
const raw = LoadResourceFile(this.resource, path);
|
|
38
|
+
if (!raw) continue;
|
|
39
|
+
try {
|
|
40
|
+
return withoutSchemaKey(JSON.parse(raw));
|
|
41
|
+
} catch (error) {
|
|
42
|
+
this.log.error(
|
|
43
|
+
`${this.resource}/${path} is not valid JSON${path === this.path ? ", trying the backup" : ""}`,
|
|
44
|
+
error,
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Stores `value` (the latest call wins); written shortly after, in order with earlier writes. */
|
|
52
|
+
write(value: unknown): void {
|
|
53
|
+
this.pending = value;
|
|
54
|
+
if (this.timer) return;
|
|
55
|
+
this.timer = setTimeout(() => {
|
|
56
|
+
this.timer = null;
|
|
57
|
+
const data =
|
|
58
|
+
this.schemaRef && isRecord(this.pending)
|
|
59
|
+
? { $schema: this.schemaRef, ...this.pending }
|
|
60
|
+
: this.pending;
|
|
61
|
+
const text = `${JSON.stringify(data, null, 2)}\n`;
|
|
62
|
+
this.writes = this.writes
|
|
63
|
+
.then(() => this.flush(text))
|
|
64
|
+
.catch((error: unknown) =>
|
|
65
|
+
this.log.error(`saving ${this.resource}/${this.path} failed`, error),
|
|
66
|
+
);
|
|
67
|
+
}, WRITE_DELAY_MS);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
private get path(): string {
|
|
71
|
+
return `data/${this.name}.json`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
private async flush(text: string): Promise<void> {
|
|
75
|
+
const file = `${GetResourcePath(this.resource)}/${this.path}`;
|
|
76
|
+
await mkdir(file.slice(0, file.lastIndexOf("/")), { recursive: true });
|
|
77
|
+
await writeFile(`${file}.tmp`, text, "utf8");
|
|
78
|
+
await copyFile(file, `${file}.bak`).catch(() => undefined);
|
|
79
|
+
await rename(`${file}.tmp`, file);
|
|
80
|
+
}
|
|
81
|
+
}
|