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

@openubl/sdk

v1.1.0

Published

TypeScript SDK for openUBL - Peruvian SUNAT Electronic Documents

Downloads

1,073

Readme

@openubl/sdk

SDK de TypeScript para openUBL. Ofrece tipos, cliente fetch y schemas Zod generados automáticamente desde el esquema OpenAPI.

Instalación

npm install @openubl/sdk

Uso

1. Helper tipado (recomendado)

import { createInvoice, SDK_VERSION, checkApiVersion } from "@openubl/sdk";
import { zInvoiceCreateRequest } from "@openubl/sdk/zod.gen";

const request = zInvoiceCreateRequest.parse({
  documento: {
    serie: "F001",
    numero: 1,
    proveedor: { ruc: "20100066603", razonSocial: "Softgreen S.A.C." },
    cliente: { nombre: "Carlos", numeroDocumentoIdentidad: "12121212121", tipoDocumentoIdentidad: "6" },
    detalles: [{ descripcion: "Item", cantidad: 10, precio: 100 }],
  },
  firmar: false,
  validar_sunat: true,
});

const { data, error } = await createInvoice({ body: request });
if (error) throw new Error(JSON.stringify(error));

console.log(data.xml);              // XML UBL 2.1 generado
console.log(data.firmado);          // false
console.log(data.validado_sunat);   // true
console.log(data.valid);            // true | null
console.log(data.errors);           // [] | null

2. Firma digital desde TypeScript

import { createInvoice } from "@openubl/sdk";

const { data, error } = await createInvoice({
  body: {
    documento: { /* ... */ },
    firmar: true,
    validar_sunat: true,
    credenciales: {
      cert_pem: "-----BEGIN CERTIFICATE-----\n...",
      key_pem: "-----BEGIN PRIVATE KEY-----\n...",
    },
  },
});

if (data) {
  console.log(data.firmado); // true
  console.log(data.xml);     // contiene <ds:Signature>
}

3. Cliente genérico

import { client } from "@openubl/sdk";
import { zInvoiceCreateRequest } from "@openubl/sdk/zod.gen";

const request = zInvoiceCreateRequest.parse({
  documento: { /* ... */ },
  firmar: false,
  validar_sunat: true,
});

const { data, error } = await client.post("/api/v1/invoice/create", { body: request });
if (error) throw new Error(JSON.stringify(error));

console.log(data.xml);
console.log(data.firmado, data.validado_sunat, data.valid, data.errors);

4. fetch nativo

Si prefieres no usar el cliente, puedes llamar directamente a la API REST. Mira el ejemplo completo en la guía de TypeScript.

Helpers disponibles

| Helper | Endpoint | Body schema | |---|---|---| | createInvoice | POST /api/v1/invoice/create | zInvoiceCreateRequest | | createCreditNote | POST /api/v1/credit-note/create | zCreditNoteCreateRequest | | createDebitNote | POST /api/v1/debit-note/create | zDebitNoteCreateRequest | | createVoidedDocuments | POST /api/v1/voided-documents/create | zVoidedDocumentsCreateRequest | | createSummaryDocuments | POST /api/v1/summary-documents/create | zSummaryDocumentsCreateRequest | | createPerception | POST /api/v1/perception/create | zPerceptionCreateRequest | | createRetention | POST /api/v1/retention/create | zRetentionCreateRequest | | signXml | POST /api/v1/sign | zSignXmlBody | | getVersion | GET /api/v1/version | — |

Respuesta CreateResponse

Todos los endpoints /create devuelven:

{
  xml: string;
  firmado: boolean;
  validado_sunat: boolean;
  valid: boolean | null;
  errors: { code: string; message: string }[] | null;
}
  • valid y errors son null cuando validar_sunat=false.
  • Si validar_sunat=true y hay errores, la API responde HTTP 422 con detail=errors.

Validación runtime con Zod

Los schemas Zod viven en @openubl/sdk/zod.gen y se regeneran automáticamente desde openapi.json. Puedes usarlos para validar cualquier payload antes de enviarlo:

import {
  zInvoiceCreateRequest,
  zProveedor,
  zCliente,
  zDocumentoVentaDetalle,
} from "@openubl/sdk/zod.gen";

const proveedor = zProveedor.parse({ ruc: "20100066603", razonSocial: "Softgreen S.A.C." });
const cliente = zCliente.parse({ nombre: "Carlos", numeroDocumentoIdentidad: "12121212121", tipoDocumentoIdentidad: "6" });
const detalle = zDocumentoVentaDetalle.parse({ descripcion: "Item", cantidad: 10, precio: 100 });
const request = zInvoiceCreateRequest.parse({
  documento: { serie: "F001", numero: 1, proveedor, cliente, detalles: [detalle] },
  firmar: false,
  validar_sunat: true,
});

Los helpers también ejecutan validación automática en el body de la petición, así que pasar un objeto mal formado devolverá un error tipado.

Manejo de errores

Todas las llamadas devuelven { data, error }. Comprueba siempre error antes de usar data:

const { data, error } = await createInvoice({ body: request });

if (error) {
  // Puede ser un z.ZodError o el error devuelto por la API
  throw new Error(JSON.stringify(error));
}

console.log(data.xml);

Validación de versión

Verifica que tu SDK y la API compartan la misma versión:

import { checkApiVersion } from "@openubl/sdk";

const result = await checkApiVersion("http://localhost:8000");
if (!result.ok) {
  throw new Error(`Desfase de versión: SDK ${result.sdkVersion} vs API ${result.apiVersion}`);
}

Desarrollo

cd sdk/typescript
npm install
npm run generate   # regenera src/ desde openapi.json
npm run build      # compila TypeScript
npm test           # ejecuta la suite de tests

Alcance del SDK

El SDK es solo un cliente HTTP tipado. No empaqueta ZIP, no envía a SUNAT ni procesa CDR: esas responsabilidades quedan en el cliente operativo.