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

@jysperu/browser-api

v1.0.2

Published

Librería moderna para realizar peticiones HTTP con manejo de errores y configuración flexible

Readme

@jysperu/browser-api

npm version npm downloads License: MIT TypeScript Bundle Size

Librería moderna para realizar peticiones HTTP con TypeScript, manejo de errores robusto y configuración flexible.

🚀 Características

  • 🔧 TypeScript completamente tipado con generics
  • API moderna basada en fetch con timeout configurable
  • 🛡️ Manejo de errores comprehensivo y normalizado
  • 🎯 Flexible - Soporta GET, POST, PUT, DELETE, PATCH
  • 📦 Sin dependencias externas
  • 🔄 Cache control personalizable
  • ⚙️ Configurable globalmente
  • 🌐 Detección automática del tag <base> HTML

📦 Instalación

npm install @jysperu/browser-api

⚡ Inicio Rápido

import { configure } from "@jysperu/browser-api";

// Configuración global (opcional)
configure({
  base: "https://api.ejemplo.com",
  timeout: 5000,
});

import { api, api_get, api_post } from "@jysperu/browser-api";

// GET request simple
const usuarios = await api_get<User[]>("/usuarios");
if (usuarios.success) {
  console.log("Usuarios:", usuarios.data);
}

// POST request
const nuevoUsuario = await api_post<User>("/usuarios", {
  nombre: "Juan Pérez",
  email: "[email protected]",
});

// Usando la función principal
const result = await api<User>("/usuarios", { nombre: "Juan" }, null, "GET");

📚 API Reference

🌐 detectBaseUrl

Detecta automáticamente la URL base desde el tag <base> del documento.

function detectBaseUrl(): string;

Comportamiento:

  • Si existe un tag <base href="..."> en el documento, usa esa URL
  • Si no existe, usa window.location.origin como fallback
  • En entornos sin DOM (SSR), retorna cadena vacía
  • Normaliza la URL removiendo barras finales

Ejemplo:

<!-- En tu HTML -->
<base href="https://api.miapp.com/v1/" />
import { detectBaseUrl } from "@jysperu/browser-api";

const baseUrl = detectBaseUrl();
console.log(baseUrl); // "https://api.miapp.com/v1"

🔧 configure

Configura los ajustes globales de la API.

interface RequestConfig {
  timeout?: number; // Timeout en milisegundos
  base?: string; // URL base para las peticiones
}

function configure(config: Partial<RequestConfig>): void;

🌐 api_get

Realiza peticiones GET con parámetros de consulta.

function api_get<T = unknown>(endpoint: string, params?: ApiParams, cachecode?: string | number | null): Promise<ApiResponse<T>>;

📤 api_post

Realiza peticiones POST con datos en el cuerpo.

function api_post<T = unknown>(endpoint: string, body?: ApiBody): Promise<ApiResponse<T>>;

🔄 api_request

Función genérica para cualquier método HTTP.

function api_request<T = unknown>(
  endpoint: string,
  method?: HttpMethod,
  data?: ApiParams | ApiBody,
  cacheCode?: string | number | null
): Promise<ApiResponse<T>>;

🎯 api (función principal)

Función principal con retrocompatibilidad.

function api<T = unknown>(
  endpoint: string,
  bodyOrParams?: ApiParams | ApiBody,
  cacheCode?: string | number | null,
  method?: HttpMethod
): Promise<ApiResponse<T>>;

🏗️ Funciones Auxiliares

buildUrl

Construye URLs con parámetros de consulta. Maneja diferentes tipos de endpoints:

function buildUrl(endpoint: string, params?: ApiParams, cachecode?: string | number | null): string;

Tipos de endpoints soportados:

// URL completa - se usa tal como está
buildUrl("https://otra-api.com/datos");

// Ruta absoluta - se concatena con la base configurada
buildUrl("/api/usuarios"); // → https://mibase.com/api/usuarios

// Ruta relativa - se agrega / automáticamente
buildUrl("usuarios"); // → https://mibase.com/usuarios

fetch2

Fetch con timeout configurable.

function fetch2(url: string, options: RequestInit, timeout?: number): Promise<Response>;

processFetchJsonResponse

Normaliza respuestas JSON.

function processFetchJsonResponse<T = unknown>(json: any): ApiResponse<T>;

📋 Tipos TypeScript

ApiResponse

interface ApiResponse<T = unknown> {
  success: boolean; // true si la operación fue exitosa
  log: string; // Mensaje de log/error
  data?: T; // Datos de respuesta (opcional)
  [key: string]: unknown;
}

ApiParams

interface ApiParams {
  [key: string]: string | number | boolean;
}

ApiBody

interface ApiBody {
  [key: string]: unknown;
}

HttpMethod

type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";

🌐 Detección Automática de Base URL

La librería detecta automáticamente la URL base de tu aplicación:

Tag Base HTML

<!DOCTYPE html>
<html>
  <head>
    <!-- La librería detecta automáticamente este tag -->
    <base href="https://api.miapp.com/v2/" />
  </head>
  <body>
    <!-- Tu aplicación -->
  </body>
</html>
import { detectBaseUrl, api_get } from "@jysperu/browser-api";

// Detecta automáticamente: "https://api.miapp.com/v2"
console.log(detectBaseUrl());

// Todas las peticiones usan esta base automáticamente
const datos = await api_get("/usuarios"); // → https://api.miapp.com/v2/usuarios

Sin Tag Base

Si no hay tag <base>, usa window.location.origin:

// En https://miapp.com/dashboard
console.log(detectBaseUrl()); // "https://miapp.com"

const datos = await api_get("/api/datos"); // → https://miapp.com/api/datos

Override Manual

import { configure } from "@jysperu/browser-api";

// Sobrescribir la detección automática
configure({
  base: "https://api-personalizada.com",
});

🌐 Compatibilidad

  • ✅ Todos los navegadores modernos (con soporte para fetch)
  • ✅ Compatible con frameworks (React, Vue, Angular, Svelte)
  • ✅ SSR friendly
  • ✅ TypeScript nativo
  • ✅ ES Modules y CommonJS

🔗 Enlaces y Recursos

📄 Licencia

MIT License - Consulta el archivo LICENSE para detalles completos.

MIT License - Copyright (c) 2025 JYS Perú

Desarrollado con ❤️ por JYS Perú