@nativewrappers/common 0.0.65 → 0.0.75

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 CHANGED
@@ -1,9 +1,14 @@
1
1
  {
2
2
  "name": "@nativewrappers/common",
3
- "description": "Native wrappers and utilities for use with Cfx.re's scripting runtimes.",
3
+ "description": "Native wrappers and utilities for use with Common Utilities.",
4
+ "contributors": [
5
+ "Remco Troost <d0p3t>",
6
+ "Dillon Skaggs <AvarianKnight>",
7
+ "Linden <thelindat>"
8
+ ],
4
9
  "license": "MIT",
5
10
  "type": "module",
6
- "version": "0.0.65",
11
+ "version": "0.0.75",
7
12
  "repository": {
8
13
  "type": "git",
9
14
  "url": "https://github.com/nativewrappers/nativewrappers.git"
package/utils/PointF.d.ts CHANGED
@@ -1,8 +1,3 @@
1
- export interface PointF {
2
- x: number;
3
- y: number;
4
- z: number;
5
- }
6
1
  export declare class PointF implements PointF {
7
2
  x: number;
8
3
  y: number;
package/Command.js DELETED
@@ -1,103 +0,0 @@
1
- import { GlobalData } from "./GlobalData";
2
- const commands = [];
3
- if (GlobalData.IS_SERVER) {
4
- on("playerJoining", () => emitNet("chat:addSuggestions", source, commands));
5
- }
6
- function registerCommand(name, commandHandler, restricted) {
7
- if (Array.isArray(name))
8
- return name.forEach((name) => registerCommand(name, commandHandler, restricted));
9
- RegisterCommand(name, commandHandler, !!restricted);
10
- if (GlobalData.IS_CLIENT)
11
- return;
12
- const ace = `command.${name}`;
13
- if (typeof restricted === "string") {
14
- if (IsPrincipalAceAllowed(restricted, ace))
15
- return;
16
- return ExecuteCommand(`add_ace ${restricted} ${ace} allow`);
17
- }
18
- if (Array.isArray(restricted)) {
19
- restricted.forEach((principal) => !IsPrincipalAceAllowed(principal, ace) &&
20
- ExecuteCommand(`add_ace ${restricted} ${ace} allow`));
21
- }
22
- }
23
- export class Command {
24
- name;
25
- help;
26
- params;
27
- #handler;
28
- constructor(name, help, handler, params, restricted = true) {
29
- this.name = name;
30
- this.help = help;
31
- this.params = params;
32
- this.#handler = handler;
33
- this.name = `/${name}`;
34
- registerCommand(name, (source, args, raw) => this.call(source, args, raw), restricted);
35
- if (params) {
36
- params.forEach((param) => {
37
- if (param.type)
38
- param.help = param.help
39
- ? `${param.help} (type: ${param.type})`
40
- : `(type: ${param.type})`;
41
- });
42
- setTimeout(() => {
43
- if (GlobalData.IS_SERVER) {
44
- commands.push(this);
45
- return emitNet("chat:addSuggestions", -1, this);
46
- }
47
- emit("chat:addSuggestion", this);
48
- }, 100);
49
- }
50
- }
51
- mapArguments(source, args, raw) {
52
- const mapped = {
53
- source,
54
- raw,
55
- };
56
- if (!this.params)
57
- return mapped;
58
- const result = this.params.every((param, index) => {
59
- const arg = args[index];
60
- let value = arg;
61
- switch (param.type) {
62
- case "number":
63
- value = +arg;
64
- break;
65
- case "string":
66
- value = !Number(arg) ? arg : false;
67
- break;
68
- case "playerId":
69
- if (GlobalData.IS_SERVER) {
70
- value = arg === "me" ? source : +arg;
71
- if (!value || !DoesPlayerExist(value.toString()))
72
- value = undefined;
73
- }
74
- else {
75
- value = arg === "me" ? GetPlayerServerId(PlayerId()) : +arg;
76
- if (!value || GetPlayerFromServerId(value) === -1)
77
- value = undefined;
78
- }
79
- break;
80
- case "longString":
81
- value = raw.substring(raw.indexOf(arg));
82
- break;
83
- }
84
- if (value === undefined && (!param.optional || (param.optional && arg))) {
85
- return Citizen.trace(`^1command '${raw.split(" ")[0] || raw}' received an invalid ${param.type} for argument ${index + 1} (${param.name}), received '${arg}'^0`);
86
- }
87
- mapped[param.name] = value;
88
- return true;
89
- });
90
- return result ? mapped : null;
91
- }
92
- async call(source, args, raw = args.join(" ")) {
93
- const parsed = this.mapArguments(source, args, raw);
94
- if (!parsed)
95
- return;
96
- try {
97
- await this.#handler(parsed);
98
- }
99
- catch (err) {
100
- Citizen.trace(`^1command '${raw.split(" ")[0] || raw}' failed to execute!^0\n${err.message}`);
101
- }
102
- }
103
- }
package/Convar.js DELETED
@@ -1,50 +0,0 @@
1
- import { GlobalData } from "./GlobalData";
2
- export class Convar {
3
- /**
4
- * @returns the current console buffer
5
- */
6
- buffer() {
7
- CLIENT: {
8
- if (GlobalData.IS_CLIENT) {
9
- throw new Error("This function isn't available on the client");
10
- }
11
- }
12
- return GetConsoleBuffer();
13
- }
14
- get(variable, defaultVar) {
15
- return GetConvar(variable, defaultVar);
16
- }
17
- getInt(variable, defaultVar) {
18
- return GetConvarInt(variable, defaultVar);
19
- }
20
- getFloat(varName, defaultVar) {
21
- return GetConvarFloat(varName, defaultVar);
22
- }
23
- getBool(varName, defaultVar) {
24
- return GetConvarBool(varName, defaultVar);
25
- }
26
- set(variable, value) {
27
- CLIENT: {
28
- if (GlobalData.IS_CLIENT) {
29
- throw new Error("This function isn't available on the client");
30
- }
31
- }
32
- SetConvar(variable, value);
33
- }
34
- setReplicated(variable, value) {
35
- CLIENT: {
36
- if (GlobalData.IS_CLIENT) {
37
- throw new Error("This function isn't available on the client");
38
- }
39
- }
40
- SetConvarReplicated(variable, value);
41
- }
42
- setServerInfo(variable, value) {
43
- CLIENT: {
44
- if (GlobalData.IS_CLIENT) {
45
- throw new Error("This function isn't available on the client");
46
- }
47
- }
48
- SetConvarServerInfo(variable, value);
49
- }
50
- }
package/GlobalData.js DELETED
@@ -1,8 +0,0 @@
1
- export class GlobalData {
2
- static CurrentResource = GetCurrentResourceName();
3
- static IS_SERVER = IsDuplicityVersion();
4
- static IS_CLIENT = !GlobalData.IS_SERVER;
5
- static NetworkTick = null;
6
- static NetworkedTicks = [];
7
- static EnablePrettyPrint = true;
8
- }
package/Kvp.js DELETED
@@ -1,141 +0,0 @@
1
- export class Kvp {
2
- /**
3
- * Returns the value associated with a key as a number.
4
- */
5
- getNumber(key) {
6
- return GetResourceKvpInt(key);
7
- }
8
- /**
9
- * Returns the value associated with a key as a float.
10
- */
11
- getFloat(key) {
12
- return GetResourceKvpFloat(key);
13
- }
14
- /**
15
- * Returns the value associated with a key as a string.
16
- */
17
- getString(key) {
18
- return GetResourceKvpString(key);
19
- }
20
- /**
21
- * Returns the value associated with a key as a parsed JSON string.
22
- */
23
- getJson(key) {
24
- const str = GetResourceKvpString(key);
25
- return str ? JSON.parse(str) : null;
26
- }
27
- /**
28
- * Sets the value associated with a key as a number.
29
- * @param async set the value using an async operation.
30
- */
31
- setNumber(key, value, async = false) {
32
- return async
33
- ? SetResourceKvpIntNoSync(key, value)
34
- : SetResourceKvpInt(key, value);
35
- }
36
- /**
37
- * Sets the value associated with a key as a float.
38
- * @param async set the value using an async operation.
39
- */
40
- setFloat(key, value, async = false) {
41
- return async
42
- ? SetResourceKvpFloatNoSync(key, value)
43
- : SetResourceKvpFloat(key, value);
44
- }
45
- /**
46
- * Sets the value associated with a key as a string.
47
- * @param async set the value using an async operation.
48
- */
49
- setString(key, value, async = false) {
50
- return async
51
- ? SetResourceKvpNoSync(key, value)
52
- : SetResourceKvp(key, value);
53
- }
54
- /**
55
- * Sets the value associated with a key as a JSON string.
56
- * @param async set the value using an async operation.
57
- */
58
- setJson(key, value, async = false) {
59
- const str = JSON.stringify(value);
60
- return async ? SetResourceKvpNoSync(key, str) : SetResourceKvp(key, str);
61
- }
62
- /**
63
- * Sets the value associated with a key as a JSON string.
64
- * @param async set the value using an async operation.
65
- */
66
- set(key, value, async = false) {
67
- switch (typeof value) {
68
- case "function":
69
- case "symbol":
70
- throw new Error(`Failed to set Kvp for invalid type '${typeof value}'`);
71
- case "undefined":
72
- return this.delete(key, async);
73
- case "object":
74
- return this.setJson(key, value, async);
75
- case "boolean":
76
- value = value ? 1 : 0;
77
- case "number":
78
- return Number.isInteger(value)
79
- ? this.setNumber(key, value, async)
80
- : this.setFloat(key, value, async);
81
- default:
82
- value = String(value);
83
- return this.setString(key, value, async);
84
- }
85
- }
86
- /**
87
- * Deletes the specified value for key.
88
- * @param async remove the value using an async operation
89
- */
90
- delete(key, async = false) {
91
- return async ? DeleteResourceKvpNoSync(key) : DeleteResourceKvp(key);
92
- }
93
- /**
94
- * Commits pending asynchronous operations to disk, ensuring data consistency.
95
- *
96
- * Should be called after calling set methods using the async flag.
97
- */
98
- flush() {
99
- FlushResourceKvp();
100
- }
101
- getAllKeys(prefix) {
102
- const keys = [];
103
- const handle = StartFindKvp(prefix);
104
- if (handle === -1)
105
- return keys;
106
- let key;
107
- do {
108
- key = FindKvp(handle);
109
- if (key)
110
- keys.push(key);
111
- } while (key);
112
- EndFindKvp(handle);
113
- return keys;
114
- }
115
- /**
116
- * Returns an array of keys which match or contain the given keys.
117
- */
118
- getKeys(prefix) {
119
- return typeof prefix === "string"
120
- ? this.getAllKeys(prefix)
121
- : prefix.flatMap((key) => this.getAllKeys(key));
122
- }
123
- /**
124
- * Get all values from keys in an array as the specified type.
125
- */
126
- getValuesAsType(prefix, type) {
127
- const values = this.getKeys(prefix);
128
- return values.map((key) => {
129
- switch (type) {
130
- case "number":
131
- return this.getNumber(key);
132
- case "float":
133
- return this.getFloat(key);
134
- case "string":
135
- return this.getString(key);
136
- default:
137
- return this.getJson(key);
138
- }
139
- });
140
- }
141
- }
package/Resource.js DELETED
@@ -1,47 +0,0 @@
1
- import { GlobalData } from "./GlobalData";
2
- export class Resource {
3
- name;
4
- constructor(name) {
5
- this.name = name;
6
- }
7
- getMetadata(metadataKey, index) {
8
- return GetResourceMetadata(this.name, metadataKey, index);
9
- }
10
- getPath() {
11
- return GetResourcePath(this.name);
12
- }
13
- loadFile(fileName) {
14
- return LoadResourceFile(this.name, fileName);
15
- }
16
- saveFile(fileName, data, length) {
17
- CLIENT: {
18
- if (GlobalData.IS_CLIENT) {
19
- throw new Error("This function isn't available on the client");
20
- }
21
- }
22
- return SaveResourceFile(this.name, fileName, data, length);
23
- }
24
- scheduleTick() {
25
- CLIENT: {
26
- if (GlobalData.IS_CLIENT) {
27
- throw new Error("This function isn't available on the client");
28
- }
29
- }
30
- return ScheduleResourceTick(this.name);
31
- }
32
- start() {
33
- StartResource(this.name);
34
- }
35
- stop() {
36
- StopResource(this.name);
37
- }
38
- static startResource(name) {
39
- StartResource(name);
40
- }
41
- static stopResource(name) {
42
- StopResource(name);
43
- }
44
- static resourceCount() {
45
- return GetNumResources();
46
- }
47
- }
package/decors/Events.js DELETED
@@ -1,217 +0,0 @@
1
- import { GlobalData } from "../GlobalData";
2
- export var ConVarType;
3
- (function (ConVarType) {
4
- ConVarType[ConVarType["String"] = 0] = "String";
5
- ConVarType[ConVarType["Integer"] = 1] = "Integer";
6
- ConVarType[ConVarType["Float"] = 2] = "Float";
7
- ConVarType[ConVarType["Boolean"] = 3] = "Boolean";
8
- })(ConVarType || (ConVarType = {}));
9
- /**
10
- * Disables pretty printing in error messages
11
- */
12
- export const DisablePrettyPrint = () => (GlobalData.EnablePrettyPrint = false);
13
- // TODO: Have a way to clean all of this up (maybe hook Symbol.disposable
14
- // somehow?)
15
- /*
16
- * Registers the export call for {exportName} to this method
17
- */
18
- export function Exports(exportName) {
19
- return function actualDecorator(originalMethod, context) {
20
- if (context.private) {
21
- throw new Error("Exports does not work on private methods, please mark the method as public");
22
- }
23
- context.addInitializer(function () {
24
- const t = this;
25
- exports(exportName, (...args) => {
26
- return originalMethod.call(t, ...args);
27
- });
28
- });
29
- };
30
- }
31
- /**
32
- * Registers the Event call for {@link eventName} to this method.
33
- *
34
- * This has internal pretty-printing to make errors easier to track, if
35
- * you want to disable this you will need to call {@link DisablePrettyPrint}, or if you're
36
- * using esbuild you can add `REMOVE_EVENT_LOG` to your drop label {@link https://esbuild.github.io/api/#drop-labels}
37
- *
38
- * @param eventName the event to bind to
39
- */
40
- export function Event(eventName) {
41
- return function actualDecorator(originalMethod, context) {
42
- if (context.private) {
43
- throw new Error("Event does not work on private methods, please mark the method as public");
44
- }
45
- context.addInitializer(function () {
46
- const t = this;
47
- on(eventName, (...args) => {
48
- try {
49
- return originalMethod.call(t, ...args);
50
- }
51
- catch (e) {
52
- REMOVE_EVENT_LOG: {
53
- if (!GlobalData.EnablePrettyPrint)
54
- return;
55
- console.error(`------- EVENT ERROR --------`);
56
- console.error(`Call to ${eventName} errored`);
57
- console.error(`Data: ${JSON.stringify(args)}`);
58
- console.error(`Error: ${e}`);
59
- console.error(`------- END EVENT ERROR --------`);
60
- }
61
- }
62
- });
63
- });
64
- };
65
- }
66
- /**
67
- * Registers the Net Event call for {@link eventName} to this method
68
- *
69
- *
70
- * This has internal pretty-printing to make errors easier to track, if
71
- * you want to disable this you will need to call {@link DisablePrettyPrint}, or if you're
72
- * using esbuild you can add `REMOVE_EVENT_LOG` to your drop label {@link https://esbuild.github.io/api/#drop-labels}
73
- *
74
- * @param eventName the event to bind this net event to
75
- * @param remoteOnly if the event should only accept remote calls, if set to true it will ignore any local call via `emit`, defaults to true
76
- */
77
- export function NetEvent(eventName, remoteOnly = true) {
78
- return function actualDecorator(originalMethod, context) {
79
- if (context.private) {
80
- throw new Error("NetEvent does not work on private methods, please mark the method as public");
81
- }
82
- context.addInitializer(function () {
83
- const t = this;
84
- onNet(eventName, (...args) => {
85
- const src = source;
86
- try {
87
- CLIENT: {
88
- if (remoteOnly && source !== 65535) {
89
- return;
90
- }
91
- }
92
- return originalMethod.call(t, ...args);
93
- }
94
- catch (e) {
95
- REMOVE_NET_EVENT_LOG: {
96
- if (!GlobalData.EnablePrettyPrint)
97
- return;
98
- console.error(`------- NET EVENT ERROR --------`);
99
- console.error(`Call to ${eventName} errored`);
100
- console.error(`Caller: ${src}`);
101
- console.error(`Data: ${JSON.stringify(args)}`);
102
- console.error(`Error: ${e}`);
103
- console.error(`------- END NET EVENT ERROR --------`);
104
- }
105
- }
106
- });
107
- });
108
- };
109
- }
110
- /**
111
- * Registers the NUI Event call for {eventName} to this method, the function signature
112
- * should be (data: unknown, cb: (data?: any) => void) => void
113
- * You shoud always execute `cb` with 'ok' if you don't want to send data back to
114
- * the UI, otherwise you'll cause a network error for the `fetch` request
115
- * @param eventName the event this will listen for
116
- */
117
- export function NuiEvent(eventName) {
118
- return function actualDecorator(originalMethod, context) {
119
- if (context.private) {
120
- throw new Error("NuiEvent does not work on private methods, please mark the method as public");
121
- }
122
- context.addInitializer(function () {
123
- const t = this;
124
- RegisterNuiCallback(eventName, (...args) => {
125
- return originalMethod.call(t, ...args);
126
- });
127
- });
128
- };
129
- }
130
- const get_convar_fn = (con_var_type) => {
131
- switch (con_var_type) {
132
- case ConVarType.String:
133
- return GetConvar;
134
- case ConVarType.Integer:
135
- return GetConvarInt;
136
- case ConVarType.Float:
137
- return GetConvarFloat;
138
- case ConVarType.Boolean:
139
- return GetConvarBool;
140
- // needed so typescript wont complain about "unreachable code" for the error below
141
- default:
142
- }
143
- // never guess people wont manage to hit this
144
- throw new Error("Got invalid ConVarType");
145
- };
146
- /**
147
- * Gets the specified `ConVar`s value, this will bind to the param.
148
- * @param name the convar name
149
- * @param is_floating_point if the convar is floating point, this should be explicitly set to true if your convar will be a float
150
- */
151
- export function ConVar(name, is_floating_point, deserialize) {
152
- // the implementation shows that this will be _initialValue, but it doesn't
153
- // seem to actually be???
154
- return function actualDecorator(_initialValue, context, ..._args) {
155
- if (context.private) {
156
- throw new Error("ConVar does not work on private types, please mark the field as public");
157
- }
158
- context.addInitializer(function () {
159
- const t = this;
160
- const default_value = Reflect.get(t, context.name);
161
- const default_type = typeof default_value;
162
- let con_var_type = null;
163
- if (default_type == "number") {
164
- if (is_floating_point || !Number.isInteger(default_value)) {
165
- con_var_type = ConVarType.Float;
166
- }
167
- else {
168
- con_var_type = ConVarType.Integer;
169
- }
170
- }
171
- else if (default_type == "boolean") {
172
- con_var_type = ConVarType.Boolean;
173
- }
174
- else if (default_value == "string") {
175
- con_var_type = ConVarType.String;
176
- }
177
- // if we're not set that means our default value was not valid, and likely
178
- // undefined (which we should just get rid of) or an object, and the
179
- // caller should send a deserialize function to work with.
180
- if (!deserialize && con_var_type === null) {
181
- throw new Error("You should provide a deserialize function if you want to convert this to an object type");
182
- }
183
- // if we got past our previous check then we're going to take the data as
184
- // a string and pass it to the deserialize function
185
- if (con_var_type === null) {
186
- con_var_type = ConVarType.String;
187
- }
188
- const con_var_fn = get_convar_fn(con_var_type);
189
- // nice and easy wrapper
190
- const get_convar_value = () => {
191
- const data = con_var_fn(name, default_value);
192
- return deserialize ? deserialize(data) : data;
193
- };
194
- Reflect.set(t, context.name, get_convar_value());
195
- AddConvarChangeListener(name, () => {
196
- Reflect.set(t, context.name, get_convar_value());
197
- });
198
- });
199
- };
200
- }
201
- /**
202
- * Gets called per server/client tick, this is asyncronous though, if you await
203
- * in it, it will not be called until whatever was being awaited resolves.
204
- */
205
- export function SetTick() {
206
- return function actualDecorator(originalMethod, context) {
207
- if (context.private) {
208
- throw new Error("SetTick does not work on private types, please mark the field as public");
209
- }
210
- context.addInitializer(function () {
211
- const t = this;
212
- setTick(async () => {
213
- await originalMethod.call(t);
214
- });
215
- });
216
- };
217
- }