Compare commits

..

32 Commits

Author SHA1 Message Date
469d970654 Merge branch 'dev' 2024-10-30 16:29:29 +00:00
217e0ddf01 Merge pull request 'Server/Client middlewares + JSDoc' (#6) from unstable into dev
Reviewed-on: #6
2024-10-30 16:21:29 +00:00
ea572070ef versions rollback 2024-10-30 16:21:03 +00:00
7308fc26e0 v0.2.1-0.2.0-alpha.2.0 2024-10-30 16:18:08 +00:00
ffd542c1de v0.2.1-0.2.0-alpha.1.0 2024-10-30 16:17:28 +00:00
914300924a v0.2.0 2024-10-30 16:16:45 +00:00
bc295a777b jsdoc 2024-10-30 15:38:06 +00:00
cd27764a30 jsdoc 2024-10-30 15:27:22 +00:00
30d125ce8e version bump 2024-10-29 17:06:14 +00:00
d56475d08a Merge pull request 'Consistency updates + cleanup' (#5) from unstable into dev
Reviewed-on: #5
2024-10-29 17:03:31 +00:00
622676d189 feat core
- server/client middlewares
2024-10-29 17:03:07 +00:00
d8df9fa7ef fix core
- renaming done
2024-10-28 17:40:25 +00:00
d9b917c024 core version bump 2024-10-28 17:37:17 +00:00
cbbf4f38e6 upd core
- typed server inner rpc
- client minor fixes
- sharing browser with rpc on client
2024-10-28 17:30:28 +00:00
3bbf1e2209 upd core
- typed client inner rpc
- better type organization
2024-10-28 16:53:42 +00:00
9fe9bad840 upd core
- renamed cef -> browser
- added browser logger + custom logger option
2024-10-28 16:35:16 +00:00
588bb42d04 upd core
- types now use namespace to avoid bloating
- moved items for further usage into data folder
2024-10-28 15:20:43 +00:00
3a4fe19df0 upd readme bump 2024-10-28 15:14:41 +00:00
c8e5bdf375 Merge branch 'dev' into unstable 2024-10-28 15:10:25 +00:00
a675114b41 upd core
- changed local shared types package name
2024-10-28 15:10:00 +00:00
54781d50b2 upd core
- changed local rpc to remote dependency
2024-10-28 15:04:39 +00:00
de33fe4763 versions bump 2024-10-28 13:20:51 +00:00
d3d75b338d v0.2.5 2024-10-28 13:02:24 +00:00
04eb724073 v0.2.4 2024-10-28 12:59:44 +00:00
e4950b6c99 Merge remote-tracking branch 'origin/dev' into dev
# Conflicts:
#	lerna.json
#	rpc/package.json
2024-10-28 12:57:58 +00:00
Oleksandr Honcharov
8f856d929f v0.2.3 2024-10-28 14:54:48 +02:00
Oleksandr Honcharov
ee8210f140 v0.2.2 2024-10-28 14:54:19 +02:00
Oleksandr Honcharov
74c0215366 v0.2.2 2024-10-28 14:53:05 +02:00
19b1b770f6 v0.2.1 2024-10-28 12:51:53 +00:00
Oleksandr Honcharov
96c92f9d19 v0.2.1 2024-10-28 14:51:45 +02:00
2b287f06a2 v0.2.0 2024-10-28 12:46:24 +00:00
2f2b1da99b upd
changed packages to organization
2024-10-28 12:43:15 +00:00
55 changed files with 9512 additions and 7558 deletions

32
browser/package.json Normal file
View File

@ -0,0 +1,32 @@
{
"name": "@entityseven/rage-fw-browser",
"version": "0.2.0",
"main": "dist/index.js",
"types": "dist/src/index.d.ts",
"files": [
"dist/**/*",
"readme.md"
],
"scripts": {
"build": "tsup"
},
"dependencies": {
"@entityseven/rage-fw-rpc": "latest"
},
"peerDependencies": {
"@entityseven/rage-fw-shared-types": "workspace:^",
"@ragempcommunity/types-cef": "^2.1.8"
},
"description": "RageFW CEF side",
"keywords": [],
"author": "SashaGoncharov19",
"contributors": [
{
"name": "rilaxik",
"email": "dev.rilaxik@gmail.com",
"url": "https://github.com/rilaxik"
}
],
"license": "MIT",
"gitHead": "ffd542c1deddb3033e16e0dae7557313ae09b05f"
}

187
browser/src/core/browser.ts Normal file
View File

@ -0,0 +1,187 @@
import { Helper } from './helper'
import { rpc } from './rpc'
import type * as T from '../types'
import {
RageFW_BrowserEvent,
RageFW_ClientEvent,
RageFW_ServerEvent,
} from '../types'
/** Browser-side interactions */
export class Browser extends Helper {
constructor() {
super()
}
/**
* Setter. Enables console debug logs for events
*/
set debugLogs(debug: boolean) {
this.debugLogs_ = debug
}
/**
* Setter. Provides an ability to specify custom logger function to get special formatting. Using this enables ``debugLogs``
*/
set customLogger(
fn: (method: string, eventName: string, ...args: unknown[]) => unknown,
) {
this.customLogger_ = fn
}
/**
* Registers a browser event with an associated callback
*
* @param eventName - The name of the event to register
* @param callback - The callback function to be executed when the event is triggered
* @returns {Browser} The current browser instance, enabling method chaining
*
* @example
* // Registering an event
* fw.event.register("showNotification", (message, color) => {
* // do something
* })
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public register<EventName extends T.RageFW_BrowserEvent>(
eventName: EventName,
callback: T.RageFW_BrowserCallback<EventName>,
): Browser {
this.log_('register', eventName, callback)
rpc.register<
Parameters<typeof callback>,
ReturnType<typeof callback>,
EventName
>(eventName, async (...data) => await callback(...data))
return this
}
/**
* Unregisters a browser event, removing the associated callback
*
* @param eventName - The name of the event to unregister
* @returns {Browser} The current browser instance, enabling method chaining
*
* @example
* // Unregistering an event
* fw.event.unregister("showNotification")
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public unregister<EventName extends T.RageFW_BrowserEvent>(
eventName: EventName,
): Browser {
rpc.unregister<EventName>(eventName)
return this
}
/**
* Triggers a browser event from the browser with arguments from shared types
*
* Formerly known as ``call`` or ``emit``
*
* @param eventName - The name of the browser event to trigger
* @param [args] - Arguments for the browser event, if present
* @returns {Promise} resolving to the browser's response for the event
*
* @example
* // Triggering a browser event without arguments
* fw.event.trigger("browserEventName")
*
* @example
* // Triggering a browser event with arguments
* fw.event.trigger("browserEventName", ["message to me"])
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public async trigger<EventName extends T.RageFW_BrowserEvent>(
eventName: EventName,
...args: T._BrowserEventHasArgs<EventName> extends true
? [T.RageFW_BrowserArgs<EventName>]
: []
): Promise<T.RageFW_BrowserReturn<EventName>> {
this.log_('[RPC](trigger):', eventName, ...args)
return await rpc.call<
typeof args,
EventName,
T.RageFW_BrowserReturn<EventName>
>(eventName, args)
}
/**
* Triggers a server event from the browser with arguments from shared types
*
* Formerly known as ``callServer`` or ``emitServer``
*
* @param eventName - The name of the server event to trigger
* @param [args] - Arguments for the server event, if present
* @returns {Promise} resolving to the server's response for the event
*
* @example
* // Triggering a server event without arguments
* fw.event.triggerServer("serverEventName")
*
* @example
* // Triggering a server event with arguments
* fw.event.triggerServer("serverEventName", ["message to server"])
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public async triggerServer<EventName extends T.RageFW_ServerEvent>(
eventName: EventName,
...args: T._ServerEventHasArgs<EventName> extends true
? [T.RageFW_ServerArgs<EventName>]
: []
): Promise<T.RageFW_ServerReturn<EventName>> {
this.log_('[RPC](triggerServer):', eventName, ...args)
return await rpc.callServer<
typeof args,
EventName,
T.RageFW_ServerReturn<EventName>
>(eventName, args)
}
/**
* Triggers a client event from the browser with arguments from shared types
*
* Formerly known as ``callClient`` or ``emitClient``
*
* @param eventName - The name of the client event to trigger
* @param [args] - Arguments for the client event, if present
* @returns {Promise} resolving to the client's response for the event
*
* @example
* // Triggering a client event without arguments
* fw.event.triggerClient("clientEventName")
*
* @example
* // Triggering a client event with arguments
* fw.event.triggerClient("clientEventName", ["message to client"])
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public async triggerClient<EventName extends T.RageFW_ClientEvent>(
eventName: EventName,
...args: T._ClientEventHasArgs<EventName> extends true
? [T.RageFW_ClientArgs<EventName>]
: []
): Promise<T.RageFW_ClientReturn<EventName>> {
this.log_('[RPC](triggerClient):', eventName, ...args)
return await rpc.callClient<
typeof args,
EventName,
T.RageFW_ClientReturn<EventName>
>(eventName, args)
}
}
// new Browser()
// .register('customCefEvent', async (a, b) => true)
// .triggerServer('customServerEvent', ['', 1])

View File

@ -0,0 +1,21 @@
export class Helper {
protected debugLogs_: boolean = false
protected customLogger_:
| undefined
| ((method: string, eventName: string, ...args: unknown[]) => unknown) =
undefined
constructor() {}
protected log_(
method: string,
eventName: string,
...args: unknown[]
): void {
if (this.customLogger_) {
this.customLogger_(method, eventName, ...args)
} else if (this.debugLogs_) {
console.log('[RPC](' + method + ')', eventName + ':', ...args)
}
}
}

View File

@ -0,0 +1,3 @@
export * from './browser'
export * from './helper'
export * from './rpc'

6
browser/src/core/rpc.ts Normal file
View File

@ -0,0 +1,6 @@
import { Rpc } from '@entityseven/rage-fw-rpc'
export const rpc = new Rpc({
forceBrowserDevMode: process.env.RageFW_forceBrowserDevMode === 'true',
debugLogs: false,
})

16
browser/src/index.ts Normal file
View File

@ -0,0 +1,16 @@
import { Browser, rpc } from './core'
/**
* Package used on a browser-side of your Rage:MP Server
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
export const fw = {
/** Browser-side interactions */
event: new Browser(),
/** ``rage-fw-rpc`` instance used under the hood. It is highly recommended to use this one if you need it instead of creating a new instance */
rpc,
}
;(async () => {
await fw.event.triggerClient('cefReady')
})()

View File

@ -0,0 +1,40 @@
import type { RageFW_ICustomBrowserEvent } from '@entityseven/rage-fw-shared-types'
export type { RageFW_ICustomBrowserEvent } from '@entityseven/rage-fw-shared-types'
/**
* Union of all available browser event names
* These only include custom events
*/
export type RageFW_BrowserEvent = keyof RageFW_ICustomBrowserEvent
/**
* Array of arguments of an event you pass as a generic
* These only include custom browser events
*/
export type RageFW_BrowserArgs<K extends RageFW_BrowserEvent> = Parameters<
RageFW_ICustomBrowserEvent[K]
>
/**
* Return type of event you pass as a generic
* These only include custom browser events
*/
export type RageFW_BrowserReturn<K extends RageFW_BrowserEvent> = ReturnType<
RageFW_ICustomBrowserEvent[K]
>
/**
* Callback (function) of event you pass as a generic
* These only include custom browser events
*/
export type RageFW_BrowserCallback<K extends keyof RageFW_ICustomBrowserEvent> =
(...args: RageFW_BrowserArgs<K>) => Promise<RageFW_BrowserReturn<K>>
export type _BrowserEventHasArgs<
EventName extends keyof RageFW_ICustomBrowserEvent,
> = keyof RageFW_ICustomBrowserEvent extends never
? false
: Parameters<RageFW_ICustomBrowserEvent[EventName]>[0] extends undefined
? false
: true

View File

@ -1,6 +1,6 @@
import type { RageFW_ICustomClientEvent } from 'rage-fw-shared-types' import type { RageFW_ICustomClientEvent } from '@entityseven/rage-fw-shared-types'
export type { RageFW_ICustomClientEvent } from 'rage-fw-shared-types' export type { RageFW_ICustomClientEvent } from '@entityseven/rage-fw-shared-types'
/** /**
* Union of all available client event names * Union of all available client event names

View File

@ -1,3 +1,3 @@
export * from './cef' export * from './browser'
export * from './client' export * from './client'
export * from './server' export * from './server'

View File

@ -1,6 +1,6 @@
import type { RageFW_ICustomServerEvent } from 'rage-fw-shared-types' import type { RageFW_ICustomServerEvent } from '@entityseven/rage-fw-shared-types'
export type { RageFW_ICustomServerEvent } from 'rage-fw-shared-types' export type { RageFW_ICustomServerEvent } from '@entityseven/rage-fw-shared-types'
/** /**
* Union of all available server event names * Union of all available server event names

View File

@ -1,29 +0,0 @@
{
"name": "rage-fw-cef",
"version": "0.1.0",
"main": "dist/index.js",
"types": "dist/src/index.d.ts",
"files": [
"dist/**/*",
"readme.md"
],
"scripts": {
"build": "tsup"
},
"dependencies": {
"rage-fw-rpc": "workspace:^"
},
"peerDependencies": {
"@ragempcommunity/types-cef": "^2.1.8",
"rage-fw-shared-types": "workspace:^"
},
"description": "RageFW CEF side",
"keywords": [],
"author": "SashaGoncharov19",
"contributors": [{
"name": "rilaxik",
"email": "dev.rilaxik@gmail.com",
"url": "https://github.com/rilaxik"
}],
"license": "MIT"
}

View File

@ -1,113 +0,0 @@
import { Rpc } from 'rage-fw-rpc'
import type {
_CefEventHasArgs,
_ClientEventHasArgs,
_ServerEventHasArgs,
RageFW_CefArgs,
RageFW_CefCallback,
RageFW_CefReturn,
RageFW_ClientArgs,
RageFW_ClientReturn,
RageFW_ICustomCefEvent,
RageFW_ICustomClientEvent,
RageFW_ICustomServerEvent,
RageFW_ServerArgs,
RageFW_ServerReturn,
} from './types'
class Cef {
private _debugMode: boolean = false
private _rpc: Rpc = new Rpc()
constructor() {}
set debug(debug: boolean) {
this._debugMode = debug
}
get rpc(): Rpc {
return this._rpc
}
public register<EventName extends keyof RageFW_ICustomCefEvent>(
eventName: EventName,
callback: RageFW_CefCallback<EventName>,
): void {
if (this._debugMode) {
console.log('[RPC](register):', eventName, callback)
}
if ('mp' in window) {
this._rpc.register(eventName, callback)
}
}
public async trigger<EventName extends keyof RageFW_ICustomCefEvent>(
eventName: EventName,
...args: _CefEventHasArgs<EventName> extends true
? [RageFW_CefArgs<EventName>]
: []
): Promise<RageFW_CefReturn<EventName>> {
if (this._debugMode) {
console.log('[RPC](trigger):', eventName, ...args)
}
if ('mp' in window) {
return await this._rpc.call(eventName, args)
}
return Promise.reject(
'RageFW was started in window which does not contain MP',
)
}
public async triggerServer<
EventName extends keyof RageFW_ICustomServerEvent,
>(
eventName: EventName,
...args: _ServerEventHasArgs<EventName> extends true
? [RageFW_ServerArgs<EventName>]
: []
): Promise<RageFW_ServerReturn<EventName>> {
if (this._debugMode) {
console.log('[RPC](triggerServer):', eventName, ...args)
}
if ('mp' in window) {
return await this._rpc.callServer(eventName, args)
}
return Promise.reject(
'RageFW was started in window which does not contain MP',
)
}
public async triggerClient<
EventName extends keyof RageFW_ICustomClientEvent,
>(
eventName: EventName,
...args: _ClientEventHasArgs<EventName> extends true
? [RageFW_ClientArgs<EventName>]
: []
): Promise<RageFW_ClientReturn<EventName>> {
if (this._debugMode) {
console.log('[RPC](triggerClient):', eventName, ...args)
}
if ('mp' in window) {
return await this._rpc.callClient(eventName, args)
}
return Promise.reject(
'RageFW was started in window which does not contain MP',
)
}
}
export const fw = {
event: new Cef(),
}
;(async () => {
await fw.event.triggerClient('cefReady')
})()

View File

@ -1,40 +0,0 @@
import { RageFW_ICustomCefEvent } from 'rage-fw-shared-types'
export { RageFW_ICustomCefEvent } from 'rage-fw-shared-types'
/**
* Union of all available cef event names
* These only include custom events
*/
export type RageFW_CefEvent = keyof RageFW_ICustomCefEvent
/**
* Array of arguments of an event you pass as a generic
* These only include custom cef events
*/
export type RageFW_CefArgs<K extends RageFW_CefEvent> = Parameters<
RageFW_ICustomCefEvent[K]
>
/**
* Return type of event you pass as a generic
* These only include custom cef events
*/
export type RageFW_CefReturn<K extends RageFW_CefEvent> = ReturnType<
RageFW_ICustomCefEvent[K]
>
/**
* Callback (function) of event you pass as a generic
* These only include custom cef events
*/
export type RageFW_CefCallback<K extends keyof RageFW_ICustomCefEvent> = (
args: RageFW_CefArgs<K>,
) => Promise<RageFW_CefReturn<K>>
export type _CefEventHasArgs<EventName extends keyof RageFW_ICustomCefEvent> =
keyof RageFW_ICustomCefEvent extends never
? false
: Parameters<RageFW_ICustomCefEvent[EventName]>[0] extends undefined
? false
: true

View File

@ -1,6 +1,6 @@
{ {
"name": "create-rage-fw", "name": "@entityseven/create-rage-fw",
"version": "0.1.0", "version": "0.1.1",
"bin": { "bin": {
"rage-fw": "dist/index.js" "rage-fw": "dist/index.js"
}, },

View File

@ -2,7 +2,7 @@
To make you life easier while using RageFW we created a basic CLI. At the moment automation we have only works via [pnpm](https://pnpm.io/) To make you life easier while using RageFW we created a basic CLI. At the moment automation we have only works via [pnpm](https://pnpm.io/)
``pnpm create rage-fw@latest`` ``pnpm create @entityseven/rage-fw@latest``
## TL;DR ## TL;DR
- ``Initialize new project`` - create new template project - ``Initialize new project`` - create new template project

View File

@ -1,6 +1,6 @@
{ {
"name": "rage-fw-client", "name": "@entityseven/rage-fw-client",
"version": "0.1.0", "version": "0.2.0",
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/src/index.d.ts", "types": "dist/src/index.d.ts",
"files": [ "files": [
@ -11,20 +11,22 @@
"build": "tsup" "build": "tsup"
}, },
"dependencies": { "dependencies": {
"rage-fw-rpc": "workspace:^" "@entityseven/rage-fw-rpc": "latest"
}, },
"peerDependencies": { "peerDependencies": {
"@ragempcommunity/types-client": "^2.1.8", "@entityseven/rage-fw-shared-types": "workspace:^",
"rage-fw-shared-types": "workspace:^" "@ragempcommunity/types-client": "^2.1.8"
}, },
"description": "RageFW Client side", "description": "RageFW Client side",
"keywords": [], "keywords": [],
"author": "SashaGoncharov19", "author": "SashaGoncharov19",
"contributors": [{ "contributors": [
{
"name": "rilaxik", "name": "rilaxik",
"email": "dev.rilaxik@gmail.com", "email": "dev.rilaxik@gmail.com",
"url": "https://github.com/rilaxik" "url": "https://github.com/rilaxik"
}], }
],
"license": "MIT", "license": "MIT",
"gitHead": "053e4fd12aa120d53e11e0d2009c0df78c1a2ad0" "gitHead": "ffd542c1deddb3033e16e0dae7557313ae09b05f"
} }

View File

@ -1,33 +1,86 @@
import { Rpc } from 'rage-fw-rpc' import { rpc } from './rpc'
import { Middleware } from './middleware'
import type { import type * as T from '../types'
RageFW_ClientArgs,
RageFW_ClientCallback,
RageFW_ClientEvent,
} from '../types'
/** Client-side interactions */
export class Client { export class Client {
private _rpc: Rpc = new Rpc() /**
* Registers a client event with an associated callback
get rpc(): Rpc { *
return this._rpc * @param eventName - The name of the event to register
} * @param callback - The callback function to be executed when the event is triggered
* @param [options] - Optional settings for callback execution
public register<EventName extends RageFW_ClientEvent>( * @param [options.middlewares] - Middleware functions to be checked before the callback executes
* @returns {Client} The current client instance, enabling method chaining
*
* @example
* // Registering an event
* fw.event.register("playerDeath", (player, reason, killer) => {
* fw.system.log.info(player, reason, killer)
* })
*
* @example
* // Registering an event with middlewares
* fw.event.register("playerDeath", (player, reason, killer) => {
* fw.system.log.info(player, reason, killer)
* }, {
* middlewares: [ignoreSuicide] // <- your middlewares here
* })
*
* // or
*
* fw.event.register("playerDeath", (player, reason, killer) => {
* fw.system.log.info(player, reason, killer)
* }, {
* middlewares: {
* executables: [ignoreSuicide], // <- your middlewares here
* onError: (msg) => fw.system.log.info(`${player.socialClub} has commited suicide`)
* }
* })
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public register<EventName extends T.RageFW_ClientEvent>(
eventName: EventName, eventName: EventName,
callback: RageFW_ClientCallback<EventName>, callback: T.RageFW_ClientCallback<EventName>,
): void { options?: {
this._rpc.register( middlewares?: T.RageFW_MiddlewareOptions<EventName>
eventName,
async (data: RageFW_ClientArgs<EventName>) => {
return await callback(data)
}, },
) ): Client {
rpc.register<
Parameters<typeof callback>,
ReturnType<typeof callback> | Promise<unknown>,
EventName
>(eventName, async (...data) => {
if (!options?.middlewares) return await callback(...data)
await Middleware.process(options.middlewares, callback, data)
})
return this
} }
public unregister<EventName extends RageFW_ClientEvent>( /**
* Unregisters a client event, removing the associated callback
*
* @param eventName - The name of the event to unregister
* @returns {Client} The current client instance, enabling method chaining
*
* @example
* // Unregistering an event
* fw.event.unregister("playerDeath")
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public unregister<EventName extends T.RageFW_ClientEvent>(
eventName: EventName, eventName: EventName,
): void { ): Client {
this._rpc.unregister(eventName) rpc.unregister<EventName>(eventName)
return this
} }
} }
// new Client()
// .register('customClientEvent', async (a, b) => true)
// .unregister('customClientEvent')

View File

@ -1,3 +1,5 @@
export * from './client' export * from './client'
export * from './player'
export * from './logger' export * from './logger'
export * from './middleware'
export * from './player'
export * from './rpc'

View File

@ -1,19 +1,40 @@
/**
* Used to log to a client in-game console
*/
export class Logger { export class Logger {
public error(...message: unknown[]) { /**
mp.console.logError( * Informational logs. Colored in white
`[${new Date().toLocaleTimeString()}] [ERROR] ${message.join(' ')}`, *
* @example
* fw.system.log.info('some information to be logged')
*/
public info(...message: unknown[]) {
mp.console.logInfo(
`[${new Date().toLocaleTimeString()}] [INFO] ${message.join(' ')}`,
) )
} }
/**
* Warning logs. Colored in yellow
*
* @example
* fw.system.log.warn('warning message')
*/
public warn(...message: unknown[]) { public warn(...message: unknown[]) {
mp.console.logWarning( mp.console.logWarning(
`[${new Date().toLocaleTimeString()}] [WARN] ${message.join(' ')}`, `[${new Date().toLocaleTimeString()}] [WARN] ${message.join(' ')}`,
) )
} }
public info(...message: unknown[]) { /**
mp.console.logInfo( * Error logs. Colored in red
`[${new Date().toLocaleTimeString()}] [INFO] ${message.join(' ')}`, *
* @example
* fw.system.log.info('some error information')
*/
public error(...message: unknown[]) {
mp.console.logError(
`[${new Date().toLocaleTimeString()}] [ERROR] ${message.join(' ')}`,
) )
} }
} }

View File

@ -0,0 +1,54 @@
import type * as T from '../types'
export class Middleware {
constructor() {}
private static async execute<EventName extends T.RageFW_ClientEvent>(
middlewares: T.RageFW_MiddlewareFunction<EventName>[],
args: T.RageFW_ClientArgs<EventName>,
): Promise<T.RageFW_MiddlewareResponseInternal> {
for (let i = 0; i < middlewares.length; i++) {
const result = await middlewares[i](...args)
if (typeof result === 'boolean' && !result)
return { success: result, id: i }
if (typeof result !== 'boolean' && !result.success)
return { ...result, id: i }
}
return {
success: true,
}
}
public static async process<EventName extends T.RageFW_ClientEvent>(
middlewareOptions: T.RageFW_MiddlewareOptions<EventName>,
callback: T.RageFW_ClientCallback<EventName>,
args: T.RageFW_ClientArgs<EventName>,
) {
if (Array.isArray(middlewareOptions)) {
const middlewaresResponse = await Middleware.execute(
middlewareOptions,
args,
)
if (middlewaresResponse.success) return await callback(...args)
} else {
const middlewaresResponse = await Middleware.execute(
middlewareOptions.executables,
args,
)
if (middlewaresResponse.success) {
return await callback(...args)
} else {
middlewareOptions.onError(
middlewaresResponse.message ??
'Middleware with id ' +
middlewaresResponse.id +
' failed',
)
}
}
}
}

View File

@ -1,53 +1,118 @@
import { Rpc } from 'rage-fw-rpc' import { rpc } from './rpc'
import type { RageFW_ICustomClientEvent } from 'rage-fw-shared-types' import type * as T from '../types'
import {
_CefEventHasArgs,
_ClientEventHasArgs,
_ServerEventHasArgs,
RageFW_CefArgs,
RageFW_CefEvent,
RageFW_CefReturn,
RageFW_ClientArgs,
RageFW_ClientReturn,
RageFW_ClientServerEvent,
RageFW_ClientServerArgs,
RageFW_ClientServerReturn,
} from '../types'
/** Handles event manipulations that require player to be present in context */
export class Player { export class Player {
private _rpc: Rpc = new Rpc() private _browser: BrowserMp | undefined = undefined
public browser: BrowserMp | undefined
get rpc(): Rpc { /**
return this._rpc * Setter. Also shares browser with ``rage-fw-rpc``
} */
public trigger<EventName extends keyof RageFW_ICustomClientEvent>( set browser(browser: BrowserMp) {
eventName: EventName, this._browser = browser
...args: _ClientEventHasArgs<EventName> extends true rpc.browser = browser
? [RageFW_ClientArgs<EventName>]
: []
): Promise<RageFW_ClientReturn<EventName>> {
return this._rpc.call(eventName, args)
} }
public triggerServer<EventName extends RageFW_ClientServerEvent>( /**
* Triggers a client event from the client with arguments from shared types
*
* Formerly known as ``call`` or ``emit``
*
* @param eventName - The name of the client event to trigger
* @param [args] - Arguments for the client event, if present
* @returns {Promise} resolving to the client's response for the event
*
* @example
* // Triggering a client event without arguments
* fw.player.trigger("clientEventName")
*
* @example
* // Triggering a client event with arguments
* fw.player.trigger("clientEventName", ["message to me"])
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public async trigger<EventName extends keyof T.RageFW_ICustomClientEvent>(
eventName: EventName, eventName: EventName,
...args: _ServerEventHasArgs<EventName> extends true ...args: T._ClientEventHasArgs<EventName> extends true
? [RageFW_ClientServerArgs<EventName>] ? [T.RageFW_ClientArgs<EventName>]
: [] : []
): Promise<RageFW_ClientServerReturn<EventName>> { ): Promise<T.RageFW_ClientReturn<EventName>> {
return this._rpc.callServer(eventName, args) return await rpc.call<
typeof args,
EventName,
T.RageFW_ClientReturn<EventName>
>(eventName, args)
} }
public triggerBrowser<EventName extends RageFW_CefEvent>( /**
* Triggers a server event from the client with arguments from shared types
*
* Formerly known as ``callServer`` or ``emitServer``
*
* @param eventName - The name of the server event to trigger
* @param [args] - Arguments for the server event, if present
* @returns {Promise} resolving to the server's response for the event
*
* @example
* // Triggering a server event without arguments
* fw.player.triggerServer("serverEventName")
*
* @example
* // Triggering a server event with arguments
* fw.player.triggerServer("serverEventName", ["message to server"])
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public async triggerServer<EventName extends T.RageFW_ServerEvent>(
eventName: EventName, eventName: EventName,
...args: _CefEventHasArgs<EventName> extends true ...args: T._ServerEventHasArgs<EventName> extends true
? [RageFW_CefArgs<EventName>] ? [T.RageFW_ServerArgs<EventName>]
: [] : []
): Promise<RageFW_CefReturn<EventName>> { ): Promise<T.RageFW_ClientServerReturn<EventName>> {
if (!this.browser) return await rpc.callServer<
typeof args,
EventName,
T.RageFW_ClientServerReturn<EventName>
>(eventName, args)
}
/**
* Triggers a browser event from the client with arguments from shared types
*
* Formerly known as ``callBrowser`` or ``emitBrowser``
*
* @param eventName - The name of the browser event to trigger
* @param [args] - Arguments for the browser event, if present
* @returns {Promise} resolving to the browser's response for the event
*
* @example
* // Triggering a browser event without arguments
* fw.player.triggerBrowser("browserEventName")
*
* @example
* // Triggering a browser event with arguments
* fw.player.triggerBrowser("browserEventName", ["message to browser"])
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public async triggerBrowser<EventName extends T.RageFW_BrowserEvent>(
eventName: EventName,
...args: T._BrowserEventHasArgs<EventName> extends true
? [T.RageFW_BrowserArgs<EventName>]
: []
): Promise<T.RageFW_BrowserReturn<EventName>> {
if (!this._browser)
throw new Error('You need to initialize browser first') throw new Error('You need to initialize browser first')
return this._rpc.callBrowser(this.browser, eventName, args)
return await rpc.callBrowser<
typeof args,
EventName,
T.RageFW_BrowserReturn<EventName>
>(eventName, args)
} }
} }
// new Player().trigger('customClientEvent', ['', 1])
// new Player().triggerServer('customServerEvent', ['', 1])
// new Player().triggerBrowser('customCefEvent', ['', 1])

5
client/src/core/rpc.ts Normal file
View File

@ -0,0 +1,5 @@
import { Rpc } from '@entityseven/rage-fw-rpc'
export const rpc = new Rpc({
debugLogs: false,
})

View File

@ -1,9 +1,22 @@
import { Client, Logger, Player } from './core' import { Client, Logger, Player, rpc } from './core'
export type { RageFW_MiddlewareFunction } from './types'
/**
* Package used on a client-side of your Rage:MP Server
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
export const fw = { export const fw = {
/** Client-side interactions */
event: new Client(), event: new Client(),
/** Handles event manipulations that require player to be present in context */
player: new Player(), player: new Player(),
/** Handles functions used to interact with the client environment */
system: { system: {
/** Used to log in a client in-game console */
log: new Logger(), log: new Logger(),
}, },
/** ``rage-fw-rpc`` instance used under the hood. It is highly recommended to use this one if you need it instead of creating a new instance */
rpc,
} }

View File

@ -1,20 +1,29 @@
/// <reference types="@ragempcommunity/types-client" /> /// <reference types="@ragempcommunity/types-client" />
import type { RageFW_ICustomCefEvent } from 'rage-fw-shared-types' import type { RageFW_ICustomBrowserEvent } from '@entityseven/rage-fw-shared-types'
export type RageFW_CefEvent = keyof RageFW_ICustomCefEvent /**
* Union of all available browser event names callable from client
* These only include custom events
*/
export type RageFW_BrowserEvent = keyof RageFW_ICustomBrowserEvent
export type RageFW_CefArgs<K extends RageFW_CefEvent> = Parameters< /**
RageFW_ICustomCefEvent[K] * Array of arguments for an event, name of which you pass as a generic
* These only include custom events
*/
export type RageFW_BrowserArgs<K extends RageFW_BrowserEvent> = Parameters<
RageFW_ICustomBrowserEvent[K]
> >
export type RageFW_CefReturn<K extends RageFW_CefEvent> = ReturnType< export type RageFW_BrowserReturn<K extends RageFW_BrowserEvent> = ReturnType<
RageFW_ICustomCefEvent[K] RageFW_ICustomBrowserEvent[K]
> >
export type _CefEventHasArgs<EventName extends keyof RageFW_ICustomCefEvent> = export type _BrowserEventHasArgs<
keyof RageFW_ICustomCefEvent extends never EventName extends keyof RageFW_ICustomBrowserEvent,
> = keyof RageFW_ICustomBrowserEvent extends never
? false ? false
: Parameters<RageFW_ICustomCefEvent[EventName]>[0] extends undefined : Parameters<RageFW_ICustomBrowserEvent[EventName]>[0] extends undefined
? false ? false
: true : true

View File

@ -1,6 +1,8 @@
/// <reference types="@ragempcommunity/types-client" /> /// <reference types="@ragempcommunity/types-client" />
import type { RageFW_ICustomClientEvent } from 'rage-fw-shared-types' import type { RageFW_ICustomClientEvent } from '@entityseven/rage-fw-shared-types'
export type { RageFW_ICustomClientEvent } from '@entityseven/rage-fw-shared-types'
/** /**
* Union of all available client event names * Union of all available client event names
@ -21,23 +23,28 @@ export type RageFW_ClientArgs<K extends RageFW_ClientEvent> =
? Parameters<IClientEvents[K]> ? Parameters<IClientEvents[K]>
: never : never
/**
* Callback (function) for an event, name of which you pass as a generic
* These only include custom events
*/
export type RageFW_ClientCallback<K extends RageFW_ClientEvent> = (
args: RageFW_ClientArgs<K>,
) => Promise<RageFW_ClientReturn<K>>
/** /**
* Return type for an event, name of which you pass as a generic * Return type for an event, name of which you pass as a generic
* These only include custom events * These include custom and system events
*/ */
export type RageFW_ClientReturn<K extends RageFW_ClientEvent> = export type RageFW_ClientReturn<K extends RageFW_ClientEvent> =
K extends keyof RageFW_ICustomClientEvent K extends keyof RageFW_ICustomClientEvent
? ReturnType<RageFW_ICustomClientEvent[K]> ? ReturnType<RageFW_ICustomClientEvent[K]>
: K extends keyof IClientEvents
? ReturnType<IClientEvents[K]>
: void : void
/**
* Callback (function) for an event, name of which you pass as a generic
* These include custom and system events
*/
export type RageFW_ClientCallback<K extends RageFW_ClientEvent> = (
...args: RageFW_ClientArgs<K>
) => Promise<RageFW_ClientReturn<K>>
/**
*
*/
export type _ClientEventHasArgs< export type _ClientEventHasArgs<
EventName extends keyof RageFW_ICustomClientEvent, EventName extends keyof RageFW_ICustomClientEvent,
> = keyof RageFW_ICustomClientEvent extends never > = keyof RageFW_ICustomClientEvent extends never

View File

@ -1,3 +1,4 @@
export * from './client'
export * from './server'
export * from './browser' export * from './browser'
export * from './client'
export * from './middleware'
export * from './server'

View File

@ -0,0 +1,26 @@
import type * as T from './client'
export type RageFW_MiddlewareResponse =
| {
success: boolean
message?: string
}
| boolean
export type RageFW_MiddlewareResponseInternal = {
success: boolean
message?: string
id?: number
}
export type RageFW_MiddlewareFunction<EventName extends T.RageFW_ClientEvent> =
(
...args: T.RageFW_ClientArgs<EventName>
) => Promise<RageFW_MiddlewareResponse>
export type RageFW_MiddlewareOptions<EventName extends T.RageFW_ClientEvent> =
| RageFW_MiddlewareFunction<EventName>[]
| {
executables: RageFW_MiddlewareFunction<EventName>[]
onError: (error: string) => unknown
}

View File

@ -3,19 +3,19 @@
import type { import type {
RageFW_ICustomClientEvent, RageFW_ICustomClientEvent,
RageFW_ICustomServerEvent, RageFW_ICustomServerEvent,
} from 'rage-fw-shared-types' } from '@entityseven/rage-fw-shared-types'
/** /**
* Union of all available server event names callable from client * Union of all available server event names callable from client
* These only include custom events * These only include custom events
*/ */
export type RageFW_ClientServerEvent = keyof RageFW_ICustomServerEvent export type RageFW_ServerEvent = keyof RageFW_ICustomServerEvent
/** /**
* Array of arguments for an event, name of which you pass as a generic * Array of arguments for an event, name of which you pass as a generic
* These only include custom events * These only include custom events
*/ */
export type RageFW_ClientServerArgs<K extends RageFW_ClientServerEvent> = export type RageFW_ServerArgs<K extends RageFW_ServerEvent> =
K extends keyof RageFW_ICustomServerEvent K extends keyof RageFW_ICustomServerEvent
? Parameters<RageFW_ICustomServerEvent[K]> ? Parameters<RageFW_ICustomServerEvent[K]>
: never : never
@ -24,7 +24,7 @@ export type RageFW_ClientServerArgs<K extends RageFW_ClientServerEvent> =
* Return type for an event, name of which you pass as a generic * Return type for an event, name of which you pass as a generic
* These only include custom events * These only include custom events
*/ */
export type RageFW_ClientServerReturn<K extends RageFW_ClientServerEvent> = export type RageFW_ClientServerReturn<K extends RageFW_ServerEvent> =
K extends keyof RageFW_ICustomServerEvent K extends keyof RageFW_ICustomServerEvent
? ReturnType<RageFW_ICustomServerEvent[K]> ? ReturnType<RageFW_ICustomServerEvent[K]>
: never : never

View File

@ -1,5 +1,5 @@
{ {
"$schema": "node_modules/lerna/schemas/lerna-schema.json", "$schema": "node_modules/lerna/schemas/lerna-schema.json",
"version": "0.1.0", "version": "0.2.1-0.2.0-alpha.2.0",
"npmClient": "pnpm" "npmClient": "pnpm"
} }

View File

@ -1,13 +1,14 @@
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"publish": "pnpm build && lerna publish --force-publish", "publish": "lerna publish --force-publish",
"build": "lerna run build", "build": "lerna run build",
"lint": "eslint --c .eslintrc.yaml --ext .ts client/ server/ shared-types/", "lint": "eslint --c .eslintrc.yaml --ext .ts client/ server/ shared-types/",
"rebuild:cef": "cd cef && pnpm build",
"rebuild:browser": "cd browser && pnpm build",
"rebuild:client": "cd client && pnpm build", "rebuild:client": "cd client && pnpm build",
"rebuild:server": "cd server && pnpm build", "rebuild:server": "cd server && pnpm build",
"rebuild": "pnpm rebuild:cef && pnpm rebuild:client && pnpm rebuild:server" "rebuild": "pnpm rebuild:browser && pnpm rebuild:client && pnpm rebuild:server"
}, },
"dependencies": { "dependencies": {
"@microsoft/api-extractor": "^7.47.0", "@microsoft/api-extractor": "^7.47.0",
@ -16,6 +17,7 @@
"@ragempcommunity/types-server": "^2.1.8", "@ragempcommunity/types-server": "^2.1.8",
"@typescript-eslint/eslint-plugin": "^7.13.0", "@typescript-eslint/eslint-plugin": "^7.13.0",
"@typescript-eslint/parser": "^7.13.0", "@typescript-eslint/parser": "^7.13.0",
"@types/node": "^22.8.1",
"eslint": "^8.56.0", "eslint": "^8.56.0",
"lerna": "^8.1.3", "lerna": "^8.1.3",
"prettier": "^3.3.1", "prettier": "^3.3.1",

5699
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,5 @@
packages: packages:
- "server" - "server"
- "client" - "client"
- "cef" - "browser"
- "rpc"
- "cli"
- "shared-types" - "shared-types"

View File

@ -13,7 +13,7 @@ You can find out more about our CLI [here](https://git.entityseven.com/entitysev
At the moment automation we have only works via [pnpm](https://pnpm.io/). To scaffold a basic project with minor settings you can use our CLI: At the moment automation we have only works via [pnpm](https://pnpm.io/). To scaffold a basic project with minor settings you can use our CLI:
``pnpm create rage-fw@latest`` ``pnpm create @entityseven/rage-fw``
This will give you a few options, among them, you can find ``Initialize new project``. Use that option to scaffold a new project for yourself using the preferred frontend framework This will give you a few options, among them, you can find ``Initialize new project``. Use that option to scaffold a new project for yourself using the preferred frontend framework

View File

@ -1,7 +1,7 @@
{ {
"name": "rage-fw-rpc", "name": "@entityseven/rage-fw-rpc",
"description": "RageFW RPC", "description": "Rage FW RPC",
"version": "0.2.1", "version": "0.2.5",
"scripts": { "scripts": {
"build": "tsup", "build": "tsup",
"start": "npx ./dist create" "start": "npx ./dist create"
@ -17,7 +17,13 @@
"peerDependencies": { "peerDependencies": {
"typescript": "^5" "typescript": "^5"
}, },
"keywords": ["ragemp", "rage", "rpc", "rage-rpc", "ragerpc"], "keywords": [
"ragemp",
"rage",
"rpc",
"rage-rpc",
"ragerpc"
],
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/src/index.d.ts", "types": "dist/src/index.d.ts",
"author": { "author": {
@ -31,5 +37,6 @@
"url": "https://github.com/SashaGoncharov19" "url": "https://github.com/SashaGoncharov19"
} }
], ],
"license": "MIT" "license": "MIT",
"gitHead": "04eb7240735c4a0e4855ebabbe8d5b326819fa76"
} }

View File

@ -14,12 +14,17 @@ yarn add rage-fw-rpc
Import installed package and initialize rpc: Import installed package and initialize rpc:
```ts ```ts
// lib/rpc.js // lib/rpc.js
import { Rpc } from 'rage-fw-rpc' import { Rpc } from 'rage-fw-rpc'
export const rpc = new Rpc(/* options */) export const rpc = new Rpc(/* options */)
``` ```
# Motivation
The idea was to create an extensible package, with various features to simplify the development process and provide as much comfort as possible. It should also be using similar architecture as the framework it was specially built for
Inspired by usage of [rage-rpc](https://github.com/micaww/rage-rpc)
# Features # Features
- Type-safe events via [TS generics](https://www.typescriptlang.org/docs/handbook/2/generics.html), avoiding type wrappers - Type-safe events via [TS generics](https://www.typescriptlang.org/docs/handbook/2/generics.html), avoiding type wrappers
- Built-in logging options for each environment - Built-in logging options for each environment
@ -28,7 +33,7 @@ Import installed package and initialize rpc:
- Actual human-readable errors - Actual human-readable errors
# Docs # Docs
*Extended version with details coming soon* ## [Extended version available here](https://git.entityseven.com/entityseven/rage-framework/wiki/RPC%400.2.5)
## register ## register
Registers a callback function for a specified event Registers a callback function for a specified event

View File

@ -1,6 +1,6 @@
{ {
"name": "rage-fw-server", "name": "@entityseven/rage-fw-server",
"version": "0.1.0", "version": "0.2.0",
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/src/index.d.ts", "types": "dist/src/index.d.ts",
"files": [ "files": [
@ -11,20 +11,22 @@
"build": "tsup" "build": "tsup"
}, },
"dependencies": { "dependencies": {
"rage-fw-rpc": "workspace:^" "@entityseven/rage-fw-rpc": "latest"
}, },
"peerDependencies": { "peerDependencies": {
"@ragempcommunity/types-server": "^2.1.8", "@entityseven/rage-fw-shared-types": "workspace:^",
"rage-fw-shared-types": "workspace:^" "@ragempcommunity/types-server": "^2.1.8"
}, },
"description": "RageFW Server side", "description": "RageFW Server side",
"keywords": [], "keywords": [],
"author": "SashaGoncharov19", "author": "SashaGoncharov19",
"contributors": [{ "contributors": [
{
"name": "rilaxik", "name": "rilaxik",
"email": "dev.rilaxik@gmail.com", "email": "dev.rilaxik@gmail.com",
"url": "https://github.com/rilaxik" "url": "https://github.com/rilaxik"
}], }
],
"license": "MIT", "license": "MIT",
"gitHead": "053e4fd12aa120d53e11e0d2009c0df78c1a2ad0" "gitHead": "ffd542c1deddb3033e16e0dae7557313ae09b05f"
} }

View File

@ -1,3 +1,5 @@
export * from './player'
export * from './server'
export * from './logger' export * from './logger'
export * from './middleware'
export * from './player'
export * from './rpc'
export * from './server'

View File

@ -2,6 +2,7 @@ import winston, { format } from 'winston'
const { timestamp, printf, colorize } = format const { timestamp, printf, colorize } = format
/** Used to log in a server console */
export class Logger { export class Logger {
private format = printf(({ message, level, timestamp }) => { private format = printf(({ message, level, timestamp }) => {
return `[${new Date(timestamp).toLocaleTimeString()}] [${level}]: ${message}` return `[${new Date(timestamp).toLocaleTimeString()}] [${level}]: ${message}`
@ -23,14 +24,32 @@ export class Logger {
), ),
}) })
/**
* Informational logs. Colored in white
*
* @example
* fw.system.log.info('some information to be logged')
*/
public info(...message: unknown[]) { public info(...message: unknown[]) {
this.systemLogger.info(message.join(' ')) this.systemLogger.info(message.join(' '))
} }
/**
* Warning logs. Colored in yellow
*
* @example
* fw.system.log.warn('warning message')
*/
public warn(...message: unknown[]) { public warn(...message: unknown[]) {
this.systemLogger.warn(message.join(' ')) this.systemLogger.warn(message.join(' '))
} }
/**
* Error logs. Colored in red
*
* @example
* fw.system.log.info('some error information')
*/
public error(...message: unknown[]) { public error(...message: unknown[]) {
this.systemLogger.error(message.join(' ')) this.systemLogger.error(message.join(' '))
} }

View File

@ -0,0 +1,54 @@
import type * as T from '../types'
export class Middleware {
constructor() {}
private static async execute<EventName extends T.RageFW_ServerEvent>(
middlewares: T.RageFW_MiddlewareFunction<EventName>[],
args: T.RageFW_ServerArgs<EventName>,
): Promise<T.RageFW_MiddlewareResponseInternal> {
for (let i = 0; i < middlewares.length; i++) {
const result = await middlewares[i](...args)
if (typeof result === 'boolean' && !result)
return { success: result, id: i }
if (typeof result !== 'boolean' && !result.success)
return { ...result, id: i }
}
return {
success: true,
}
}
public static async process<EventName extends T.RageFW_ServerEvent>(
middlewareOptions: T.RageFW_MiddlewareOptions<EventName>,
callback: T.RageFW_ServerCallback<EventName>,
args: T.RageFW_ServerArgs<EventName>,
) {
if (Array.isArray(middlewareOptions)) {
const middlewaresResponse = await Middleware.execute(
middlewareOptions,
args,
)
if (middlewaresResponse.success) return await callback(...args)
} else {
const middlewaresResponse = await Middleware.execute(
middlewareOptions.executables,
args,
)
if (middlewaresResponse.success) {
return await callback(...args)
} else {
middlewareOptions.onError(
middlewaresResponse.message ??
'Middleware with id ' +
middlewaresResponse.id +
' failed',
)
}
}
}
}

View File

@ -1,40 +1,68 @@
import { Rpc } from 'rage-fw-rpc' import { rpc } from './rpc'
import type * as T from '../types'
import type {
_CefEventHasArgs,
_ClientEventHasArgs,
RageFW_CefArgs,
RageFW_CefEvent,
RageFW_CefReturn,
RageFW_ClientEvent,
RageFW_ServerClientArgs,
RageFW_ServerClientReturn,
} from '../types'
/** Handles event manipulations that require player to be present in context */
export class Player { export class Player {
private _rpc: Rpc = new Rpc() /**
* Triggers a client event from the server with arguments from shared types
get rpc(): Rpc { *
return this._rpc * Formerly known as ``callClient`` or ``emitClient``
} *
* @param {PlayerMp} player - Player object as an event target
public triggerClient<EventName extends RageFW_ClientEvent>( * @param eventName - The name of the client event to trigger
* @param [args] - Arguments for the client event, if present
* @returns {Promise} resolving to the client's response for the event
*
* @example
* // Triggering a client event without arguments
* fw.player.triggerClient("clientEventName")
*
* @example
* // Triggering a client event with arguments
* fw.player.triggerClient("clientEventName", ["message to client"])
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public async triggerClient<EventName extends T.RageFW_ClientEvent>(
player: PlayerMp, player: PlayerMp,
eventName: EventName, eventName: EventName,
...args: _ClientEventHasArgs<EventName> extends true ...args: T._ClientEventHasArgs<EventName> extends true
? [RageFW_ServerClientArgs<EventName>] ? [T.RageFW_ClientArgs<EventName>]
: [] : []
): Promise<RageFW_ServerClientReturn<EventName>> { ): Promise<T.RageFW_ClientReturn<EventName>> {
return this._rpc.callClient(player, eventName, args) return await rpc.callClient(player, eventName, args)
} }
public triggerBrowser<EventName extends RageFW_CefEvent>( /**
* Triggers a browser event from the server with arguments from shared types
*
* Formerly known as ``callBrowser`` or ``emitBrowser``
*
* @param {PlayerMp} player - Player object as an event target
* @param eventName - The name of the browser event to trigger
* @param [args] - Arguments for the browser event, if present
* @returns {Promise} resolving to the browser's response for the event
*
* @example
* // Triggering a browser event without arguments
* fw.player.triggerBrowser("browserEventName")
*
* @example
* // Triggering a browser event with arguments
* fw.player.triggerBrowser("browserEventName", ["message to browser"])
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public async triggerBrowser<EventName extends T.RageFW_BrowserEvent>(
player: PlayerMp, player: PlayerMp,
eventName: EventName, eventName: EventName,
...args: _CefEventHasArgs<EventName> extends true ...args: T._BrowserEventHasArgs<EventName> extends true
? [RageFW_CefArgs<EventName>] ? [T.RageFW_BrowserArgs<EventName>]
: [] : []
): Promise<RageFW_CefReturn<EventName>> { ): Promise<T.RageFW_BrowserReturn<EventName>> {
return this._rpc.callBrowser(player, eventName, args) return await rpc.callBrowser(player, eventName, args)
} }
} }
// new Player().triggerBrowser({} as PlayerMp, 'customCefEvent', ['', 1])
// new Player().triggerClient({} as PlayerMp, 'customClientEvent', ['', 1])

5
server/src/core/rpc.ts Normal file
View File

@ -0,0 +1,5 @@
import { Rpc } from '@entityseven/rage-fw-rpc'
export const rpc = new Rpc({
debugLogs: false,
})

View File

@ -1,117 +1,96 @@
import { Rpc } from 'rage-fw-rpc' import { rpc } from './rpc'
import { RageFW_ICustomServerEvent } from 'rage-fw-shared-types' import { Middleware } from './middleware'
import type * as T from '../types'
import { nativeEvents } from '../native.events'
import type {
_ServerEventHasArgs,
RageFW_ServerArgs,
RageFW_ServerCallback,
RageFW_ServerCallbackCustom,
RageFW_ServerCallbackNative,
RageFW_ServerEvent,
RageFW_ServerReturn,
} from '../types'
/** Server-side interactions */
export class Server { export class Server {
private _rpc: Rpc = new Rpc() /**
* Registers a server event with an associated callback
get rpc(): Rpc { *
return this._rpc * @param eventName - The name of the event to register
} * @param callback - The callback function to be executed when the event is triggered
* @param [options] - Optional settings for callback execution
private isNativeEvent(eventName: string): eventName is keyof IServerEvents { * @param [options.middlewares] - Middleware functions to be checked before the callback executes
return nativeEvents.includes(eventName) * @returns {Server} The current server instance, enabling method chaining
} *
* @example
private registerCustom<EventName extends keyof RageFW_ICustomServerEvent>( * // Registering an event
* fw.event.register("playerJoin", (player) => {
* fw.system.log.info(`${player.socialClub} has joined the game`)
* })
*
* @example
* // Registering an event with middlewares
* fw.event.register("playerJoin", (player) => {
* fw.system.log.info(`${player.name} has joined the game`)
* }, {
* middlewares: [ignoreBots] // <- your middlewares here
* })
*
* // or
*
* fw.event.register("playerJoin", (player) => {
* fw.system.log.info(`${player.socialClub} has joined the game`)
* }, {
* middlewares: {
* executables: [ignoreBots], // <- your middlewares here
* onError: (msg) => fw.system.log.info(`[BOT] ${player.socialClub} has joined the game`)
* }
* })
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public register<EventName extends T.RageFW_ServerEvent>(
eventName: EventName, eventName: EventName,
callback: RageFW_ServerCallbackCustom<EventName>, callback: T.RageFW_ServerCallback<EventName>,
): void { options?: {
this._rpc.register( middlewares?: T.RageFW_MiddlewareOptions<EventName>
eventName, },
): Server {
rpc.register<
Parameters<typeof callback>,
ReturnType<typeof callback> | Promise<unknown>,
EventName
>(eventName, async (...data) => {
if (!options?.middlewares) return await callback(...data)
await Middleware.process(options.middlewares, callback, data)
})
return this
}
/**
* Unregisters a server event, removing the associated callback
*
* @param eventName - The name of the event to unregister
* @returns {Server} The current server instance, enabling method chaining
*
* @example
* // Unregistering an event
* fw.event.unregister("playerJoin")
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
public unregister<EventName extends T.RageFW_ServerEvent>(
eventName: EventName,
): Server {
rpc.unregister<EventName>(eventName)
return this
}
// fixme // fixme
async (args: RageFW_ServerArgs<EventName>, info) => { // public trigger<EventName extends keyof T.RageFW_ICustomServerEvent>(
await callback([info.player as PlayerMp, ...args]) // eventName: EventName,
}, // ...args: T._ServerEventHasArgs<EventName> extends true
) // ? [T.RageFW_ServerArgs<EventName>]
} // : []
// ): Promise<T.RageFW_ServerReturn<EventName>> {
private registerNative<EventName extends keyof IServerEvents>( // return rpc.call(eventName, args)
eventName: EventName, // }
callback: RageFW_ServerCallbackNative<EventName>,
): void {
mp.events.add(
eventName,
(...args: Parameters<IServerEvents[EventName]>) =>
callback([...args]),
)
}
public register<EventName extends RageFW_ServerEvent>(
eventName: EventName,
callback: RageFW_ServerCallback<EventName>,
): void {
if (this.isNativeEvent(eventName)) {
this.registerNative(
eventName,
callback as RageFW_ServerCallbackNative,
)
} else {
this.registerCustom(
eventName,
callback as unknown as RageFW_ServerCallbackCustom,
)
}
}
public registerMany<EventName extends RageFW_ServerEvent>(events: {
[event in EventName]: RageFW_ServerCallback<event>
}): void {
Object.entries<RageFW_ServerCallback<EventName>>(events).map(
([eventName, callback]) => {
if (this.isNativeEvent(eventName)) {
this.registerNative(
eventName,
callback as RageFW_ServerCallbackNative,
)
} else {
this.registerCustom(
eventName as keyof RageFW_ICustomServerEvent,
callback as unknown as RageFW_ServerCallbackCustom,
)
}
},
)
}
private unregisterCustom<EventName extends keyof RageFW_ICustomServerEvent>(
eventName: EventName,
): void {
this._rpc.unregister(eventName)
}
private unregisterNative<EventName extends keyof IServerEvents>(
eventName: EventName,
): void {
mp.events.remove(eventName)
}
public unregister<EventName extends RageFW_ServerEvent>(
eventName: EventName,
): void {
if (this.isNativeEvent(eventName)) {
this.unregisterNative(eventName)
} else {
this.unregisterCustom(eventName)
}
}
public trigger<EventName extends keyof RageFW_ICustomServerEvent>(
eventName: EventName,
...args: _ServerEventHasArgs<EventName> extends true
? [RageFW_ServerArgs<EventName>]
: []
): Promise<RageFW_ServerReturn<EventName>> {
return this._rpc.call(eventName, args)
}
} }
// new Server()
// .register('customServerEvent', async (a, b, c) => true)
// .unregister('customServerEvent')

View File

@ -1,11 +1,24 @@
import { Logger, Player, Server } from './core' import { Logger, Player, Server, rpc } from './core'
export type { RageFW_MiddlewareFunction } from './types'
/**
* Package used on a server-side of your Rage:MP Server
*
* @see {@link https://git.entityseven.com/entityseven/rage-framework/wiki Wiki}
*/
export const fw = { export const fw = {
/** Server-side interactions */
event: new Server(), event: new Server(),
/** Handles event manipulations that require player to be present in context */
player: new Player(), player: new Player(),
/** Handles functions used to interact with the client environment */
system: { system: {
/** Used to log in a server console */
log: new Logger(), log: new Logger(),
}, },
/** ``rage-fw-rpc`` instance used under the hood. It is highly recommended to use this one if you need it instead of creating a new instance */
rpc,
} }
fw.system.log.info( fw.system.log.info(

View File

@ -1,18 +1,34 @@
import type { RageFW_ICustomCefEvent } from 'rage-fw-shared-types' import type { RageFW_ICustomBrowserEvent } from '@entityseven/rage-fw-shared-types'
export type RageFW_CefEvent = keyof RageFW_ICustomCefEvent /**
* Union of all available browser event names
* These only include custom events
*/
export type RageFW_BrowserEvent = keyof RageFW_ICustomBrowserEvent
export type RageFW_CefArgs<K extends RageFW_CefEvent> = Parameters< /**
RageFW_ICustomCefEvent[K] * Array of arguments of an event you pass as a generic
* These only include custom events
*/
export type RageFW_BrowserArgs<K extends RageFW_BrowserEvent> = Parameters<
RageFW_ICustomBrowserEvent[K]
> >
export type RageFW_CefReturn<K extends RageFW_CefEvent> = ReturnType< /**
RageFW_ICustomCefEvent[K] * Return type of event you pass as a generic
* These only include custom events
*/
export type RageFW_BrowserReturn<K extends RageFW_BrowserEvent> = ReturnType<
RageFW_ICustomBrowserEvent[K]
> >
export type _CefEventHasArgs<EventName extends keyof RageFW_ICustomCefEvent> = /**
keyof RageFW_ICustomCefEvent extends never *
*/
export type _BrowserEventHasArgs<
EventName extends keyof RageFW_ICustomBrowserEvent,
> = keyof RageFW_ICustomBrowserEvent extends never
? false ? false
: Parameters<RageFW_ICustomCefEvent[EventName]>[0] extends undefined : Parameters<RageFW_ICustomBrowserEvent[EventName]>[0] extends undefined
? false ? false
: true : true

View File

@ -1,6 +1,6 @@
/// <reference types="@ragempcommunity/types-server" /> /// <reference types="@ragempcommunity/types-server" />
import type { RageFW_ICustomClientEvent } from 'rage-fw-shared-types' import type { RageFW_ICustomClientEvent } from '@entityseven/rage-fw-shared-types'
/** /**
* Union of all available client event names * Union of all available client event names
@ -12,7 +12,7 @@ export type RageFW_ClientEvent = keyof RageFW_ICustomClientEvent
* Array of arguments of an event you pass as a generic * Array of arguments of an event you pass as a generic
* These only include custom events * These only include custom events
*/ */
export type RageFW_ServerClientArgs<K extends RageFW_ClientEvent> = export type RageFW_ClientArgs<K extends RageFW_ClientEvent> =
K extends RageFW_ClientEvent K extends RageFW_ClientEvent
? Parameters<RageFW_ICustomClientEvent[K]> ? Parameters<RageFW_ICustomClientEvent[K]>
: never : never
@ -21,11 +21,14 @@ export type RageFW_ServerClientArgs<K extends RageFW_ClientEvent> =
* Return type of event you pass as a generic * Return type of event you pass as a generic
* These only include custom events * These only include custom events
*/ */
export type RageFW_ServerClientReturn<K extends RageFW_ClientEvent> = export type RageFW_ClientReturn<K extends RageFW_ClientEvent> =
K extends RageFW_ClientEvent K extends RageFW_ClientEvent
? ReturnType<RageFW_ICustomClientEvent[K]> ? ReturnType<RageFW_ICustomClientEvent[K]>
: never : never
/**
*
*/
export type _ClientEventHasArgs< export type _ClientEventHasArgs<
EventName extends keyof RageFW_ICustomClientEvent, EventName extends keyof RageFW_ICustomClientEvent,
> = keyof RageFW_ICustomClientEvent extends never > = keyof RageFW_ICustomClientEvent extends never

View File

@ -1,3 +1,4 @@
export * from './client'
export * from './server'
export * from './browser' export * from './browser'
export * from './client'
export * from './middleware'
export * from './server'

View File

@ -0,0 +1,26 @@
import type * as T from './server'
export type RageFW_MiddlewareResponse =
| {
success: boolean
message?: string
}
| boolean
export type RageFW_MiddlewareResponseInternal = {
success: boolean
message?: string
id?: number
}
export type RageFW_MiddlewareFunction<EventName extends T.RageFW_ServerEvent> =
(
...args: T.RageFW_ServerArgs<EventName>
) => Promise<RageFW_MiddlewareResponse>
export type RageFW_MiddlewareOptions<EventName extends T.RageFW_ServerEvent> =
| RageFW_MiddlewareFunction<EventName>[]
| {
executables: RageFW_MiddlewareFunction<EventName>[]
onError: (error: string) => unknown
}

View File

@ -3,8 +3,9 @@
import type { import type {
RageFW_ICustomClientEvent, RageFW_ICustomClientEvent,
RageFW_ICustomServerEvent, RageFW_ICustomServerEvent,
} from 'rage-fw-shared-types' } from '@entityseven/rage-fw-shared-types'
export type { RageFW_ICustomServerEvent } from 'rage-fw-shared-types'
export type { RageFW_ICustomServerEvent } from '@entityseven/rage-fw-shared-types'
/** /**
* Union of all available server event names * Union of all available server event names
@ -20,20 +21,9 @@ export type RageFW_ServerEvent =
*/ */
export type RageFW_ServerArgs<K extends RageFW_ServerEvent> = export type RageFW_ServerArgs<K extends RageFW_ServerEvent> =
K extends keyof RageFW_ICustomServerEvent K extends keyof RageFW_ICustomServerEvent
? Parameters<RageFW_ICustomServerEvent[K]> ? [PlayerMp, ...Parameters<RageFW_ICustomServerEvent[K]>]
: K extends keyof IServerEvents : K extends keyof IServerEvents
? Parameters<IServerEvents[K]> ? [PlayerMp, Parameters<IServerEvents[K]>]
: never
/**
* Callback (function) for an event, name of which you pass as a generic
* These include system and custom events
*/
export type RageFW_ServerCallback<K extends RageFW_ServerEvent> =
K extends keyof RageFW_ICustomServerEvent
? RageFW_ServerCallbackCustom<K>
: K extends keyof IServerEvents
? RageFW_ServerCallbackNative<K>
: never : never
/** /**
@ -45,28 +35,19 @@ export type RageFW_ServerReturn<K extends RageFW_ServerEvent> =
? ReturnType<RageFW_ICustomServerEvent[K]> ? ReturnType<RageFW_ICustomServerEvent[K]>
: K extends keyof IServerEvents : K extends keyof IServerEvents
? ReturnType<IServerEvents[K]> ? ReturnType<IServerEvents[K]>
: never : void
/** /**
* Array of arguments for an event, name of which you pass as a generic * Callback (function) for an event, name of which you pass as a generic
* These only include custom events * These include system and custom events
*/ */
export type RageFW_ServerCallbackCustom< export type RageFW_ServerCallback<K extends RageFW_ServerEvent> = (
K extends keyof RageFW_ICustomServerEvent = keyof RageFW_ICustomServerEvent, ...args: RageFW_ServerArgs<K>
> = (
payload: [player: PlayerMp, ...args: RageFW_ServerArgs<K>],
) => Promise<RageFW_ServerReturn<K>> ) => Promise<RageFW_ServerReturn<K>>
/** /**
* Array of arguments for an event, name of which you pass as a generic *
* These only include system events
*/ */
export type RageFW_ServerCallbackNative<
K extends keyof IServerEvents = keyof IServerEvents,
> = (
payload: Parameters<IServerEvents[K]>,
) => Promise<ReturnType<IServerEvents[K]>>
export type _ServerEventHasArgs<EventName extends RageFW_ServerEvent> = export type _ServerEventHasArgs<EventName extends RageFW_ServerEvent> =
EventName extends keyof RageFW_ICustomServerEvent EventName extends keyof RageFW_ICustomServerEvent
? keyof RageFW_ICustomClientEvent extends never ? keyof RageFW_ICustomClientEvent extends never

View File

@ -1,6 +1,6 @@
{ {
"name": "rage-fw-shared-types", "name": "@entityseven/rage-fw-shared-types",
"version": "0.1.0", "version": "0.2.0",
"types": "types/types/index.d.ts", "types": "types/types/index.d.ts",
"files": [ "files": [
"types/**/*" "types/**/*"
@ -8,5 +8,5 @@
"author": "SashaGoncharov19", "author": "SashaGoncharov19",
"license": "MIT", "license": "MIT",
"type": "module", "type": "module",
"gitHead": "053e4fd12aa120d53e11e0d2009c0df78c1a2ad0" "gitHead": "ffd542c1deddb3033e16e0dae7557313ae09b05f"
} }

View File

@ -1,9 +1,14 @@
declare module 'rage-fw-shared-types' { declare module '@entityseven/rage-fw-shared-types' {
export interface RageFW_ICustomServerEvent {} export interface RageFW_ICustomServerEvent {
customServerEvent(arg1: string, arg2: number): boolean
}
export interface RageFW_ICustomClientEvent { export interface RageFW_ICustomClientEvent {
cefReady(): void cefReady(): void
customClientEvent(arg1: string, arg2: number): boolean
} }
export interface RageFW_ICustomCefEvent {} export interface RageFW_ICustomBrowserEvent {
customCefEvent(arg1: string, arg2: number): boolean
}
} }