npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

os-fivem-fed-modules

v1.4.0

Published

A shared module for Front-End development using ReactJS & TypeScript

Readme

os-fivem-fed-modules

Biblioteca compartilhada para desenvolvimento com ReactJS em projetos FiveM . Ela fornece hooks e utilitários para:

  • Observar mensagens NUI (window.postMessage) com tipagem e segurança de handler
  • Enviar eventos para o backend (Lua/JS) com fallback para ambiente de navegador
  • Simular eventos NUI no navegador durante o desenvolvimento (Debugger)
  • Utilidades úteis como lazy load de componentes, detecção de ambiente, sleep e manipulação de áudio

Instalação

# npm
npm install os-fivem-fed-modules

# yarn
yarn add os-fivem-fed-modules

# bun
bun add os-fivem-fed-modyles

Importação

import { 
    useObserve, 
    Post, 
    Debugger, 
    useListen, 
    useImageValidation, 
    useSound, 
    isEnvBrowser, 
    lazyLoad, 
    sleep 
} from "os-fivem-fed-modules";

Visão geral da API

  • Hooks
    • useObserve<T>(action, handler) — Observa mensagens NUI (window "message") filtradas por action
    • useListen<T extends Event>(event, handler, target?) — Observa eventos DOM (ex.: keydown, resize)
    • useImageValidation(imageUrl) — Valida se uma imagem remota pode ser carregada
    • useSound(src, { volume, loop }) — Controle simples de áudio (play/pause)
  • Utilitários
    • Post.create<T>(eventName, data?, mockData?) — Faz POST para o backend FiveM, com mock opcional no navegador
    • Debugger — Simula eventos NUI no navegador (útil para desenvolvimento local)
    • isEnvBrowser() — Detecta se está rodando no navegador (fora do runtime do FiveM)
    • lazyLoad(loader) — Lazy load de componentes por nome, usando React.lazy
    • sleep(ms) — Promise que resolve após um atraso
  • Tipos
    • ObservedMessageType<T> = { action: string; data: T }
    • DebuggerEventType = { action: string; data: any }

Exemplos rápidos

1) Observando mensagens NUI com useObserve

import { useState } from "react";
import { useObserve } from "os-fivem-fed-modules";

type Data = { open: boolean; userId?: number };

export function App() {
	const [open, setOpen] = useState(false);
	const [userId, setUserId] = useState<number>(0);

	useObserve<Data>("setVisible", (response) => {
		setOpen(response.open);
		if (response.userId) setUserId(response.userId);
	});

    return (
        open && <div>{userId}</div>
    )
}

No backend (Lua), um envio típico para a NUI seria algo como:

SendNUIMessage({ 
    action = 'setVisible', 
    data = { 
        open = true, 
        title = 123 
    } 
})

2) Enviando eventos para o backend com Post

import { Post } from "os-fivem-fed-modules";

await Post.create("useItem", { id: "water" });

// Durante o desenvolvimento no navegador, você pode passar mockData

type ItemsData = { id: string; amount: number }[]

const result = await Post.create<{ ok: boolean }>(
	"getItems",
	{ filter: "drinks" },
	[
        { id: "water", amount: 10 },
        { id: "juice", amount: 2 }
    ]
);
// Em runtime FiveM: faz fetch para https://<resourceName>/inventory:getItems
// Em navegador: retorna imediatamente mockData (se fornecido)

Notas importantes:

  • O nome do resource é obtido via GetParentResourceName() quando disponível; caso contrário, assume nui-frame-app.
  • Em caso de erro na requisição, a função lança o erro (catch/try se necessário).

3) Simulando mensagens no navegador com Debugger

import { Debugger } from "os-fivem-fed-modules";

new Debugger(
	[
		{ 
            action: "setVisible", 
            data: { 
                open: true, 
                userId: 123     
            } 
        },
		{ 
            action: "addNotify", 
            data: { 
                type: "success", 
                message: "Bem-vindo!" 
            } 
        },
	],
	500
);

Em ambiente browser (isEnvBrowser() === true) os eventos serão despachados como mensagens window.postMessage.

4) Ouvindo eventos DOM com useListen

import { useListen } from "os-fivem-fed-modules";

export function EscToClose({ onClose }: { onClose: () => void }) {
	useListen<KeyboardEvent>("keydown", (event) => {
		if (event.key === "Escape") onClose();
	});

	return null;
}

5) Validando imagens com useImageValidation

import { useImageValidation } from "os-fivem-fed-modules";

export function Avatar({ url }: { url: string }) {
	const { isImageValid, imageUrl } = useImageValidation(url);
	
    return isImageValid ? (
		<img 
            src={imageUrl} 
            alt="avatar" 
        />
	) : (
		<div>Imagem inválida</div>
	);
}

6) Áudio simples com useSound

import { useSound } from "os-fivem-fed-modules";

export function ClickSound() {
	const { play, pause, isPlaying } = useSound("/sounds/click.ogg", {
		volume: 0.5,
		loop: false,
	});

	return (
		<div>
			<button onClick={play}>Play</button>
			<button onClick={pause} disabled={!isPlaying}>Pause</button>
		</div>
	);
}

7) Outros utilitários

import { isEnvBrowser, lazyLoad, sleep, noop } from "os-fivem-fed-modules";

// 1) Ambiente
if (isEnvBrowser()) {
	console.log("Desenvolvendo no navegador");
}

// 2) Lazy load por nome de export
const Components = lazyLoad(() => import("./components"));
// Uso: <Components.MyModal /> irá carregar dinamicamente o export nomeado "MyModal" do módulo

// 3) Sleep
await sleep(300);

Contribuindo

  • Faça um fork do repositório
  • Crie uma branch: feat/minha-feature
  • Rode o build localmente e valide os exemplos
  • Abra um Pull Request descrevendo a motivação e o escopo

Issues e discussões em: https://github.com/onesourceteam/os-fivem-fed-modules/issues

Licença

MIT © OneSource — Veja o arquivo LICENSE para mais detalhes.