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

@opens/accesshub-frontend

v0.2.2

Published

Frontend client for aggregated AccessHub company access with localStorage caching

Downloads

214

Readme

AccessHub Frontend SDK

Biblioteca para consultar, em uma única requisição, os recursos diretos e herdados dos grupos dos pacotes de uma empresa, com cache no navegador.

Recursos

  • ⚡️ Rápida e eficiente
  • 🔄 Cache automático com TTL configurável
  • 🛡️ Fallback para dados em cache quando a API falha
  • 🧩 API limpa e intuitiva
  • 📱 Suporta browsers modernos
  • 🔧 Totalmente tipada (TypeScript)

Instalação

npm install @opens/accesshub-frontend

Uso básico

import { AccessHubClient } from "@opens/accesshub-frontend";

const client = new AccessHubClient({
  accessHubURL: "https://api.example.com/api",
  token: "your-auth-token",
});

const response = await client.getCompanyAccess("company-123");
const hasRecording = await client.hasResource("company-123", "recording");

if (response._metadata.fromCache) {
  console.log("Dados obtidos do cache");
}

await client.clearCache("company-123");

resources é um mapa indexado pelo nome em lowercase. O nome original é preservado em cada item.

Cache e fallback

  • TTL padrão: 600 segundos.
  • Cache válido evita novas requisições por empresa.
  • Se a API falhar, o último cache conhecido é usado mesmo depois de expirado.
  • Sem API e sem cache, a SDK retorna mapas vazios com _metadata.fromFallback = true.
  • O token nunca é persistido no localStorage.

Integração com Vue

Exemplo Vue 2

// Em um componente Vue
export default {
  data() {
    return {
      resources: {},
      loading: true,
      error: null,
    };
  },

  async created() {
    const client = new AccessHubClient({
      accessHubURL: process.env.VUE_APP_API_URL,
      token: this.$store.getters.token,
    });

    try {
      const response = await client.getCompanyAccess("company-123");
      this.resources = response.resources;
    } catch (err) {
      this.error = err.message;
    } finally {
      this.loading = false;
    }
  },
};

Exemplo Vue 3 Composition API

import { ref, onMounted } from "vue";
import { AccessHubClient } from "@opens/accesshub-frontend";

export function useResources(companyId) {
  const resources = ref({});
  const loading = ref(true);
  const error = ref(null);

  const client = new AccessHubClient({
    accessHubURL: import.meta.env.VITE_API_URL,
    token: localStorage.getItem("token"),
  });

  async function fetchResources() {
    loading.value = true;

    try {
      const response = await client.getCompanyAccess(companyId);
      resources.value = response.resources;
    } catch (err) {
      error.value = err.message;
    } finally {
      loading.value = false;
    }
  }

  onMounted(fetchResources);

  return {
    resources,
    loading,
    error,
    refresh: fetchResources,
  };
}

Exemplo Nuxt 2

// Em uma página ou componente Nuxt
export default {
  data() {
    return {
      resources: {},
      loading: true,
    };
  },

  async fetch() {
    const client = new AccessHubClient({
      accessHubURL: process.env.apiUrl,
      token: this.$auth.getToken(),
    });

    const response = await client.getCompanyAccess("company-123");
    this.resources = response.resources;
    this.loading = false;
  },
};

Opções de Configuração

import { AccessHubClient } from "@opens/accesshub-frontend";
import type { ClientConfig } from "@opens/accesshub-frontend";

// Configuração completa (todos os valores são opcionais)
const config: ClientConfig = {
  accessHubURL: "https://api.example.com/api", // URL base da API
  cacheTTL: 300, // TTL do cache em segundos (padrão: 600)
  token: "your-auth-token", // Token de autenticação opcional
};

const client = new AccessHubClient(config);

Tratamento de Erros

O cliente lida com falhas de forma elegante:

try {
  const access = await client.getCompanyAccess("company-id");

  // Verificar se os dados vieram de fallback (API inacessível)
  if (access._metadata.fromFallback) {
    console.warn("API inacessível, usando dados em cache");
  }
} catch (error) {
  console.error("Falha ao obter recursos:", error.message);
}

Compatibilidade com Navegadores

  • Chrome, Firefox, Edge, Safari (últimas 2 versões)
  • IE11 não é suportado

Uso com Bundlers

// Usando bundlers como webpack, rollup ou esbuild
import { AccessHubClient } from "@opens/accesshub-frontend";

// Configuração é a mesma independente do ambiente
const client = new AccessHubClient({
  accessHubURL: "https://api.example.com/api",
  token: "your-token",
});

API Completa

AccessHubClient

| Método | Descrição | | ------------------------------ | -------------------------------------------------------------------- | | getCompanyAccess(companyId) | Obtém todos os recursos diretos e herdados dos grupos de uma empresa | | hasResource(companyId, name) | Verifica um recurso usando comparação case-insensitive | | clearCache(companyId?) | Limpa uma empresa ou todas as chaves do acesso agregado |

ResourceClient continua exportado apenas para compatibilidade e está depreciado.

Tipos

// Configuração do cliente
interface ClientConfig {
  accessHubURL: string; // URL base da API
  cacheTTL: number; // Tempo de vida do cache em segundos
  token?: string; // Token de autenticação opcional
}

// Recurso
interface Resource {
  id: string;
  name: string;
  description: string;
  // ... outras propriedades
}

// Resposta da API
interface ResourceResponse {
  resources: Record<string, Resource>;
  _metadata: {
    fromCache: boolean; // Indica se veio do cache
    fromFallback: boolean; // Indica se é fallback por falha na API
    lastUpdated: string; // Data da última atualização
    expiredAt?: number; // Indica se o cache está expirado
  };
}