Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
## OpenCore Framework v1.1.2
## OpenCore Framework v1.2.0

### Updates
- Dependencies updated and override `js-yaml` to `5.4.1`
- Typescript updated to version 7.
### Added
- Added the `Register` type registry, exported from `@open-core/framework/register`, which the OpenCore CLI (v1.6.0+) augments with the generated `.opencore/opencore.gen.ts` of every resource.
- Typed `events.emit()`, `player.emit()`, `rpc.call()`, `rpc.notify()` and `WebView.send()` against the registered handlers: names autocomplete and payloads are checked against the handler signatures.
- Typed `rpc.call()` results from the handler's return type.
- Added strict mode, enabled through the CLI's `build.typegen.strict`, which rejects names no handler declares while still accepting the framework's own `opencore:*` events.
- Exported the registry helper types (`ClientEvents`, `ServerEvents`, `ServerRpc`, `ClientRpc`, `Commands`, `ViewSend`, `ViewReceive`, `NameOf`, `StrictNameOf`, `ArgsOf`, `RpcArgsOf`, `RpcResultOf`, `RpcCallResultOf`, `PayloadOf`, `DropFirst`, `IsRegistered`) from the package root.

### Changed
- Without generated types every signature keeps its previous loose form, so enabling or disabling typegen requires no source changes.
- `WebViewBridge`, `NuiBridge` and `createWebView()` now default their message maps to the registered `ViewSend` and `ViewReceive`, and accept any object type as a map.
- Removed the untyped `emit(event: string, target, ...args: unknown[])` overload of `EventsAPI`. It matched every call the typed signature rejected; without generated types the remaining signature is equally loose.
- For a registered RPC name, `rpc.call()` always resolves to the handler's result and ignores an explicit `TResult`. `TResult` still types calls to unregistered names.

### Fixed
- Prevented a contextual type from overriding a registered RPC result, which let `const x: Promise<string> = rpc.call('bank:getBalance')` compile against a handler returning `number`.
- Fixed the `WebView` and `NUI` singletons being published with a pinned loose type, which kept `send()` from ever being narrowed.
7 changes: 6 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@open-core/framework",
"version": "1.1.2",
"version": "1.2.0",
"description": "Secure, event-driven TypeScript Framework & Runtime engine for CitizenFX (Cfx).",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand All @@ -24,6 +24,11 @@
"import": "./dist/index.js",
"require": "./dist/index.js"
},
"./register": {
"types": "./dist/runtime/shared/types/register.d.ts",
"import": "./dist/runtime/shared/types/register.js",
"require": "./dist/runtime/shared/types/register.js"
},
"./server": {
"types": "./dist/runtime/server/index.d.ts",
"import": "./dist/runtime/server/index.js",
Expand Down
58 changes: 41 additions & 17 deletions src/adapters/contracts/transport/events.api.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,33 @@
import { EventContext, RuntimeContext } from './context'
import { Player } from '../../../runtime/server/entities/player'
import type {
ArgsOf,
ClientEvents,
NameOf,
ServerEvents,
} from '../../../runtime/shared/types/register'

type EmitArgs<C extends RuntimeContext> = C extends 'server'
? [target: Player | number | number[] | 'all', ...args: unknown[]]
: [...args: unknown[]]
/**
* The map of events this runtime may *emit*.
*
* @remarks
* A server emits to clients, so it is constrained by the client's `@Client.OnNet` handlers,
* and vice versa. Both resolve to a loose `Record<string, unknown[]>` when typegen is off.
*/
type EmitEventMap<C extends RuntimeContext> = C extends 'server' ? ClientEvents : ServerEvents

/*
* Note: only the *emitting* side is narrowed. `on()` keeps inferring its argument types from
* the handler, because those handlers are precisely what the generator reads to build the
* event map — constraining them against the generated map would be circular.
*/

/** Coerces a resolved payload type back into a rest-parameter-compatible tuple. */
type AsArgs<A> = A extends unknown[] ? A : unknown[]

type EmitArgs<C extends RuntimeContext, A = unknown[]> = C extends 'server'
? [target: Player | number | number[] | 'all', ...args: AsArgs<A>]
: [...args: AsArgs<A>]

/**
* broadcast and listen to events without relying on runtime. The adapter will be used.
Expand All @@ -24,21 +48,21 @@ export abstract class EventsAPI<C extends RuntimeContext> {

/**
* Emit an event.
* SERVER → CLIENT
* Server:
* - sends to client(s)
* - sends to client(s); the first argument after `event` is the target
* Client:
* - sends to server, targetOrArg will be ignored
*/
abstract emit(event: string, target: Player | number | number[] | 'all', ...args: unknown[]): void

/**
* Emit an event.
* CLIENT → SERVER
* Server:
* - sends to client(s)
* Client:
* - sends to server, targetOrArg will be ignored
* - sends to server, no target
*
* @remarks
* When typegen is active, `event` autocompletes to the names declared by the receiving side
* and `args` is checked against that handler's signature.
*
* There is deliberately no untyped overload: one accepting `(event: string, target, ...unknown[])`
* would match any call the typed signature rejects, silently disabling both strict mode and
* payload checking. With typegen off this signature is already as loose as that overload was.
*/
abstract emit(event: string, ...args: EmitArgs<C>): void
abstract emit<K extends NameOf<EmitEventMap<C>>>(
event: K,
...args: EmitArgs<C, ArgsOf<EmitEventMap<C>, K>>
): void
}
47 changes: 39 additions & 8 deletions src/adapters/contracts/transport/rpc.api.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { EventContext, RuntimeContext } from './context'
import type {
ClientRpc,
NameOf,
RpcArgsOf,
RpcCallResultOf,
ServerRpc,
} from '../../../runtime/shared/types/register'

export interface RpcContext extends EventContext {
/**
Expand All @@ -17,13 +24,28 @@ export interface RpcContext extends EventContext {
export type RpcTarget = number | number[] | 'all'
export type RpcCallTarget = number | number[]

type RpcCallArgs<C extends RuntimeContext> = C extends 'server'
? [target: RpcCallTarget, ...args: unknown[]]
: [...args: unknown[]]
/**
* The map of RPCs this runtime may *invoke*.
*
* @remarks
* A server calls handlers registered on clients (`@Client.OnRPC`) and vice versa. Both
* resolve to a loose map when typegen is off.
*
* Only the invoking side is narrowed: `on()` keeps inferring from its handler, because those
* handlers are what the generator reads to build this map.
*/
type InvokeRpcMap<C extends RuntimeContext> = C extends 'server' ? ClientRpc : ServerRpc

/** Coerces a resolved payload type back into a rest-parameter-compatible tuple. */
type AsArgs<A> = A extends unknown[] ? A : unknown[]

type RpcNotifyArgs<C extends RuntimeContext> = C extends 'server'
? [target: RpcTarget, ...args: unknown[]]
: [...args: unknown[]]
type RpcCallArgs<C extends RuntimeContext, A = unknown[]> = C extends 'server'
? [target: RpcCallTarget, ...args: AsArgs<A>]
: [...args: AsArgs<A>]

type RpcNotifyArgs<C extends RuntimeContext, A = unknown[]> = C extends 'server'
? [target: RpcTarget, ...args: AsArgs<A>]
: [...args: AsArgs<A>]

/**
* Remote Procedure Call API.
Expand Down Expand Up @@ -66,14 +88,23 @@ export abstract class RpcAPI<C extends RuntimeContext> {
*
* @remarks
* Use this when you need a return value.
*
* With typegen active, a generated name resolves to its handler's return type and `TResult`
* is ignored for it; `TResult` only types calls to names typegen does not know.
*/
abstract call<TResult = unknown>(name: string, ...args: RpcCallArgs<C>): Promise<TResult>
abstract call<TResult = never, K extends NameOf<InvokeRpcMap<C>> = NameOf<InvokeRpcMap<C>>>(
name: K,
...args: RpcCallArgs<C, RpcArgsOf<InvokeRpcMap<C>, K>>
): Promise<RpcCallResultOf<InvokeRpcMap<C>, K, TResult>>

/**
* Notify an RPC and wait for ACK. (acknowledgments)
*
* @remarks
* Use this when you only need delivery confirmation (no return value).
*/
abstract notify(name: string, ...args: RpcNotifyArgs<C>): Promise<void>
abstract notify<K extends NameOf<InvokeRpcMap<C>>>(
name: K,
...args: RpcNotifyArgs<C, RpcArgsOf<InvokeRpcMap<C>, K>>
): Promise<void>
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ import 'reflect-metadata'
export * from './kernel'
export * from './runtime/core'
export * from './contracts'
export * from './runtime/shared/types/register'
export * from './runtime/shared/types/system-types'
32 changes: 21 additions & 11 deletions src/runtime/client/webview-bridge.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { injectable } from 'tsyringe'
import { WebViewService } from './webview.service'
import type { WebViewFocusOptions } from '../../adapters/contracts/client/ui/webview/types'
import type { NameOf, PayloadOf, ViewReceive, ViewSend } from '../shared/types/register'
import { di } from './client-container'

@injectable()
export class WebViewBridge<
TSend extends Record<string, any> = Record<string, any>,
TReceive extends Record<string, any> = Record<string, any>,
> {
export class WebViewBridge<TSend extends object = ViewSend, TReceive extends object = ViewReceive> {
constructor(
private readonly serviceResolver: WebViewService | (() => WebViewService),
private readonly viewId = 'default',
Expand Down Expand Up @@ -43,7 +41,14 @@ export class WebViewBridge<
return this.service.getCapabilities()
}

send<K extends keyof TSend & string>(action: K, data: TSend[K]): void {
/**
* Sends a message to the WebView.
*
* @remarks
* With typegen active, `action` autocompletes to the messages the UI listens for and `data`
* is checked against the payload declared there.
*/
send<K extends NameOf<TSend>>(action: K, data: PayloadOf<TSend, K>): void {
this.service.send(this.viewId, action, data)
}

Expand Down Expand Up @@ -107,20 +112,25 @@ export class WebViewBridge<
}

export class NuiBridge<
TSend extends Record<string, any> = Record<string, any>,
TReceive extends Record<string, any> = Record<string, any>,
TSend extends object = ViewSend,
TReceive extends object = ViewReceive,
> extends WebViewBridge<TSend, TReceive> {}

function resolveWebViewService(): WebViewService {
return di.resolve(WebViewService)
}

export const WebView = new WebViewBridge(resolveWebViewService)
export const NUI = WebView
/*
* Annotated rather than inferred: an inferred type is resolved while the framework itself is
* compiled, where no generated file exists, so the emitted `.d.ts` would pin the loose view map
* and typegen could never narrow the singleton. `WebViewBridge` keeps its defaults deferred.
*/
export const WebView: WebViewBridge = new WebViewBridge(resolveWebViewService)
export const NUI: WebViewBridge = WebView

export function createWebView<
TSend extends Record<string, any> = Record<string, any>,
TReceive extends Record<string, any> = Record<string, any>,
TSend extends object = ViewSend,
TReceive extends object = ViewReceive,
>(viewId: string): WebViewBridge<TSend, TReceive> {
return new WebViewBridge(resolveWebViewService, viewId)
}
20 changes: 18 additions & 2 deletions src/runtime/server/entities/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { loggers } from '../../../kernel/logger'
import { Vector3 } from '../../../kernel/utils/vector3'
import { BaseEntity } from '../../core/entity'
import { Spatial } from '../../core/spatial'
import type { ArgsOf, ClientEvents, NameOf } from '../../shared/types/register'
import { SYSTEM_EVENTS } from '../../shared/types/system-types'
import { LinkedID } from '../types/linked-id'
import { PlayerSession } from '../types/player-session.types'
Expand All @@ -24,6 +25,11 @@ import { NativeHandle } from '../../core'
* Adapter bundle for player operations.
* Passed to Player instances by PlayerDirectory.
*/
/** `EventsAPI<'server'>.emit` without its typegen constraints, for forwarding pre-checked args. */
interface UntypedServerEmitter {
emit(event: string, target: number, ...args: unknown[]): void
}

export interface PlayerAdapters {
playerInfo: IPlayerInfo
playerServer: IPlayerServer
Expand Down Expand Up @@ -163,11 +169,21 @@ export class Player extends BaseEntity implements Spatial, NativeHandle {
/**
* Sends a network event exclusively to this specific player (client-side).
*
* @remarks
* When typegen is active, `eventName` autocompletes to the events declared by
* `@Client.OnNet` handlers and `args` is checked against the matching handler signature.
*
* @param eventName - The name of the event to trigger on the client.
* @param args - Data to send to the client.
*/
emit(eventName: string, ...args: any[]): void {
this.adapters.events.emit(eventName, this.clientID, ...args)
emit<K extends NameOf<ClientEvents>>(
eventName: K,
...args: ArgsOf<ClientEvents, K> extends infer A ? (A extends unknown[] ? A : any[]) : any[]
): void {
// `args` was already checked against `K` by this signature; forward it through an untyped
// view, since TypeScript cannot relate this method's `K` to the one `EventsAPI.emit` infers.
const events: UntypedServerEmitter = this.adapters.events
events.emit(eventName, this.clientID, ...(args as unknown[]))
}

/**
Expand Down
Loading
Loading