@aifivem/lib 0.6.0 → 0.7.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.
@@ -1,53 +1,53 @@
1
- /**
2
- * One in-flight action per player. `run` returns `busy` instead of starting a second copy.
3
- * Call `release(source)` from playerDropped.
4
- */
5
- export class SourceLock {
6
- private readonly active = new Set<number>();
7
-
8
- async run<T, B>(
9
- source: number,
10
- busy: B,
11
- task: () => Promise<T>,
12
- ): Promise<T | B> {
13
- if (this.active.has(source)) return busy;
14
- this.active.add(source);
15
- try {
16
- return await task();
17
- } finally {
18
- this.active.delete(source);
19
- }
20
- }
21
-
22
- release(source: number): void {
23
- this.active.delete(source);
24
- }
25
- }
26
-
27
- /** Per-player burst limit: at most `count` actions inside any `windowMs`. Call `release(source)` from playerDropped. */
28
- export class RateLimit {
29
- private readonly hits = new Map<number, number[]>();
30
-
31
- constructor(
32
- private readonly count: number,
33
- private readonly windowMs: number,
34
- ) {}
35
-
36
- take(source: number): boolean {
37
- const now = GetGameTimer();
38
- const recent = (this.hits.get(source) ?? []).filter(
39
- (at) => now - at < this.windowMs,
40
- );
41
- if (recent.length >= this.count) {
42
- this.hits.set(source, recent);
43
- return false;
44
- }
45
- recent.push(now);
46
- this.hits.set(source, recent);
47
- return true;
48
- }
49
-
50
- release(source: number): void {
51
- this.hits.delete(source);
52
- }
53
- }
1
+ /**
2
+ * One in-flight action per player. `run` returns `busy` instead of starting a second copy.
3
+ * Call `release(source)` from playerDropped.
4
+ */
5
+ export class SourceLock {
6
+ private readonly active = new Set<number>();
7
+
8
+ async run<T, B>(
9
+ source: number,
10
+ busy: B,
11
+ task: () => Promise<T>,
12
+ ): Promise<T | B> {
13
+ if (this.active.has(source)) return busy;
14
+ this.active.add(source);
15
+ try {
16
+ return await task();
17
+ } finally {
18
+ this.active.delete(source);
19
+ }
20
+ }
21
+
22
+ release(source: number): void {
23
+ this.active.delete(source);
24
+ }
25
+ }
26
+
27
+ /** Per-player burst limit: at most `count` actions inside any `windowMs`. Call `release(source)` from playerDropped. */
28
+ export class RateLimit {
29
+ private readonly hits = new Map<number, number[]>();
30
+
31
+ constructor(
32
+ private readonly count: number,
33
+ private readonly windowMs: number,
34
+ ) {}
35
+
36
+ take(source: number): boolean {
37
+ const now = GetGameTimer();
38
+ const recent = (this.hits.get(source) ?? []).filter(
39
+ (at) => now - at < this.windowMs,
40
+ );
41
+ if (recent.length >= this.count) {
42
+ this.hits.set(source, recent);
43
+ return false;
44
+ }
45
+ recent.push(now);
46
+ this.hits.set(source, recent);
47
+ return true;
48
+ }
49
+
50
+ release(source: number): void {
51
+ this.hits.delete(source);
52
+ }
53
+ }
@@ -1,29 +1,29 @@
1
- /** Rounds to `decimals` places (default 0). */
2
- export function round(value: number, decimals = 0): number {
3
- const power = 10 ** decimals;
4
- return Math.round(value * power) / power;
5
- }
6
-
7
- /** `1234567` as `1,234,567` (`separator` default `,`); keeps a sign and decimals. */
8
- export function groupDigits(value: number | string, separator = ","): string {
9
- const [whole = "", fraction] = String(value).split(".");
10
- const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
11
- return fraction === undefined ? grouped : `${grouped}.${fraction}`;
12
- }
13
-
14
- /**
15
- * Text from another script made plain: HTML tags, GTA colour and input codes (`~r~`, `~INPUT_PICKUP~`) and `&nbsp;`
16
- * removed, runs of spaces folded.
17
- */
18
- export function stripGameText(text: unknown): string {
19
- if (text === null || text === undefined) return "";
20
- return String(text)
21
- .replace(/<[^>]*>/g, "")
22
- .replace(/~[\w]+~/g, "")
23
- .replace(/&nbsp;/g, " ")
24
- .replace(/\s\s+/g, " ")
25
- .trim();
26
- }
1
+ /** Rounds to `decimals` places (default 0). */
2
+ export function round(value: number, decimals = 0): number {
3
+ const power = 10 ** decimals;
4
+ return Math.round(value * power) / power;
5
+ }
6
+
7
+ /** `1234567` as `1,234,567` (`separator` default `,`); keeps a sign and decimals. */
8
+ export function groupDigits(value: number | string, separator = ","): string {
9
+ const [whole = "", fraction] = String(value).split(".");
10
+ const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, separator);
11
+ return fraction === undefined ? grouped : `${grouped}.${fraction}`;
12
+ }
13
+
14
+ /**
15
+ * Text from another script made plain: HTML tags, GTA colour and input codes (`~r~`, `~INPUT_PICKUP~`) and `&nbsp;`
16
+ * removed, runs of spaces folded.
17
+ */
18
+ export function stripGameText(text: unknown): string {
19
+ if (text === null || text === undefined) return "";
20
+ return String(text)
21
+ .replace(/<[^>]*>/g, "")
22
+ .replace(/~[\w]+~/g, "")
23
+ .replace(/&nbsp;/g, " ")
24
+ .replace(/\s\s+/g, " ")
25
+ .trim();
26
+ }
27
27
 
28
28
  /** A weight in grams for players: "750 g", "1.5 kg", "1,250 kg" (one decimal under 100 kg). */
29
29
  export function formatWeight(grams: number): string {
@@ -1,20 +1,20 @@
1
- /** Grid cells for world streaming (lib `AreaStream` / `AreaFollower`): the same math on server and client. */
2
-
3
- /** Cells are clamped to +-16,000 so `cellKey` stays a small integer (a fast Map key). */
4
- const LIMIT = 16_000;
5
- const OFFSET = 16_384;
6
- const clampCell = (v: number): number => Math.max(-LIMIT, Math.min(LIMIT, v));
7
-
8
- /** The integer cell of a point on a grid of `size` metres. */
9
- export const gridCell = (
10
- x: number,
11
- y: number,
12
- size: number,
13
- ): { cx: number; cy: number } => ({
14
- cx: clampCell(Math.floor(x / size)),
15
- cy: clampCell(Math.floor(y / size)),
16
- });
17
-
18
- /** One number for a cell (below 2^30). */
19
- export const cellKey = (cx: number, cy: number): number =>
20
- (clampCell(cx) + OFFSET) * 32_768 + (clampCell(cy) + OFFSET);
1
+ /** Grid cells for world streaming (lib `AreaStream` / `AreaFollower`): the same math on server and client. */
2
+
3
+ /** Cells are clamped to +-16,000 so `cellKey` stays a small integer (a fast Map key). */
4
+ const LIMIT = 16_000;
5
+ const OFFSET = 16_384;
6
+ const clampCell = (v: number): number => Math.max(-LIMIT, Math.min(LIMIT, v));
7
+
8
+ /** The integer cell of a point on a grid of `size` metres. */
9
+ export const gridCell = (
10
+ x: number,
11
+ y: number,
12
+ size: number,
13
+ ): { cx: number; cy: number } => ({
14
+ cx: clampCell(Math.floor(x / size)),
15
+ cy: clampCell(Math.floor(y / size)),
16
+ });
17
+
18
+ /** One number for a cell (below 2^30). */
19
+ export const cellKey = (cx: number, cy: number): number =>
20
+ (clampCell(cx) + OFFSET) * 32_768 + (clampCell(cy) + OFFSET);
@@ -1,17 +1,17 @@
1
- /** Helpers usable on client and server. No FiveM natives here. */
2
-
3
- export { sleep, waitFor } from "./wait";
4
- export { bool, int, num, record, str, vec4, type Vec4 } from "./read";
5
- export {
6
- oneArg,
7
- readFinite,
8
- readId,
9
- readInt,
10
- readText,
11
- readVec3,
12
- readVec4,
13
- } from "./strict";
14
- export { fail, isActionOk, replyError, type ActionResult } from "./action";
1
+ /** Helpers usable on client and server. No FiveM natives here. */
2
+
3
+ export { sleep, waitFor } from "./wait";
4
+ export { bool, int, num, record, str, vec4, type Vec4 } from "./read";
5
+ export {
6
+ oneArg,
7
+ readFinite,
8
+ readId,
9
+ readInt,
10
+ readText,
11
+ readVec3,
12
+ readVec4,
13
+ } from "./strict";
14
+ export { fail, isActionOk, replyError, type ActionResult } from "./action";
15
15
  export {
16
16
  distance,
17
17
  flatDistance,
@@ -20,7 +20,7 @@ export {
20
20
  type Vec3,
21
21
  } from "./vec";
22
22
  export { pickRandom, randomInt, rollChance } from "./random";
23
- export { ServerClock } from "./clock";
23
+ export { ServerClock } from "./clock";
24
24
  export {
25
25
  formatWeight,
26
26
  groupDigits,
@@ -35,145 +35,145 @@ export {
35
35
  isPublic,
36
36
  readAccess,
37
37
  type AccessRule,
38
- } from "./access";
39
- export {
40
- BLIP_STYLE_FIELDS,
41
- readBlipStyle,
42
- type BlipStyle,
43
- } from "./blipStyle";
44
- export {
45
- polyFromCorners,
46
- readZoneShape,
47
- zoneBounds,
48
- zoneContains,
49
- type ZoneShape,
50
- } from "./zone";
38
+ } from "./access";
39
+ export {
40
+ BLIP_STYLE_FIELDS,
41
+ readBlipStyle,
42
+ type BlipStyle,
43
+ } from "./blipStyle";
44
+ export {
45
+ polyFromCorners,
46
+ readZoneShape,
47
+ zoneBounds,
48
+ zoneContains,
49
+ type ZoneShape,
50
+ } from "./zone";
51
51
  export {
52
52
  LiveRecords,
53
53
  readRecords,
54
54
  RecordObjects,
55
55
  type RecordReader,
56
56
  type RecordSource,
57
- } from "./records";
58
- export { formatText, LangTexts } from "./lang";
59
- export { spec } from "./spec";
60
- export {
61
- toVehicleProps,
62
- toVehicleSetup,
63
- type VehicleProps,
64
- type VehicleSetup,
65
- } from "./vehicleProps";
66
-
67
- export function isRecord(value: unknown): value is Record<string, unknown> {
68
- return typeof value === "object" && value !== null && !Array.isArray(value);
69
- }
70
-
71
- /** Client text made safe for the server console: one line, no control characters, no `^n` colour codes. */
72
- export function logSafe(text: string, max: number): string {
73
- // oxlint-disable-next-line no-control-regex
74
- return text
75
- .replace(/\r?\n/g, " | ")
76
- .replace(/[\u0000-\u001f\u007f]/g, "")
77
- .replace(/\^\d/g, "")
78
- .slice(0, max);
79
- }
80
-
81
- /**
82
- * JSON-like text of an untrusted value cut at `max` characters, built without serializing the rest (a hostile
83
- * payload can be megabytes): for log lines. Deeper than 4 levels shows as `[...]` / `{...}`.
84
- */
85
- export function previewJson(value: unknown, max: number): string {
86
- let out = "";
87
- const walk = (v: unknown, depth: number): void => {
88
- if (out.length >= max) return;
89
- if (typeof v === "string") {
90
- out += JSON.stringify(v.length > max ? v.slice(0, max) : v);
91
- return;
92
- }
93
- if (v === null || typeof v !== "object") {
94
- out += String(v);
95
- return;
96
- }
97
- if (depth > 4) {
98
- out += Array.isArray(v) ? "[...]" : "{...}";
99
- return;
100
- }
101
- if (Array.isArray(v)) {
102
- out += "[";
103
- for (let i = 0; i < v.length && out.length < max; i++) {
104
- if (i > 0) out += ",";
105
- walk(v[i], depth + 1);
106
- }
107
- out += "]";
108
- return;
109
- }
110
- out += "{";
111
- let first = true;
112
- for (const key in v) {
113
- if (out.length >= max) break;
114
- if (!first) out += ",";
115
- first = false;
116
- out += `${JSON.stringify(key.slice(0, 50))}:`;
117
- walk((v as Record<string, unknown>)[key], depth + 1);
118
- }
119
- out += "}";
120
- };
121
- walk(value, 0);
122
- return out.slice(0, max);
123
- }
124
-
125
- /** GTA vehicle class (`GetVehicleClassFromName`) -> the type `CreateVehicleServerSetter` wants. */
126
- export function vehicleTypeOfClass(vehicleClass: number): string {
127
- switch (vehicleClass) {
128
- case 8:
129
- case 13:
130
- return "bike";
131
- case 14:
132
- return "boat";
133
- case 15:
134
- return "heli";
135
- case 16:
136
- return "plane";
137
- case 21:
138
- return "train";
139
- default:
140
- return "automobile";
141
- }
142
- }
143
-
144
- /** One parsed value as an `args` result: `[value]`, or null to refuse the call. */
145
- export const asArgs = <T>(value: T | null): [T] | null =>
146
- value === null ? null : [value];
147
-
148
- export interface Logger {
149
- info(message: string, ...details: unknown[]): void;
150
- warn(message: string, ...details: unknown[]): void;
151
- error(message: string, ...details: unknown[]): void;
152
- }
153
-
154
- /** Console output prefixed with the resource name, so server logs show where a line came from. */
155
- export function createLogger(resource: string): Logger {
156
- const prefix = `[${resource}]`;
157
- return {
158
- info: (message, ...details) =>
159
- console.log(`${prefix} ${message}`, ...details),
160
- warn: (message, ...details) =>
161
- console.warn(`${prefix} ^3${message}^7`, ...details),
162
- error: (message, ...details) =>
163
- console.error(`${prefix} ^1${message}^7`, ...details),
164
- };
165
- }
166
-
167
- /** A data file's `"$schema"` key is for editors only: readers of panel files never see it. */
168
- export function withoutSchemaKey(value: unknown): unknown {
169
- if (!isRecord(value) || !("$schema" in value)) return value;
170
- const { $schema: _schema, ...rest } = value;
171
- return rest;
172
- }
173
- export {
174
- PLACE_PED_SPEC,
175
- placePedFields,
176
- readPlacePed,
177
- type PlacePed,
178
- } from "./placePed";
179
- export { cellKey, gridCell } from "./grid";
57
+ } from "./records";
58
+ export { formatText, LangTexts } from "./lang";
59
+ export { spec } from "./spec";
60
+ export {
61
+ toVehicleProps,
62
+ toVehicleSetup,
63
+ type VehicleProps,
64
+ type VehicleSetup,
65
+ } from "./vehicleProps";
66
+
67
+ export function isRecord(value: unknown): value is Record<string, unknown> {
68
+ return typeof value === "object" && value !== null && !Array.isArray(value);
69
+ }
70
+
71
+ /** Client text made safe for the server console: one line, no control characters, no `^n` colour codes. */
72
+ export function logSafe(text: string, max: number): string {
73
+ // oxlint-disable-next-line no-control-regex
74
+ return text
75
+ .replace(/\r?\n/g, " | ")
76
+ .replace(/[\u0000-\u001f\u007f]/g, "")
77
+ .replace(/\^\d/g, "")
78
+ .slice(0, max);
79
+ }
80
+
81
+ /**
82
+ * JSON-like text of an untrusted value cut at `max` characters, built without serializing the rest (a hostile
83
+ * payload can be megabytes): for log lines. Deeper than 4 levels shows as `[...]` / `{...}`.
84
+ */
85
+ export function previewJson(value: unknown, max: number): string {
86
+ let out = "";
87
+ const walk = (v: unknown, depth: number): void => {
88
+ if (out.length >= max) return;
89
+ if (typeof v === "string") {
90
+ out += JSON.stringify(v.length > max ? v.slice(0, max) : v);
91
+ return;
92
+ }
93
+ if (v === null || typeof v !== "object") {
94
+ out += String(v);
95
+ return;
96
+ }
97
+ if (depth > 4) {
98
+ out += Array.isArray(v) ? "[...]" : "{...}";
99
+ return;
100
+ }
101
+ if (Array.isArray(v)) {
102
+ out += "[";
103
+ for (let i = 0; i < v.length && out.length < max; i++) {
104
+ if (i > 0) out += ",";
105
+ walk(v[i], depth + 1);
106
+ }
107
+ out += "]";
108
+ return;
109
+ }
110
+ out += "{";
111
+ let first = true;
112
+ for (const key in v) {
113
+ if (out.length >= max) break;
114
+ if (!first) out += ",";
115
+ first = false;
116
+ out += `${JSON.stringify(key.slice(0, 50))}:`;
117
+ walk((v as Record<string, unknown>)[key], depth + 1);
118
+ }
119
+ out += "}";
120
+ };
121
+ walk(value, 0);
122
+ return out.slice(0, max);
123
+ }
124
+
125
+ /** GTA vehicle class (`GetVehicleClassFromName`) -> the type `CreateVehicleServerSetter` wants. */
126
+ export function vehicleTypeOfClass(vehicleClass: number): string {
127
+ switch (vehicleClass) {
128
+ case 8:
129
+ case 13:
130
+ return "bike";
131
+ case 14:
132
+ return "boat";
133
+ case 15:
134
+ return "heli";
135
+ case 16:
136
+ return "plane";
137
+ case 21:
138
+ return "train";
139
+ default:
140
+ return "automobile";
141
+ }
142
+ }
143
+
144
+ /** One parsed value as an `args` result: `[value]`, or null to refuse the call. */
145
+ export const asArgs = <T>(value: T | null): [T] | null =>
146
+ value === null ? null : [value];
147
+
148
+ export interface Logger {
149
+ info(message: string, ...details: unknown[]): void;
150
+ warn(message: string, ...details: unknown[]): void;
151
+ error(message: string, ...details: unknown[]): void;
152
+ }
153
+
154
+ /** Console output prefixed with the resource name, so server logs show where a line came from. */
155
+ export function createLogger(resource: string): Logger {
156
+ const prefix = `[${resource}]`;
157
+ return {
158
+ info: (message, ...details) =>
159
+ console.log(`${prefix} ${message}`, ...details),
160
+ warn: (message, ...details) =>
161
+ console.warn(`${prefix} ^3${message}^7`, ...details),
162
+ error: (message, ...details) =>
163
+ console.error(`${prefix} ^1${message}^7`, ...details),
164
+ };
165
+ }
166
+
167
+ /** A data file's `"$schema"` key is for editors only: readers of panel files never see it. */
168
+ export function withoutSchemaKey(value: unknown): unknown {
169
+ if (!isRecord(value) || !("$schema" in value)) return value;
170
+ const { $schema: _schema, ...rest } = value;
171
+ return rest;
172
+ }
173
+ export {
174
+ PLACE_PED_SPEC,
175
+ placePedFields,
176
+ readPlacePed,
177
+ type PlacePed,
178
+ } from "./placePed";
179
+ export { cellKey, gridCell } from "./grid";
@@ -1,39 +1,39 @@
1
- /** Fills `{0}`, `{1}`... with the arguments by position (a translation may reorder or repeat them). */
2
- export function formatText(
3
- template: string,
4
- args: ReadonlyArray<string | number>,
5
- ): string {
6
- return template.replace(/\{(\d+)\}/g, (match, index: string) => {
7
- const value = args[Number(index)];
8
- return value === undefined ? match : String(value);
9
- });
10
- }
11
-
12
- /**
13
- * A NUI page's lang texts (its client sends them with the screen): `translate` fills `{0}` placeholders and answers
14
- * the key itself when a text is missing; `subscribe` / `snapshot` fit React's `useSyncExternalStore`. Methods are
15
- * bound, so they can be passed around as plain functions.
16
- */
17
- export class LangTexts {
18
- private texts: Record<string, string> = {};
19
- private readonly listeners = new Set<() => void>();
20
-
21
- /** Replaces every text and tells the subscribers. */
22
- readonly set = (next: Record<string, string>): void => {
23
- this.texts = next;
24
- for (const listener of this.listeners) listener();
25
- };
26
-
27
- /** The text of `key` with `{0}`, `{1}`... filled in; the key itself when it is missing. */
28
- readonly translate = (key: string, ...args: Array<string | number>): string =>
29
- formatText(this.texts[key] ?? key, args);
30
-
31
- /** Calls `listener` after each `set`; answers the unsubscribe function. */
32
- readonly subscribe = (listener: () => void): (() => void) => {
33
- this.listeners.add(listener);
34
- return () => this.listeners.delete(listener);
35
- };
36
-
37
- /** The current texts (a new object after each `set`). */
38
- readonly snapshot = (): Record<string, string> => this.texts;
39
- }
1
+ /** Fills `{0}`, `{1}`... with the arguments by position (a translation may reorder or repeat them). */
2
+ export function formatText(
3
+ template: string,
4
+ args: ReadonlyArray<string | number>,
5
+ ): string {
6
+ return template.replace(/\{(\d+)\}/g, (match, index: string) => {
7
+ const value = args[Number(index)];
8
+ return value === undefined ? match : String(value);
9
+ });
10
+ }
11
+
12
+ /**
13
+ * A NUI page's lang texts (its client sends them with the screen): `translate` fills `{0}` placeholders and answers
14
+ * the key itself when a text is missing; `subscribe` / `snapshot` fit React's `useSyncExternalStore`. Methods are
15
+ * bound, so they can be passed around as plain functions.
16
+ */
17
+ export class LangTexts {
18
+ private texts: Record<string, string> = {};
19
+ private readonly listeners = new Set<() => void>();
20
+
21
+ /** Replaces every text and tells the subscribers. */
22
+ readonly set = (next: Record<string, string>): void => {
23
+ this.texts = next;
24
+ for (const listener of this.listeners) listener();
25
+ };
26
+
27
+ /** The text of `key` with `{0}`, `{1}`... filled in; the key itself when it is missing. */
28
+ readonly translate = (key: string, ...args: Array<string | number>): string =>
29
+ formatText(this.texts[key] ?? key, args);
30
+
31
+ /** Calls `listener` after each `set`; answers the unsubscribe function. */
32
+ readonly subscribe = (listener: () => void): (() => void) => {
33
+ this.listeners.add(listener);
34
+ return () => this.listeners.delete(listener);
35
+ };
36
+
37
+ /** The current texts (a new object after each `set`). */
38
+ readonly snapshot = (): Record<string, string> => this.texts;
39
+ }