facturapi
Version:
Librería oficial de Facturapi. Crea CFDIs timbrados y enviados al SAT, XML y PDF
1,282 lines (1,281 loc) • 47.3 kB
JavaScript
class le {
constructor(t) {
this.client = t;
}
/**
* Creates a new customer in your organization
* @param data Customer data
* @param params Query params
* @returns Customer object
*/
create(t, n = null) {
return this.client.post("/customers", { body: t, params: n });
}
/**
* Gets a paginated list of customers that belong to your organization
* @param params Search parameters
* @returns List of customers
*/
list(t) {
return t || (t = {}), this.client.get("/customers", { params: t });
}
/**
* Gets a single customer object
* @param id Customer Id
* @returns Customer object
*/
retrieve(t) {
return t ? this.client.get("/customers/" + t) : Promise.reject(new Error("id is required"));
}
/**
* Updates a customer
* @param id Customer Id
* @param data Customer data to update
* @param params Query params
* @returns Updated customer
*/
update(t, n, o = null) {
return this.client.put("/customers/" + t, { body: n, params: o });
}
/**
* Permanently removes a customer from your organization.
* @param id Customer Id
* @returns Deleted customer
*/
del(t) {
return this.client.delete("/customers/" + t);
}
/**
* Validate customer with SAT validation.
* @param id Customer Id
* @returns Validation result
*/
validateTaxInfo(t) {
return this.client.get("/customers/" + t + "/tax-info-validation");
}
/**
* Send the customer an email with a link to edit their information.
* @param id Customer Id
* @param options Email options
* @param options.email Email address to send the link to
*/
sendEditLinkByEmail(t, n) {
return this.client.post("/customers/" + t + "/email-edit-link", {
body: n
});
}
}
class ce {
constructor(t) {
this.client = t;
}
/**
* Creates a new product in your organization
* @param data - Product data
* @returns Product object
*/
create(t) {
return this.client.post("/products", { body: t });
}
/**
* Gets a paginated list of products that belong to your organization
* @param params - Search parameters
* @returns Search results object. The object contains a `data` property with the list of products.
*/
list(t) {
return this.client.get("/products", { params: t });
}
/**
* Gets a single product object
* @param id - Product Id
* @returns Product object
*/
retrieve(t) {
return t ? this.client.get("/products/" + t) : Promise.reject(new Error("id is required"));
}
/**
* Updates a product
* @param id - Product Id
* @param data - Product data to update
* @returns Updated product
*/
update(t, n) {
return this.client.put("/products/" + t, { body: n });
}
/**
* Permanently removes a product from your organization.
* @param id - Product Id
* @returns Deleted product
*/
del(t) {
return this.client.delete("/products/" + t);
}
}
class ue {
constructor(t) {
this.client = t;
}
/**
* Creates a new valid invoice (CFDI).
* @param body Invoice data
* @param params Query params
* @returns Invoice object
*/
create(t, n) {
return this.client.post("/invoices", { body: t, params: n });
}
/**
* Gets a paginated list of invoices created by your organization
* @param params - Search parameters
* @returns Search results object. The object contains a `data` property with the list of invoices.
*/
list(t) {
return t || (t = {}), this.client.get("/invoices", { params: t });
}
/**
* Gets a single invoice object
* @param id Invoice Id
* @returns Invoice object
*/
retrieve(t) {
return t ? this.client.get("/invoices/" + t) : Promise.reject(new Error("id is required"));
}
/**
* Cancels an invoice. The invoice will not be valid anymore and will change its status to canceled.
* @param id Invoice Id
* @param params Cancel options
* @returns Canceled invoice
*/
cancel(t, n) {
return this.client.delete("/invoices/" + t, { params: n });
}
/**
* Sends the invoice to the customer's email
* @param id Invoice Id
* @param options Additional arguments
* @param options.email Email address to send the invoice to
* @returns Object with 'ok' property set to true if the email was sent successfully
*/
sendByEmail(t, n) {
return this.client.post("/invoices/" + t + "/email", { body: n });
}
/**
* Downloads the specified invoice in PDF format
* @param id Invoice Id
* @returns PDF file in a stream (Node.js) or Blob (browser)
*/
async downloadPdf(t) {
return this.client.get("/invoices/" + t + "/pdf");
}
/**
* Downloads the specified invoice in XML format
* @param id Invoice Id
* @returns XML file in a stream (Node.js) or Blob (browser)
*/
async downloadXml(t) {
return this.client.get("/invoices/" + t + "/xml");
}
/**
* Downloads the specified invoice in a ZIP package containing both PDF and XML files
* @param id Invoice Id
* @returns ZIP file in a stream (Node.js) or Blob (browser)
*/
downloadZip(t) {
return this.client.get("/invoices/" + t + "/zip");
}
/**
* Downloads the cancellation receipt of a canceled invoice in XML format
* @param id Invoice Id
* @returns XML file in a stream (Node.js) or Blob (browser)
*/
downloadCancellationReceiptXml(t) {
return this.client.get("/invoices/" + t + "/cancellation_receipt/xml");
}
/**
* Downloads the cancellation receipt of a canceled invoice in PDF format
* @param id Invoice Id
* @returns PDF file in a stream (Node.js) or Blob (browser)
*/
downloadCancellationReceiptPdf(t) {
return this.client.get("/invoices/" + t + "/cancellation_receipt/pdf");
}
/**
* Edits an invoice with "draft" status.
* @param id Invoice Id
* @param data Invoice data to edit
* @returns Edited invoice
*/
updateDraft(t, n) {
return this.client.put("/invoices/" + t, { body: n });
}
/**
* Stamps an invoice with "draft" status.
* @param id Invoice Id
* @param params Query params
* @returns Stamped invoice
*/
stampDraft(t, n) {
return this.client.post("/invoices/" + t + "/stamp", { params: n });
}
/**
* Updates the latest status of the invoice from the SAT
* @param id Invoice Id
* @returns Updated invoice
*/
updateStatus(t) {
return this.client.put("/invoices/" + t + "/status");
}
/**
* Creates a draft invoice from any other invoice
* @param id Invoice Id
* @returns Draft invoice
*/
copyToDraft(t) {
return this.client.post("/invoices/" + t + "/copy");
}
}
var fe = /* @__PURE__ */ function() {
return typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : window;
}(), { FormData: j, Blob: je, File: de } = fe;
const he = "https://www.facturapi.io/v2", Ee = "https://www.facturapi.io/v1", H = "v2", T = typeof process < "u" && !!process?.versions?.node, z = typeof navigator < "u" && navigator?.product === "ReactNative";
function pe(e) {
return new Promise((t, n) => {
const o = [];
e.on("data", (d) => o.push(d)), e.on("end", () => t(Buffer.concat(o))), e.on("error", n);
});
}
const L = async (e, t, n) => {
if (T) {
const o = e instanceof Buffer ? e : await pe(e);
return new de([o], t, {
type: n
});
}
return e;
};
class _e {
constructor(t) {
this.client = t;
}
/**
* Creates a new organization for your account
* @param data - Organization data
* @returns Organization object
*/
create(t) {
return this.client.post("/organizations", { body: t });
}
/**
* Gets a paginated list of organizations that belong to your account
* @param params - Search parameters
* @returns Search results object. The object contains a `data` property with the list of organizations.
*/
list(t) {
return t || (t = {}), this.client.get("/organizations", { params: t });
}
/**
* Gets a single organization object
* @param id
* @returns
*/
retrieve(t) {
return t ? this.client.get("/organizations/" + t) : Promise.reject(new Error("id is required"));
}
/**
* Updates the organization's legal information
* @param id Organization Id
* @param data
* @returns
*/
updateLegal(t, n) {
return t ? this.client.put("/organizations/" + t + "/legal", { body: n }) : Promise.reject(new Error("id is required"));
}
/**
* Updates the organization's customization information
* @param id Organization Id
* @param data Customization settings
* @returns Organization object
*/
updateCustomization(t, n) {
return this.client.put("/organizations/" + t + "/customization", {
body: n
});
}
/**
* Updates the organization's customization information
* @param id Organization Id
* @param data Receipt settings
* @returns Organization object
*/
updateReceiptSettings(t, n) {
return this.client.put("/organizations/" + t + "/receipts", {
body: n
});
}
/**
* Updates the organization's customization information
* @param id Organization Id
* @param data Domain data
* @returns Organization object
*/
updateDomain(t, n) {
return this.client.put("/organizations/" + t + "/domain", { body: n });
}
/**
* Checks if a domain is available for self invoices
* @param data Domain data
* @returns Domain availability
*/
checkDomainIsAvailable(t) {
return this.client.put("/organizations/domain-check", { body: t });
}
/**
* Uploads the organization's logo
* @param id Organization Id
* @param file Logo file
* @returns Organization object
*/
async uploadLogo(t, n) {
const o = await L(
n,
"file",
"application/octet-stream"
), d = new j();
return d.append("file", o, "file"), this.client.put("/organizations/" + t + "/logo", { formData: d });
}
/**
* Uploads the organization's certificate (CSD)
* @param id Organization Id
* @param cerFile Certificate file
* @param keyFile Key file
* @param password Certificate password
* @returns Organization object
*/
async uploadCertificate(t, n, o, d) {
let l = new j();
const [c, f] = await Promise.all([
L(n, "cer.cer", "application/octet-stream"),
L(o, "key.key", "application/octet-stream")
]);
return l.append("cer", c, "cer.cer"), l.append("key", f, "key.key"), l.append("password", d), this.client.put("/organizations/" + t + "/certificate", {
formData: l
});
}
/**
* Deletes the organization's certificate (CSD)
* @param id Organization Id
* @returns Organization object
*/
deleteCertificate(t) {
return this.client.delete("/organizations/" + t + "/certificate");
}
/**
* Permanently removes a organization from your account.
* @param id Organization Id
* @returns Deleted organization object
*/
del(t) {
return t ? this.client.delete("/organizations/" + t) : Promise.reject(new Error("id is required"));
}
/**
* Gets the test api key for an organization
* @param id Organization Id
* @returns Test api key
*/
getTestApiKey(t) {
return this.client.get("/organizations/" + t + "/apikeys/test");
}
/**
* Renews the test api key and makes the previous one unusable
* @param id Organization Id
* @returns New test api key
*/
renewTestApiKey(t) {
return this.client.put("/organizations/" + t + "/apikeys/test");
}
/**
* List live api keys
* @param id Organization Id
* @returns List of live api keys
*/
async listLiveApiKeys(t) {
return this.client.get("/organizations/" + t + "/apikeys/live");
}
/**
* Renews the live api key and makes the previous one unusable
* @param id Organization Id
* @returns New live api key
*/
renewLiveApiKey(t) {
return this.client.put("/organizations/" + t + "/apikeys/live");
}
/**
* Delete a live api key
* @param organizationId Organization Id
* @param apiKeyId Api Key Id
* @returns List of live api keys
*/
async deleteLiveApiKey(t, n) {
return this.client.delete(
"/organizations/" + t + "/apikeys/live/" + n
);
}
/**
* Get list of Series Organization
* @param organization_id Organization Id
* @returns Series object
*/
listSeriesGroup(t) {
return this.client.get(
"/organizations/" + t + "/series-group"
);
}
/**
* Creates a Series Organization
* @param organization_id Organization Id
* @param seriesData - Series data
* @returns Series object
*/
createSeriesGroup(t, n) {
return this.client.post(
"/organizations/" + t + "/series-group",
{
body: n
}
);
}
/**
* Update a Series Organization
* @param organization_id Organization Id
* @param seriesName Series seriesName
* @param data - Series data
* @returns Series object
*/
updateSeriesGroup(t, n, o) {
return this.client.put(
`/organizations/${t}/series-group/${n}`,
{
body: o
}
);
}
/**
* Update a Series Organization
* @param organization_id Organization Id
* @param seriesName Series seriesName
* @returns Series object
*/
deleteSeriesGroup(t, n) {
return this.client.delete(
`/organizations/${t}/series-group/${n}`
);
}
/**
* Get the organization that belongs to the authenticated API key
* @returns Organization object
*/
me() {
return this.client.get("/organizations/me");
}
/**
* Updates the organization's self-invoice settings
* @param id Organization Id
* @param data Self-invoice settings
* @returns Organization object
*/
updateSelfInvoiceSettings(t, n) {
return this.client.put("/organizations/" + t + "/self-invoice", {
body: n
});
}
}
class Oe {
constructor(t) {
this.client = t;
}
/**
* Creates a new product in your organization
* @param {Object} params - Search parameters
* @returns {Promise}
*/
searchProducts(t) {
return this.client.get("/catalogs/products", { params: t });
}
/**
* Gets a paginated list of products that belong to your organization
* @param {[Object]} params - Search parameters
* @returns {Promise}
*/
searchUnits(t) {
return this.client.get("/catalogs/units", { params: t });
}
}
class Ae {
constructor(t) {
this.client = t;
}
/**
* Creates a new receipt
* @param data Receipt data
* @returns Receipt object
*/
create(t) {
return this.client.post("/receipts", { body: t });
}
/**
* Gets a paginated list of receipts that belong to your organization
* @param params Search parameters
* @returns Search results object. The object contains a `data` property with the list of receipts.
*/
list(t) {
return t || (t = {}), this.client.get("/receipts", { params: t });
}
/**
* Gets a single receipt object
* @param id Receipt Id
* @returns Receipt object
*/
retrieve(t) {
return t ? this.client.get("/receipts/" + t) : Promise.reject(new Error("id is required"));
}
/**
* Creates an invoice for this receipt
* @param id Receipt Id
* @param data Invoice data
* @returns Invoice object
*/
invoice(t, n) {
return this.client.post("/receipts/" + t + "/invoice", { body: n });
}
/**
* Creates a global invoice for open receipts
* @param data
* @returns
*/
createGlobalInvoice(t) {
return this.client.post("/receipts/global-invoice", { body: t });
}
/**
* Marks a receipt as canceled. The receipt won't be available for invoicing anymore.
* @param id
* @returns
*/
cancel(t) {
return this.client.delete("/receipts/" + t);
}
/**
* Sends the receipt to the customer's email
* @param id Receipt Id
* @param data Additional arguments
* @param data.email Email address to send the receipt to
* @returns Email sent confirmation
*/
sendByEmail(t, n) {
return this.client.post("/receipts/" + t + "/email", { body: n });
}
/**
* Downloads the specified receipt in PDF format
* @param id Receipt Id
* @returns PDF file in a stream (Node.js) or Blob (browser)
*/
downloadPdf(t) {
return this.client.get("/receipts/" + t + "/pdf");
}
}
class ye {
constructor(t) {
this.client = t;
}
/**
* Creates a new valid retention (CFDI).
* @param data
* @returns
*/
create(t) {
return this.client.post("/retentions", { body: t });
}
/**
* Gets a paginated list of retentions created by the organization
* @param params - Search parameters
* @returns
*/
list(t) {
return t || (t = {}), this.client.get("/retentions", { params: t });
}
/**
* Gets a single retention object
* @param id
* @returns
*/
retrieve(t) {
return t ? this.client.get("/retentions/" + t) : Promise.reject(new Error("id is required"));
}
/**
* Cancels a retention.
* @param id
* @returns
*/
cancel(t) {
return this.client.delete("/retentions/" + t);
}
/**
* Sends a retention to the customer's email
* @param id Retention Id
* @param data Additional arguments
* @param data.email Email address to send the retention to
* @returns
*/
sendByEmail(t, n) {
return this.client.post("/retentions/" + t + "/email", { body: n });
}
/**
* Downloads the specified retention in PDF format
* @param id Retention Id
* @returns PDF file in a stream
*/
downloadPdf(t) {
return this.client.get("/retentions/" + t + "/pdf");
}
/**
* Downloads the specified retention in XML format
* @param id Retention Id
* @returns XML file in a stream
*/
downloadXml(t) {
return this.client.get("/retentions/" + t + "/xml");
}
/**
* Downloads the specified retention in a ZIP package containing both PDF and XML files
* @param id Retention Id
* @returns ZIP file in a stream
*/
downloadZip(t) {
return this.client.get("/retentions/" + t + "/zip");
}
}
class Ie {
constructor(t) {
this.client = t;
}
/**
* Creates a new webhook in your organization
* @param data - Webhook options
* @returns Webhook object
*/
create(t) {
return this.client.post("/webhooks", { body: t });
}
/**
* Gets a paginated list of webhooks that belong to your organization
* @param params - Search parameters
* @returns Search results object. The object contains a `data` property with the list of webhooks.
*/
list(t) {
return t || (t = {}), this.client.get("/webhooks", { params: t });
}
/**
* Gets a single webhook object
* @param id - Webhook Id
* @returns Webhook object
*/
retrieve(t) {
return t ? this.client.get("/webhooks/" + t) : Promise.reject(new Error("id is required"));
}
/**
* Updates a webhook
* @param id - Webhook Id
* @param data Updated webhook data
* @returns
*/
update(t, n) {
return this.client.put("/webhooks/" + t, { body: n });
}
/**
* Permanently removes a webhook from your organization.
* @param id - Webhook Id
* @returns Deleted webhook
*/
del(t) {
return this.client.delete("/webhooks/" + t);
}
/**
* Validate the response of webhook with the secret and facturapi-signature
* @param secret - Webhook Secret, received in the webhook creation
* @param signature - Facturapi Signature Header
* @param payload - Received event object to validate
* @returns When the signature is valid, it returns the event object
*/
async validateSignature(t) {
const { secret: n, signature: o, payload: d } = t;
let l;
if (typeof d == "string")
l = d;
else if (Buffer.isBuffer(d))
l = d.toString("utf8");
else if (typeof d == "object")
l = JSON.stringify(d);
else
throw new Error("Invalid payload type");
if (z)
return this.client.post("/webhooks/validate-signature", {
body: {
secret: n,
signature: o,
payload: l
}
});
if (T) {
const c = await import("crypto"), h = c.createHmac("sha256", n).update(l).digest(), A = Buffer.from(o, "hex");
if (h.length !== A.length)
throw new Error("Invalid signature");
if (!c.timingSafeEqual(h, A))
throw new Error("Invalid signature");
return JSON.parse(l);
} else {
const c = new TextEncoder(), f = c.encode(l), h = c.encode(n), A = await crypto.subtle.sign(
"HMAC",
await crypto.subtle.importKey(
"raw",
h,
{ name: "HMAC", hash: "SHA-256" },
!1,
["sign"]
),
f
), S = Array.from(new Uint8Array(A)).map((N) => N.toString(16).padStart(2, "0")).join("").toLowerCase();
if (o !== S)
throw new Error("Invalid signature");
}
return JSON.parse(l);
}
}
class be {
/**
* @param {Client} client
*/
constructor(t) {
this.client = t;
}
/**
* Validates a tax_id in EFOS list
* @param {Object} taxId - Search parameters
* @returns {Promise}
*/
validateTaxId(t) {
return this.client.get("/tools/tax_id_validation", {
params: {
tax_id: t
}
});
}
}
var q = /* @__PURE__ */ ((e) => (e.EFECTIVO = "01", e.CHEQUE_NOMINATIVO = "02", e.TRANSFERENCIA_ELECTRONICA_DE_FONDOS = "03", e.TARJETA_DE_CREDITO = "04", e.MONEDERO_ELECTRONICO = "05", e.DINERO_ELECTRONICO = "06", e.VALES_DE_DESPENSA = "08", e.DACION_EN_PAGO = "12", e.PAGO_POR_SUBROGACION = "13", e.PAGO_POR_CONSIGNACION = "14", e.CONDONACION = "15", e.COMPENSACION = "17", e.NOVACION = "23", e.CONFUSION = "24", e.REMISIÓN_DE_DEUDA = "25", e.PRESCRIPCION_O_CADUCIDAD = "26", e.A_SATISFACCION_DEL_ACREEDOR = "27", e.TARJETA_DE_DEBITO = "28", e.TARJETA_DE_SERVICIOS = "29", e.APLICACION_DE_ANTICIPOS = "30", e.INTERMEDIARIO_DE_PAGOS = "31", e.POR_DEFINIR = "99", e))(q || {});
const Fe = [
{ value: "01", label: "Efectivo" },
{ value: "02", label: "Cheque nominativo" },
{ value: "03", label: "Transferencia electrónica de fondos" },
{ value: "04", label: "Tarjeta de crédito" },
{ value: "05", label: "Monedero electrónico" },
{ value: "06", label: "Dinero electrónico" },
{ value: "08", label: "Vales de despensa" },
{ value: "12", label: "Dación en pago" },
{ value: "13", label: "Pago por subrogación" },
{ value: "14", label: "Pago por consignación" },
{ value: "15", label: "Condonación" },
{ value: "17", label: "Compensación" },
{ value: "23", label: "Novación" },
{ value: "24", label: "Confusión" },
{ value: "25", label: "Remisión de deuda" },
{ value: "26", label: "Prescripción o caducidad" },
{ value: "27", label: "A satisfacción del acreedor" },
{ value: "28", label: "Tarjeta de débito" },
{ value: "29", label: "Tarjeta de servicios" },
{ value: "30", label: "Aplicación de anticipos" },
{ value: "31", label: "Intermediario de pagos" },
{ value: "99", label: "Por definir" }
];
var x = /* @__PURE__ */ ((e) => (e.IVA = "IVA", e.IEPS = "IEPS", e.ISR = "ISR", e))(x || {}), J = /* @__PURE__ */ ((e) => (e.RATE = "Tasa", e.QUOTA = "Cuota", e))(J || {}), X = /* @__PURE__ */ ((e) => (e.SUM_BEFORE_TAXES = "sum_before_taxes", e.UNIT = "unit", e.BREAK_DOWN = "break_down", e.SUBTRACT_BEFORE_BREAKDOWN = "subtract_before_break_down", e))(X || {}), K = /* @__PURE__ */ ((e) => (e.PAGO_EN_UNA_EXHIBICION = "PUE", e.PAGO_EN_PARCIALIDADES_DIFERIDO = "PPD", e))(K || {}), Q = /* @__PURE__ */ ((e) => (e.ADQUISICION_MERCANCIAS = "G01", e.DEVOLUCIONES_DESCUENTOS_BONIFICACIONES = "G02", e.GASTOS_EN_GENERAL = "G03", e.CONSTRUCCIONES = "I01", e.MOBILIARIO_Y_EQUIPO_DE_OFICINA = "I02", e.EQUIPO_DE_TRANSPORTE = "I03", e.EQUIPO_DE_COMPUTO = "I04", e.DADOS_TROQUELES_HERRAMENTAL = "I05", e.COMUNICACIONES_TELEFONICAS = "I06", e.COMUNICACIONES_SATELITALES = "I07", e.OTRA_MAQUINARIA = "I08", e.HONORARIOS_MEDICOS = "D01", e.GASTOS_MEDICOS_POR_INCAPACIDAD = "D02", e.GASTOS_FUNERALES = "D03", e.DONATIVOS = "D04", e.INTERESES_POR_CREDITOS_HIPOTECARIOS = "D05", e.APORTACIONES_VOLUNTARIAS_SAR = "D06", e.PRIMA_SEGUROS_GASTOS_MEDICOS = "D07", e.GASTOS_TRANSPORTACION_ESCOLAR = "D08", e.CUENTAS_AHORRO_PENSIONES = "D09", e.SERVICIOS_EDUCATIVOS = "D10", e.SIN_EFECTOS_FISCALES = "S01", e.PAGOS = "CP01", e.NOMINA = "CN01", e.POR_DEFINIR = "P01", e))(Q || {}), Y = /* @__PURE__ */ ((e) => (e.INGRESO = "I", e.EGRESO = "E", e.TRASLADO = "T", e.NOMINA = "N", e.PAGO = "P", e))(Y || {}), $ = /* @__PURE__ */ ((e) => (e.NOTA_DE_CREDITO = "01", e.NOTA_DE_DEBITO = "02", e.DELOVUCION_DE_MERCANCIA = "03", e.SUSTITUCION_DE_CFDI_PREVIOS = "04", e.TRASLADOS_DE_MERCANCIA_FACTURADOS_PREVIAMENTE = "05", e.FACTURA_POR_TRASLADOS_PREVIOS = "06", e.APLICACION_DE_ANTICIPO = "07", e))($ || {}), W = /* @__PURE__ */ ((e) => (e.GENERAL_LEY_DE_PERSONAS_MORALES = "601", e.PERSONAS_MORALES_CON_FINES_NO_LUCRATIVOS = "603", e.SUELDOS_Y_SALARIOS = "605", e.ARRENDAMIENTO = "606", e.REGIMEN_DE_ENAJENACION_O_ADQUISICION_DE_BIENES = "607", e.DEMAS_INGRESOS = "608", e.RESIDENTES_EN_EL_EXTRANJERO_SIN_ESTABLECIMIENTO_PERMANENTE_EN_MÉXICO = "610", e.RESIDENTES_EN_EL_EXTRANJERO = "610", e.INGRESOS_POR_DIVIDENDOS_SOCIOS_Y_ACCIONISTAS = "611", e.PERSONAS_FISICAS_CON_ACTIVIDADES_EMPRESARIALES_Y_PROFESIONALES = "612", e.INGRESOS_POR_INTERESES = "614", e.REGIMEN_DE_LOS_INGRESOS_POR_OBTENCION_DE_PREMIOS = "615", e.SIN_OBLIGACIONES_FISCALES = "616", e.SOCIEDADES_COOPERATIVAS_DE_PRODUCCION = "620", e.REGIMEN_DE_INCORPORACION_FISCAL = "621", e.ACTIVIDADES_AGRICOLAS_GANADERAS_SILVICOLAS_Y_PESQUERAS = "622", e.OPCIONAL_PARA_GRUPOS_DE_SOCIEDADES = "623", e.COORDINADOS = "624", e.ACTIVIDADES_EMPRESARIALES_CON_INGRESOS_A_TRAVÉS_DE_PLATAFORMAS_TECNOLÓGICAS = "625", e.RÉGIMEN_SIMPLIFICADO_DE_CONFIANZA = "626", e))(W || {}), Z = /* @__PURE__ */ ((e) => (e.DRAFT = "draft", e.PENDING = "pending", e.VALID = "valid", e.CANCELED = "canceled", e.FAILED = "failed", e))(Z || {}), Se = /* @__PURE__ */ ((e) => (e.DAY = "day", e.WEEK = "week", e.FORTNIGHT = "fortnight", e.MONTH = "month", e.TWO_MONTHS = "two_months", e))(Se || {}), Ne = /* @__PURE__ */ ((e) => (e.OPEN = "open", e.CANCELED = "canceled", e.INVOICED_TO_CUSTOMER = "invoiced_to_customer", e.INVOICED_GLOBALLY = "invoiced_globally", e))(Ne || {}), Re = /* @__PURE__ */ ((e) => (e.ISSUING = "issuing", e.RECEIVING = "receiving", e))(Re || {}), ge = /* @__PURE__ */ ((e) => (e.NONE = "none", e.ACCEPTED = "accepted", e.PENDING = "pending", e.REJECTED = "rejected", e.EXPIRED = "expired", e))(ge || {}), De = /* @__PURE__ */ ((e) => (e.DAY = "day", e.WEEK = "week", e.FORTNIGHT = "fortnight", e.MONTH = "month", e.TWO_MONTHS = "two_months", e))(De || {}), Ce = /* @__PURE__ */ ((e) => (e.CUSTOM = "custom", e.PAGO = "pago", e.NOMINA = "nomina", e))(Ce || {}), we = /* @__PURE__ */ ((e) => (e.ERRORES_CON_RELACION = "01", e.ERRORES_SIN_RELACION = "02", e.NO_SE_CONCRETO = "03", e.FACTURA_GLOBAL = "04", e))(we || {}), D = typeof globalThis < "u" ? globalThis : typeof window < "u" ? window : typeof global < "u" ? global : typeof self < "u" ? self : {};
function Te(e) {
return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
}
var C = { exports: {} }, F;
function ve() {
return F || (F = 1, function(e, t) {
var n = typeof globalThis < "u" && globalThis || typeof self < "u" && self || typeof D < "u" && D, o = function() {
function l() {
this.fetch = !1, this.DOMException = n.DOMException;
}
return l.prototype = n, new l();
}();
(function(l) {
(function(c) {
var f = typeof l < "u" && l || typeof self < "u" && self || // eslint-disable-next-line no-undef
typeof D < "u" && D || {}, h = {
searchParams: "URLSearchParams" in f,
iterable: "Symbol" in f && "iterator" in Symbol,
blob: "FileReader" in f && "Blob" in f && function() {
try {
return new Blob(), !0;
} catch {
return !1;
}
}(),
formData: "FormData" in f,
arrayBuffer: "ArrayBuffer" in f
};
function A(r) {
return r && DataView.prototype.isPrototypeOf(r);
}
if (h.arrayBuffer)
var S = [
"[object Int8Array]",
"[object Uint8Array]",
"[object Uint8ClampedArray]",
"[object Int16Array]",
"[object Uint16Array]",
"[object Int32Array]",
"[object Uint32Array]",
"[object Float32Array]",
"[object Float64Array]"
], N = ArrayBuffer.isView || function(r) {
return r && S.indexOf(Object.prototype.toString.call(r)) > -1;
};
function y(r) {
if (typeof r != "string" && (r = String(r)), /[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(r) || r === "")
throw new TypeError('Invalid character in header field name: "' + r + '"');
return r.toLowerCase();
}
function R(r) {
return typeof r != "string" && (r = String(r)), r;
}
function v(r) {
var i = {
next: function() {
var s = r.shift();
return { done: s === void 0, value: s };
}
};
return h.iterable && (i[Symbol.iterator] = function() {
return i;
}), i;
}
function p(r) {
this.map = {}, r instanceof p ? r.forEach(function(i, s) {
this.append(s, i);
}, this) : Array.isArray(r) ? r.forEach(function(i) {
if (i.length != 2)
throw new TypeError("Headers constructor: expected name/value pair to be length 2, found" + i.length);
this.append(i[0], i[1]);
}, this) : r && Object.getOwnPropertyNames(r).forEach(function(i) {
this.append(i, r[i]);
}, this);
}
p.prototype.append = function(r, i) {
r = y(r), i = R(i);
var s = this.map[r];
this.map[r] = s ? s + ", " + i : i;
}, p.prototype.delete = function(r) {
delete this.map[y(r)];
}, p.prototype.get = function(r) {
return r = y(r), this.has(r) ? this.map[r] : null;
}, p.prototype.has = function(r) {
return this.map.hasOwnProperty(y(r));
}, p.prototype.set = function(r, i) {
this.map[y(r)] = R(i);
}, p.prototype.forEach = function(r, i) {
for (var s in this.map)
this.map.hasOwnProperty(s) && r.call(i, this.map[s], s, this);
}, p.prototype.keys = function() {
var r = [];
return this.forEach(function(i, s) {
r.push(s);
}), v(r);
}, p.prototype.values = function() {
var r = [];
return this.forEach(function(i) {
r.push(i);
}), v(r);
}, p.prototype.entries = function() {
var r = [];
return this.forEach(function(i, s) {
r.push([s, i]);
}), v(r);
}, h.iterable && (p.prototype[Symbol.iterator] = p.prototype.entries);
function P(r) {
if (!r._noBody) {
if (r.bodyUsed)
return Promise.reject(new TypeError("Already read"));
r.bodyUsed = !0;
}
}
function M(r) {
return new Promise(function(i, s) {
r.onload = function() {
i(r.result);
}, r.onerror = function() {
s(r.error);
};
});
}
function ee(r) {
var i = new FileReader(), s = M(i);
return i.readAsArrayBuffer(r), s;
}
function te(r) {
var i = new FileReader(), s = M(i), u = /charset=([A-Za-z0-9_-]+)/.exec(r.type), E = u ? u[1] : "utf-8";
return i.readAsText(r, E), s;
}
function re(r) {
for (var i = new Uint8Array(r), s = new Array(i.length), u = 0; u < i.length; u++)
s[u] = String.fromCharCode(i[u]);
return s.join("");
}
function U(r) {
if (r.slice)
return r.slice(0);
var i = new Uint8Array(r.byteLength);
return i.set(new Uint8Array(r)), i.buffer;
}
function G() {
return this.bodyUsed = !1, this._initBody = function(r) {
this.bodyUsed = this.bodyUsed, this._bodyInit = r, r ? typeof r == "string" ? this._bodyText = r : h.blob && Blob.prototype.isPrototypeOf(r) ? this._bodyBlob = r : h.formData && FormData.prototype.isPrototypeOf(r) ? this._bodyFormData = r : h.searchParams && URLSearchParams.prototype.isPrototypeOf(r) ? this._bodyText = r.toString() : h.arrayBuffer && h.blob && A(r) ? (this._bodyArrayBuffer = U(r.buffer), this._bodyInit = new Blob([this._bodyArrayBuffer])) : h.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(r) || N(r)) ? this._bodyArrayBuffer = U(r) : this._bodyText = r = Object.prototype.toString.call(r) : (this._noBody = !0, this._bodyText = ""), this.headers.get("content-type") || (typeof r == "string" ? this.headers.set("content-type", "text/plain;charset=UTF-8") : this._bodyBlob && this._bodyBlob.type ? this.headers.set("content-type", this._bodyBlob.type) : h.searchParams && URLSearchParams.prototype.isPrototypeOf(r) && this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8"));
}, h.blob && (this.blob = function() {
var r = P(this);
if (r)
return r;
if (this._bodyBlob)
return Promise.resolve(this._bodyBlob);
if (this._bodyArrayBuffer)
return Promise.resolve(new Blob([this._bodyArrayBuffer]));
if (this._bodyFormData)
throw new Error("could not read FormData body as blob");
return Promise.resolve(new Blob([this._bodyText]));
}), this.arrayBuffer = function() {
if (this._bodyArrayBuffer) {
var r = P(this);
return r || (ArrayBuffer.isView(this._bodyArrayBuffer) ? Promise.resolve(
this._bodyArrayBuffer.buffer.slice(
this._bodyArrayBuffer.byteOffset,
this._bodyArrayBuffer.byteOffset + this._bodyArrayBuffer.byteLength
)
) : Promise.resolve(this._bodyArrayBuffer));
} else {
if (h.blob)
return this.blob().then(ee);
throw new Error("could not read as ArrayBuffer");
}
}, this.text = function() {
var r = P(this);
if (r)
return r;
if (this._bodyBlob)
return te(this._bodyBlob);
if (this._bodyArrayBuffer)
return Promise.resolve(re(this._bodyArrayBuffer));
if (this._bodyFormData)
throw new Error("could not read FormData body as text");
return Promise.resolve(this._bodyText);
}, h.formData && (this.formData = function() {
return this.text().then(se);
}), this.json = function() {
return this.text().then(JSON.parse);
}, this;
}
var ie = ["CONNECT", "DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT", "TRACE"];
function ne(r) {
var i = r.toUpperCase();
return ie.indexOf(i) > -1 ? i : r;
}
function I(r, i) {
if (!(this instanceof I))
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
i = i || {};
var s = i.body;
if (r instanceof I) {
if (r.bodyUsed)
throw new TypeError("Already read");
this.url = r.url, this.credentials = r.credentials, i.headers || (this.headers = new p(r.headers)), this.method = r.method, this.mode = r.mode, this.signal = r.signal, !s && r._bodyInit != null && (s = r._bodyInit, r.bodyUsed = !0);
} else
this.url = String(r);
if (this.credentials = i.credentials || this.credentials || "same-origin", (i.headers || !this.headers) && (this.headers = new p(i.headers)), this.method = ne(i.method || this.method || "GET"), this.mode = i.mode || this.mode || null, this.signal = i.signal || this.signal || function() {
if ("AbortController" in f) {
var a = new AbortController();
return a.signal;
}
}(), this.referrer = null, (this.method === "GET" || this.method === "HEAD") && s)
throw new TypeError("Body not allowed for GET or HEAD requests");
if (this._initBody(s), (this.method === "GET" || this.method === "HEAD") && (i.cache === "no-store" || i.cache === "no-cache")) {
var u = /([?&])_=[^&]*/;
if (u.test(this.url))
this.url = this.url.replace(u, "$1_=" + (/* @__PURE__ */ new Date()).getTime());
else {
var E = /\?/;
this.url += (E.test(this.url) ? "&" : "?") + "_=" + (/* @__PURE__ */ new Date()).getTime();
}
}
}
I.prototype.clone = function() {
return new I(this, { body: this._bodyInit });
};
function se(r) {
var i = new FormData();
return r.trim().split("&").forEach(function(s) {
if (s) {
var u = s.split("="), E = u.shift().replace(/\+/g, " "), a = u.join("=").replace(/\+/g, " ");
i.append(decodeURIComponent(E), decodeURIComponent(a));
}
}), i;
}
function oe(r) {
var i = new p(), s = r.replace(/\r?\n[\t ]+/g, " ");
return s.split("\r").map(function(u) {
return u.indexOf(`
`) === 0 ? u.substr(1, u.length) : u;
}).forEach(function(u) {
var E = u.split(":"), a = E.shift().trim();
if (a) {
var g = E.join(":").trim();
try {
i.append(a, g);
} catch (B) {
console.warn("Response " + B.message);
}
}
}), i;
}
G.call(I.prototype);
function O(r, i) {
if (!(this instanceof O))
throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');
if (i || (i = {}), this.type = "default", this.status = i.status === void 0 ? 200 : i.status, this.status < 200 || this.status > 599)
throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");
this.ok = this.status >= 200 && this.status < 300, this.statusText = i.statusText === void 0 ? "" : "" + i.statusText, this.headers = new p(i.headers), this.url = i.url || "", this._initBody(r);
}
G.call(O.prototype), O.prototype.clone = function() {
return new O(this._bodyInit, {
status: this.status,
statusText: this.statusText,
headers: new p(this.headers),
url: this.url
});
}, O.error = function() {
var r = new O(null, { status: 200, statusText: "" });
return r.ok = !1, r.status = 0, r.type = "error", r;
};
var ae = [301, 302, 303, 307, 308];
O.redirect = function(r, i) {
if (ae.indexOf(i) === -1)
throw new RangeError("Invalid status code");
return new O(null, { status: i, headers: { location: r } });
}, c.DOMException = f.DOMException;
try {
new c.DOMException();
} catch {
c.DOMException = function(i, s) {
this.message = i, this.name = s;
var u = Error(i);
this.stack = u.stack;
}, c.DOMException.prototype = Object.create(Error.prototype), c.DOMException.prototype.constructor = c.DOMException;
}
function m(r, i) {
return new Promise(function(s, u) {
var E = new I(r, i);
if (E.signal && E.signal.aborted)
return u(new c.DOMException("Aborted", "AbortError"));
var a = new XMLHttpRequest();
function g() {
a.abort();
}
a.onload = function() {
var _ = {
statusText: a.statusText,
headers: oe(a.getAllResponseHeaders() || "")
};
E.url.indexOf("file://") === 0 && (a.status < 200 || a.status > 599) ? _.status = 200 : _.status = a.status, _.url = "responseURL" in a ? a.responseURL : _.headers.get("X-Request-URL");
var b = "response" in a ? a.response : a.responseText;
setTimeout(function() {
s(new O(b, _));
}, 0);
}, a.onerror = function() {
setTimeout(function() {
u(new TypeError("Network request failed"));
}, 0);
}, a.ontimeout = function() {
setTimeout(function() {
u(new TypeError("Network request timed out"));
}, 0);
}, a.onabort = function() {
setTimeout(function() {
u(new c.DOMException("Aborted", "AbortError"));
}, 0);
};
function B(_) {
try {
return _ === "" && f.location.href ? f.location.href : _;
} catch {
return _;
}
}
if (a.open(E.method, B(E.url), !0), E.credentials === "include" ? a.withCredentials = !0 : E.credentials === "omit" && (a.withCredentials = !1), "responseType" in a && (h.blob ? a.responseType = "blob" : h.arrayBuffer && (a.responseType = "arraybuffer")), i && typeof i.headers == "object" && !(i.headers instanceof p || f.Headers && i.headers instanceof f.Headers)) {
var V = [];
Object.getOwnPropertyNames(i.headers).forEach(function(_) {
V.push(y(_)), a.setRequestHeader(_, R(i.headers[_]));
}), E.headers.forEach(function(_, b) {
V.indexOf(b) === -1 && a.setRequestHeader(b, _);
});
} else
E.headers.forEach(function(_, b) {
a.setRequestHeader(b, _);
});
E.signal && (E.signal.addEventListener("abort", g), a.onreadystatechange = function() {
a.readyState === 4 && E.signal.removeEventListener("abort", g);
}), a.send(typeof E._bodyInit > "u" ? null : E._bodyInit);
});
}
return m.polyfill = !0, f.fetch || (f.fetch = m, f.Headers = p, f.Request = I, f.Response = O), c.Headers = p, c.Request = I, c.Response = O, c.fetch = m, c;
})({});
})(o), o.fetch.ponyfill = !0, delete o.fetch.polyfill;
var d = n.fetch ? n : o;
t = d.fetch, t.default = d.fetch, t.fetch = d.fetch, t.Headers = d.Headers, t.Request = d.Request, t.Response = d.Response, e.exports = t;
}(C, C.exports)), C.exports;
}
var Pe = ve();
const me = /* @__PURE__ */ Te(Pe);
let w;
T ? w = (e) => Buffer.from(e).toString("base64") : z ? w = (e) => globalThis.Buffer.from(e).toString("base64") : w = globalThis.btoa;
const Be = async (e) => {
if (!e.ok) {
const n = await e.json();
throw new Error(n.message || e.statusText);
}
const t = e.headers.get("content-type");
if (t) {
if (t.includes("image/") || t.includes("application/pdf") || t.includes("application/xml") || t.includes("application/zip"))
if (T) {
const n = e.body?.getReader();
if (!n)
return e.body;
try {
const { Readable: o } = await import("stream");
return new o({
read() {
n.read().then(({ done: d, value: l }) => {
d ? this.push(null) : this.push(Buffer.from(l));
});
}
});
} catch {
throw new Error(
'Node.js streams are not available in this environment. Please install the "stream" package.'
);
}
} else
return e.blob();
else if (t.includes("application/json"))
return e.json();
}
return e.text();
};
function Le(e) {
return w(e);
}
const Me = (e, t = H) => {
const n = t === "v1" ? Ee : he, o = {
Authorization: `Basic ${Le(e + ":")}`
};
return {
async request(l, c) {
const { params: f, body: h, formData: A, ...S } = c || {}, N = f ? "?" + new URLSearchParams(f).toString() : "", y = {
...S,
headers: {
...o,
...A ? {} : { "Content-Type": "application/json" }
},
body: A || (h ? JSON.stringify(h) : void 0)
}, R = await me(n + l + N, y);
return Be(R);
},
get(l, c) {
return this.request(l, { method: "GET", ...c });
},
post(l, c) {
return this.request(l, { method: "POST", ...c });
},
put(l, c) {
return this.request(l, { method: "PUT", ...c });
},
delete(l, c) {
return this.request(l, { method: "DELETE", ...c });
}
};
};
var Ue = /* @__PURE__ */ ((e) => (e.RECEIPT_SELF_INVOICE_COMPLETE = "receipt.self_invoice_complete", e.INVOICE_CANCELLATION_STATUS_UPDATED = "invoice.cancellation_status_updated", e.RECEIPT_STATUS_UPDATED = "receipt.status_updated", e.GLOBAL_INVOICE = "invoice.global_invoice_created", e.INVOICES_STATUS_UPDATED = "invoice.status_updated", e.INVOICES_CREATED_FROM_DASHBOARD = "invoice.created_from_dashboard", e.CUSTOMER_EDIT_LINK_COMPLETED = "customer.edit_link_completed", e))(Ue || {}), Ge = /* @__PURE__ */ ((e) => (e.RECEIPT = "receipt", e.INVOICE = "invoice", e.CUSTOMER = "customer", e))(Ge || {}), Ve = /* @__PURE__ */ ((e) => (e.ENABLED = "enabled", e.DISABLED = "disabled", e))(Ve || {});
const k = ["v1", "v2"];
class ke {
static get TaxType() {
return x;
}
static get TaxFactor() {
return J;
}
static get IepsMode() {
return X;
}
static get PaymentForm() {
return q;
}
static get PaymentMethod() {
return K;
}
static get InvoiceType() {
return Y;
}
static get InvoiceUse() {
return Q;
}
static get InvoiceRelation() {
return $;
}
static get TaxSystem() {
return W;
}
static get InvoiceStatus() {
return Z;
}
constructor(t, n = {}) {
if (n.apiVersion) {
if (!k.includes(n.apiVersion))
throw new Error(
"Invalid API version. Valid values are: " + k.join(", ")
);
this.apiVersion = n.apiVersion;
} else
this.apiVersion = H;
const o = Me(t, this.apiVersion);
this.customers = new le(o), this.products = new ce(o), this.invoices = new ue(o), this.organizations = new _e(o), this.catalogs = new Oe(o), this.receipts = new Ae(o), this.retentions = new ye(o), this.tools = new be(o), this.webhooks = new Ie(o);
}
}
export {
Ge as ApiEventDataType,
Ue as ApiEventType,
we as CancellationMotive,
ge as CancellationStatus,
Se as GlobalInvoicePeriodicity,
X as IepsMode,
Ce as InvoiceComplementType,
$ as InvoiceRelation,
Z as InvoiceStatus,
Y as InvoiceType,
Q as InvoiceUse,
De as InvoicingPeriod,
Re as IssuingType,
q as PaymentForm,
Fe as PaymentFormList,
K as PaymentMethod,
Ne as ReceiptStatus,
J as TaxFactor,
W as TaxSystem,
x as TaxType,
Ve as WebhookEndpointStatus,
ke as default
};