@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,57 +1,57 @@
1
- import { formatText, isRecord } from "../shared";
2
-
3
- /** Convar holding the language (`setr ai:locale "en"` in misc.cfg); replicated so clients read it too. */
4
- export const LOCALE_CONVAR = "ai:locale";
5
-
6
- function readLocaleFile(
7
- resource: string,
8
- lang: string,
9
- ): Record<string, string> {
10
- const raw = LoadResourceFile(resource, `locales/${lang}.json`);
11
- if (!raw) return {};
12
- const parsed: unknown = JSON.parse(raw);
13
- if (!isRecord(parsed)) return {};
14
- const texts: Record<string, string> = {};
15
- for (const [key, value] of Object.entries(parsed))
16
- if (typeof value === "string") texts[key] = value;
17
- return texts;
18
- }
19
-
20
- /**
21
- * The resource's lang texts: `locales/en.json` (complete base) overlaid with `locales/<ai:locale>.json`.
22
- * `${OTHER_KEY}` inside a text is replaced by that text once at load. Returns `t(key, ...args)` filling
23
- * `{0}`, `{1}`...; a missing key returns the key itself so it is visible in game.
24
- *
25
- * const t = createLocale<typeof import("../../locales/en.json")>();
26
- * t("NOTIFY_NO_MONEY", price);
27
- */
28
- export function createLocale<T extends Record<string, string>>(): (
29
- key: keyof T & string,
30
- ...args: Array<string | number>
31
- ) => string {
32
- const texts = loadLocaleTexts();
33
- return (key, ...args) => formatText(texts[key] ?? key, args);
34
- }
35
-
36
- /**
37
- * The resource's merged lang table (`en.json` overlaid with the `ai:locale` language, `${KEY}` references
38
- * resolved). A NUI gets this once and fills `{0}` placeholders itself.
39
- */
40
- export function loadLocaleTexts(
41
- resource = GetCurrentResourceName(),
42
- ): Record<string, string> {
43
- const lang = GetConvar(LOCALE_CONVAR, "en");
44
- const texts = {
45
- ...readLocaleFile(resource, "en"),
46
- ...(lang === "en" ? {} : readLocaleFile(resource, lang)),
47
- };
48
-
49
- for (const key of Object.keys(texts)) {
50
- texts[key] = (texts[key] ?? "").replace(
51
- /\$\{([A-Z0-9_]+)\}/g,
52
- (match, ref: string) => texts[ref] ?? match,
53
- );
54
- }
55
-
56
- return texts;
57
- }
1
+ import { formatText, isRecord } from "../shared";
2
+
3
+ /** Convar holding the language (`setr ai:locale "en"` in misc.cfg); replicated so clients read it too. */
4
+ export const LOCALE_CONVAR = "ai:locale";
5
+
6
+ function readLocaleFile(
7
+ resource: string,
8
+ lang: string,
9
+ ): Record<string, string> {
10
+ const raw = LoadResourceFile(resource, `locales/${lang}.json`);
11
+ if (!raw) return {};
12
+ const parsed: unknown = JSON.parse(raw);
13
+ if (!isRecord(parsed)) return {};
14
+ const texts: Record<string, string> = {};
15
+ for (const [key, value] of Object.entries(parsed))
16
+ if (typeof value === "string") texts[key] = value;
17
+ return texts;
18
+ }
19
+
20
+ /**
21
+ * The resource's lang texts: `locales/en.json` (complete base) overlaid with `locales/<ai:locale>.json`.
22
+ * `${OTHER_KEY}` inside a text is replaced by that text once at load. Returns `t(key, ...args)` filling
23
+ * `{0}`, `{1}`...; a missing key returns the key itself so it is visible in game.
24
+ *
25
+ * const t = createLocale<typeof import("../../locales/en.json")>();
26
+ * t("NOTIFY_NO_MONEY", price);
27
+ */
28
+ export function createLocale<T extends Record<string, string>>(): (
29
+ key: keyof T & string,
30
+ ...args: Array<string | number>
31
+ ) => string {
32
+ const texts = loadLocaleTexts();
33
+ return (key, ...args) => formatText(texts[key] ?? key, args);
34
+ }
35
+
36
+ /**
37
+ * The resource's merged lang table (`en.json` overlaid with the `ai:locale` language, `${KEY}` references
38
+ * resolved). A NUI gets this once and fills `{0}` placeholders itself.
39
+ */
40
+ export function loadLocaleTexts(
41
+ resource = GetCurrentResourceName(),
42
+ ): Record<string, string> {
43
+ const lang = GetConvar(LOCALE_CONVAR, "en");
44
+ const texts = {
45
+ ...readLocaleFile(resource, "en"),
46
+ ...(lang === "en" ? {} : readLocaleFile(resource, lang)),
47
+ };
48
+
49
+ for (const key of Object.keys(texts)) {
50
+ texts[key] = (texts[key] ?? "").replace(
51
+ /\$\{([A-Z0-9_]+)\}/g,
52
+ (match, ref: string) => texts[ref] ?? match,
53
+ );
54
+ }
55
+
56
+ return texts;
57
+ }
@@ -1,112 +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
- }
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
+ }
@@ -1,81 +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
- }
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
+ }
@@ -1,58 +1,58 @@
1
- import { createLogger } from "../shared";
2
- import {
3
- ClientGate,
4
- type ClientInputOptions,
5
- type ParsedInputOptions,
6
- } from "./gate";
7
-
8
- const log = createLogger(GetCurrentResourceName());
9
-
10
- /**
11
- * A net event a client sends: the only way an ai-* server listens to clients (never bare `onNet`). The source is
12
- * read first, then the gate runs (real player, rate, guards, `args` parser, optional lock) and only then the
13
- * handler. A handler that takes arguments gets them only through `args` (options come before it then), so
14
- * unchecked client data never reaches it. A thrown error is logged, never sent back.
15
- *
16
- * onClientEvent("ai-shop:close", (source) => shop.close(source));
17
- * onClientEvent(
18
- * "ai-shop:buy",
19
- * { args: ([item, count]) => (typeof item === "string" && isCount(count) ? [item, count] : null), guards: [hasCharacter()], lock: true },
20
- * (source, item, count) => shop.buy(source, item, count),
21
- * );
22
- */
23
- export function onClientEvent(
24
- name: string,
25
- handler: (source: number) => unknown,
26
- options?: ClientInputOptions,
27
- ): void;
28
- export function onClientEvent<const A extends readonly unknown[]>(
29
- name: string,
30
- options: ParsedInputOptions<A>,
31
- handler: (source: number, ...args: A) => unknown,
32
- ): void;
33
- export function onClientEvent(
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, 10);
48
- onNet(name, (...raw: unknown[]) => {
49
- const source = Number(globalThis.source);
50
- const args = gate.check(source, raw);
51
- if (!args) return;
52
- gate
53
- .run(source, undefined, () => handler(source, ...args))
54
- .catch((error: unknown) =>
55
- log.error(`event ${name} failed for ${source}`, error),
56
- );
57
- });
58
- }
1
+ import { createLogger } from "../shared";
2
+ import {
3
+ ClientGate,
4
+ type ClientInputOptions,
5
+ type ParsedInputOptions,
6
+ } from "./gate";
7
+
8
+ const log = createLogger(GetCurrentResourceName());
9
+
10
+ /**
11
+ * A net event a client sends: the only way an ai-* server listens to clients (never bare `onNet`). The source is
12
+ * read first, then the gate runs (real player, rate, guards, `args` parser, optional lock) and only then the
13
+ * handler. A handler that takes arguments gets them only through `args` (options come before it then), so
14
+ * unchecked client data never reaches it. A thrown error is logged, never sent back.
15
+ *
16
+ * onClientEvent("ai-shop:close", (source) => shop.close(source));
17
+ * onClientEvent(
18
+ * "ai-shop:buy",
19
+ * { args: ([item, count]) => (typeof item === "string" && isCount(count) ? [item, count] : null), guards: [hasCharacter()], lock: true },
20
+ * (source, item, count) => shop.buy(source, item, count),
21
+ * );
22
+ */
23
+ export function onClientEvent(
24
+ name: string,
25
+ handler: (source: number) => unknown,
26
+ options?: ClientInputOptions,
27
+ ): void;
28
+ export function onClientEvent<const A extends readonly unknown[]>(
29
+ name: string,
30
+ options: ParsedInputOptions<A>,
31
+ handler: (source: number, ...args: A) => unknown,
32
+ ): void;
33
+ export function onClientEvent(
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, 10);
48
+ onNet(name, (...raw: unknown[]) => {
49
+ const source = Number(globalThis.source);
50
+ const args = gate.check(source, raw);
51
+ if (!args) return;
52
+ gate
53
+ .run(source, undefined, () => handler(source, ...args))
54
+ .catch((error: unknown) =>
55
+ log.error(`event ${name} failed for ${source}`, error),
56
+ );
57
+ });
58
+ }
@@ -1,15 +1,15 @@
1
- import type { Vec3 } from "../shared/vec";
2
-
3
- /** An entity's position (server copy of the owner's sync). */
4
- export function entityCoords(entity: number): Vec3 {
5
- const [x = 0, y = 0, z = 0] = GetEntityCoords(entity);
6
- return { x, y, z };
7
- }
8
-
9
- /** A player's ped position. */
10
- export const coordsOf = (source: number): Vec3 =>
11
- entityCoords(GetPlayerPed(String(source)));
12
-
1
+ import type { Vec3 } from "../shared/vec";
2
+
3
+ /** An entity's position (server copy of the owner's sync). */
4
+ export function entityCoords(entity: number): Vec3 {
5
+ const [x = 0, y = 0, z = 0] = GetEntityCoords(entity);
6
+ return { x, y, z };
7
+ }
8
+
9
+ /** A player's ped position. */
10
+ export const coordsOf = (source: number): Vec3 =>
11
+ entityCoords(GetPlayerPed(String(source)));
12
+
13
13
  /** The vehicle the player sits in (with `driver: true` only when in its driver seat), 0 on foot. */
14
14
  export function vehicleOf(
15
15
  source: number,
@@ -21,11 +21,11 @@ export function vehicleOf(
21
21
  return GetPedInVehicleSeat(vehicle, -1) === ped ? vehicle : 0;
22
22
  }
23
23
 
24
- /** The player's ped is within `metres` of a point. */
25
- export function isNear(source: number, point: Vec3, metres: number): boolean {
26
- const [x = 0, y = 0, z = 0] = GetEntityCoords(GetPlayerPed(String(source)));
27
- const dx = x - point.x;
28
- const dy = y - point.y;
29
- const dz = z - point.z;
30
- return dx * dx + dy * dy + dz * dz <= metres * metres;
31
- }
24
+ /** The player's ped is within `metres` of a point. */
25
+ export function isNear(source: number, point: Vec3, metres: number): boolean {
26
+ const [x = 0, y = 0, z = 0] = GetEntityCoords(GetPlayerPed(String(source)));
27
+ const dx = x - point.x;
28
+ const dy = y - point.y;
29
+ const dz = z - point.z;
30
+ return dx * dx + dy * dy + dz * dz <= metres * metres;
31
+ }