facturapi
Version:
Librería oficial de Facturapi. Crea CFDIs timbrados y enviados al SAT, XML y PDF
3 lines (2 loc) • 27.1 kB
JavaScript
;var Ie=Object.create;var Q=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var Ne=Object.getPrototypeOf,Re=Object.prototype.hasOwnProperty;var ge=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of be(t))!Re.call(e,u)&&u!==n&&Q(e,u,{get:()=>t[u],enumerable:!(s=Se(t,u))||s.enumerable});return e};var Y=(e,t,n)=>(n=e!=null?Ie(Ne(e)):{},ge(t||!e||!e.__esModule?Q(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});class De{constructor(t){this.client=t}create(t,n=null){return this.client.post("/customers",{body:t,params:n})}list(t){return t||(t={}),this.client.get("/customers",{params:t})}retrieve(t){return t?this.client.get("/customers/"+t):Promise.reject(new Error("id is required"))}update(t,n,s=null){return this.client.put("/customers/"+t,{body:n,params:s})}del(t){return this.client.delete("/customers/"+t)}validateTaxInfo(t){return this.client.get("/customers/"+t+"/tax-info-validation")}sendEditLinkByEmail(t,n){return this.client.post("/customers/"+t+"/email-edit-link",{body:n})}}class Ce{constructor(t){this.client=t}create(t){return this.client.post("/products",{body:t})}list(t){return this.client.get("/products",{params:t})}retrieve(t){return t?this.client.get("/products/"+t):Promise.reject(new Error("id is required"))}update(t,n){return this.client.put("/products/"+t,{body:n})}del(t){return this.client.delete("/products/"+t)}}class Te{constructor(t){this.client=t}create(t,n){return this.client.post("/invoices",{body:t,params:n})}list(t){return t||(t={}),this.client.get("/invoices",{params:t})}retrieve(t){return t?this.client.get("/invoices/"+t):Promise.reject(new Error("id is required"))}cancel(t,n){return this.client.delete("/invoices/"+t,{params:n})}sendByEmail(t,n){return this.client.post("/invoices/"+t+"/email",{body:n})}async downloadPdf(t){return this.client.get("/invoices/"+t+"/pdf")}async downloadXml(t){return this.client.get("/invoices/"+t+"/xml")}downloadZip(t){return this.client.get("/invoices/"+t+"/zip")}downloadCancellationReceiptXml(t){return this.client.get("/invoices/"+t+"/cancellation_receipt/xml")}downloadCancellationReceiptPdf(t){return this.client.get("/invoices/"+t+"/cancellation_receipt/pdf")}updateDraft(t,n){return this.client.put("/invoices/"+t,{body:n})}stampDraft(t,n){return this.client.post("/invoices/"+t+"/stamp",{params:n})}updateStatus(t){return this.client.put("/invoices/"+t+"/status")}copyToDraft(t){return this.client.post("/invoices/"+t+"/copy")}}var we=function(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:window}(),{FormData:$,Blob:Ye,File:ve}=we;const Pe="https://www.facturapi.io/v2",me="https://www.facturapi.io/v1",ee="v2",w=typeof process<"u"&&!!process?.versions?.node,te=typeof navigator<"u"&&navigator?.product==="ReactNative";function Be(e){return new Promise((t,n)=>{const s=[];e.on("data",u=>s.push(u)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",n)})}const L=async(e,t,n)=>{if(w){const s=e instanceof Buffer?e:await Be(e);return new ve([s],t,{type:n})}return e};class Le{constructor(t){this.client=t}create(t){return this.client.post("/organizations",{body:t})}list(t){return t||(t={}),this.client.get("/organizations",{params:t})}retrieve(t){return t?this.client.get("/organizations/"+t):Promise.reject(new Error("id is required"))}updateLegal(t,n){return t?this.client.put("/organizations/"+t+"/legal",{body:n}):Promise.reject(new Error("id is required"))}updateCustomization(t,n){return this.client.put("/organizations/"+t+"/customization",{body:n})}updateReceiptSettings(t,n){return this.client.put("/organizations/"+t+"/receipts",{body:n})}updateDomain(t,n){return this.client.put("/organizations/"+t+"/domain",{body:n})}checkDomainIsAvailable(t){return this.client.put("/organizations/domain-check",{body:t})}async uploadLogo(t,n){const s=await L(n,"file","application/octet-stream"),u=new $;return u.append("file",s,"file"),this.client.put("/organizations/"+t+"/logo",{formData:u})}async uploadCertificate(t,n,s,u){let l=new $;const[c,d]=await Promise.all([L(n,"cer.cer","application/octet-stream"),L(s,"key.key","application/octet-stream")]);return l.append("cer",c,"cer.cer"),l.append("key",d,"key.key"),l.append("password",u),this.client.put("/organizations/"+t+"/certificate",{formData:l})}deleteCertificate(t){return this.client.delete("/organizations/"+t+"/certificate")}del(t){return t?this.client.delete("/organizations/"+t):Promise.reject(new Error("id is required"))}getTestApiKey(t){return this.client.get("/organizations/"+t+"/apikeys/test")}renewTestApiKey(t){return this.client.put("/organizations/"+t+"/apikeys/test")}async listLiveApiKeys(t){return this.client.get("/organizations/"+t+"/apikeys/live")}renewLiveApiKey(t){return this.client.put("/organizations/"+t+"/apikeys/live")}async deleteLiveApiKey(t,n){return this.client.delete("/organizations/"+t+"/apikeys/live/"+n)}listSeriesGroup(t){return this.client.get("/organizations/"+t+"/series-group")}createSeriesGroup(t,n){return this.client.post("/organizations/"+t+"/series-group",{body:n})}updateSeriesGroup(t,n,s){return this.client.put(`/organizations/${t}/series-group/${n}`,{body:s})}deleteSeriesGroup(t,n){return this.client.delete(`/organizations/${t}/series-group/${n}`)}me(){return this.client.get("/organizations/me")}updateSelfInvoiceSettings(t,n){return this.client.put("/organizations/"+t+"/self-invoice",{body:n})}}class Me{constructor(t){this.client=t}searchProducts(t){return this.client.get("/catalogs/products",{params:t})}searchUnits(t){return this.client.get("/catalogs/units",{params:t})}}class Ue{constructor(t){this.client=t}create(t){return this.client.post("/receipts",{body:t})}list(t){return t||(t={}),this.client.get("/receipts",{params:t})}retrieve(t){return t?this.client.get("/receipts/"+t):Promise.reject(new Error("id is required"))}invoice(t,n){return this.client.post("/receipts/"+t+"/invoice",{body:n})}createGlobalInvoice(t){return this.client.post("/receipts/global-invoice",{body:t})}cancel(t){return this.client.delete("/receipts/"+t)}sendByEmail(t,n){return this.client.post("/receipts/"+t+"/email",{body:n})}downloadPdf(t){return this.client.get("/receipts/"+t+"/pdf")}}class Ge{constructor(t){this.client=t}create(t){return this.client.post("/retentions",{body:t})}list(t){return t||(t={}),this.client.get("/retentions",{params:t})}retrieve(t){return t?this.client.get("/retentions/"+t):Promise.reject(new Error("id is required"))}cancel(t){return this.client.delete("/retentions/"+t)}sendByEmail(t,n){return this.client.post("/retentions/"+t+"/email",{body:n})}downloadPdf(t){return this.client.get("/retentions/"+t+"/pdf")}downloadXml(t){return this.client.get("/retentions/"+t+"/xml")}downloadZip(t){return this.client.get("/retentions/"+t+"/zip")}}class Ve{constructor(t){this.client=t}create(t){return this.client.post("/webhooks",{body:t})}list(t){return t||(t={}),this.client.get("/webhooks",{params:t})}retrieve(t){return t?this.client.get("/webhooks/"+t):Promise.reject(new Error("id is required"))}update(t,n){return this.client.put("/webhooks/"+t,{body:n})}del(t){return this.client.delete("/webhooks/"+t)}async validateSignature(t){const{secret:n,signature:s,payload:u}=t;let l;if(typeof u=="string")l=u;else if(Buffer.isBuffer(u))l=u.toString("utf8");else if(typeof u=="object")l=JSON.stringify(u);else throw new Error("Invalid payload type");if(te)return this.client.post("/webhooks/validate-signature",{body:{secret:n,signature:s,payload:l}});if(w){const c=await import("crypto"),h=c.createHmac("sha256",n).update(l).digest(),A=Buffer.from(s,"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,d=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"]),d),b=Array.from(new Uint8Array(A)).map(N=>N.toString(16).padStart(2,"0")).join("").toLowerCase();if(s!==b)throw new Error("Invalid signature")}return JSON.parse(l)}}class Fe{constructor(t){this.client=t}validateTaxId(t){return this.client.get("/tools/tax_id_validation",{params:{tax_id:t}})}}var M=(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))(M||{});const je=[{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 U=(e=>(e.IVA="IVA",e.IEPS="IEPS",e.ISR="ISR",e))(U||{}),G=(e=>(e.RATE="Tasa",e.QUOTA="Cuota",e))(G||{}),V=(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))(V||{}),F=(e=>(e.PAGO_EN_UNA_EXHIBICION="PUE",e.PAGO_EN_PARCIALIDADES_DIFERIDO="PPD",e))(F||{}),j=(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))(j||{}),k=(e=>(e.INGRESO="I",e.EGRESO="E",e.TRASLADO="T",e.NOMINA="N",e.PAGO="P",e))(k||{}),H=(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))(H||{}),z=(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))(z||{}),q=(e=>(e.DRAFT="draft",e.PENDING="pending",e.VALID="valid",e.CANCELED="canceled",e.FAILED="failed",e))(q||{}),re=(e=>(e.DAY="day",e.WEEK="week",e.FORTNIGHT="fortnight",e.MONTH="month",e.TWO_MONTHS="two_months",e))(re||{}),ie=(e=>(e.OPEN="open",e.CANCELED="canceled",e.INVOICED_TO_CUSTOMER="invoiced_to_customer",e.INVOICED_GLOBALLY="invoiced_globally",e))(ie||{}),ne=(e=>(e.ISSUING="issuing",e.RECEIVING="receiving",e))(ne||{}),se=(e=>(e.NONE="none",e.ACCEPTED="accepted",e.PENDING="pending",e.REJECTED="rejected",e.EXPIRED="expired",e))(se||{}),oe=(e=>(e.DAY="day",e.WEEK="week",e.FORTNIGHT="fortnight",e.MONTH="month",e.TWO_MONTHS="two_months",e))(oe||{}),ae=(e=>(e.CUSTOM="custom",e.PAGO="pago",e.NOMINA="nomina",e))(ae||{}),le=(e=>(e.ERRORES_CON_RELACION="01",e.ERRORES_SIN_RELACION="02",e.NO_SE_CONCRETO="03",e.FACTURA_GLOBAL="04",e))(le||{}),D=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ke(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var C={exports:{}},W;function He(){return W||(W=1,function(e,t){var n=typeof globalThis<"u"&&globalThis||typeof self<"u"&&self||typeof D<"u"&&D,s=function(){function l(){this.fetch=!1,this.DOMException=n.DOMException}return l.prototype=n,new l}();(function(l){(function(c){var d=typeof l<"u"&&l||typeof self<"u"&&self||typeof D<"u"&&D||{},h={searchParams:"URLSearchParams"in d,iterable:"Symbol"in d&&"iterator"in Symbol,blob:"FileReader"in d&&"Blob"in d&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in d,arrayBuffer:"ArrayBuffer"in d};function A(r){return r&&DataView.prototype.isPrototypeOf(r)}if(h.arrayBuffer)var b=["[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&&b.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 o=r.shift();return{done:o===void 0,value:o}}};return h.iterable&&(i[Symbol.iterator]=function(){return i}),i}function p(r){this.map={},r instanceof p?r.forEach(function(i,o){this.append(o,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 o=this.map[r];this.map[r]=o?o+", "+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 o in this.map)this.map.hasOwnProperty(o)&&r.call(i,this.map[o],o,this)},p.prototype.keys=function(){var r=[];return this.forEach(function(i,o){r.push(o)}),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,o){r.push([o,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 x(r){return new Promise(function(i,o){r.onload=function(){i(r.result)},r.onerror=function(){o(r.error)}})}function de(r){var i=new FileReader,o=x(i);return i.readAsArrayBuffer(r),o}function he(r){var i=new FileReader,o=x(i),f=/charset=([A-Za-z0-9_-]+)/.exec(r.type),E=f?f[1]:"utf-8";return i.readAsText(r,E),o}function Ee(r){for(var i=new Uint8Array(r),o=new Array(i.length),f=0;f<i.length;f++)o[f]=String.fromCharCode(i[f]);return o.join("")}function J(r){if(r.slice)return r.slice(0);var i=new Uint8Array(r.byteLength);return i.set(new Uint8Array(r)),i.buffer}function X(){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=J(r.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):h.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(r)||N(r))?this._bodyArrayBuffer=J(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(de);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var r=P(this);if(r)return r;if(this._bodyBlob)return he(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(Ee(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(Oe)}),this.json=function(){return this.text().then(JSON.parse)},this}var pe=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function _e(r){var i=r.toUpperCase();return pe.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 o=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,!o&&r._bodyInit!=null&&(o=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=_e(i.method||this.method||"GET"),this.mode=i.mode||this.mode||null,this.signal=i.signal||this.signal||function(){if("AbortController"in d){var a=new AbortController;return a.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&o)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(o),(this.method==="GET"||this.method==="HEAD")&&(i.cache==="no-store"||i.cache==="no-cache")){var f=/([?&])_=[^&]*/;if(f.test(this.url))this.url=this.url.replace(f,"$1_="+new Date().getTime());else{var E=/\?/;this.url+=(E.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}I.prototype.clone=function(){return new I(this,{body:this._bodyInit})};function Oe(r){var i=new FormData;return r.trim().split("&").forEach(function(o){if(o){var f=o.split("="),E=f.shift().replace(/\+/g," "),a=f.join("=").replace(/\+/g," ");i.append(decodeURIComponent(E),decodeURIComponent(a))}}),i}function Ae(r){var i=new p,o=r.replace(/\r?\n[\t ]+/g," ");return o.split("\r").map(function(f){return f.indexOf(`
`)===0?f.substr(1,f.length):f}).forEach(function(f){var E=f.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}X.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)}X.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 ye=[301,302,303,307,308];O.redirect=function(r,i){if(ye.indexOf(i)===-1)throw new RangeError("Invalid status code");return new O(null,{status:i,headers:{location:r}})},c.DOMException=d.DOMException;try{new c.DOMException}catch{c.DOMException=function(i,o){this.message=i,this.name=o;var f=Error(i);this.stack=f.stack},c.DOMException.prototype=Object.create(Error.prototype),c.DOMException.prototype.constructor=c.DOMException}function m(r,i){return new Promise(function(o,f){var E=new I(r,i);if(E.signal&&E.signal.aborted)return f(new c.DOMException("Aborted","AbortError"));var a=new XMLHttpRequest;function g(){a.abort()}a.onload=function(){var _={statusText:a.statusText,headers:Ae(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 S="response"in a?a.response:a.responseText;setTimeout(function(){o(new O(S,_))},0)},a.onerror=function(){setTimeout(function(){f(new TypeError("Network request failed"))},0)},a.ontimeout=function(){setTimeout(function(){f(new TypeError("Network request timed out"))},0)},a.onabort=function(){setTimeout(function(){f(new c.DOMException("Aborted","AbortError"))},0)};function B(_){try{return _===""&&d.location.href?d.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||d.Headers&&i.headers instanceof d.Headers)){var K=[];Object.getOwnPropertyNames(i.headers).forEach(function(_){K.push(y(_)),a.setRequestHeader(_,R(i.headers[_]))}),E.headers.forEach(function(_,S){K.indexOf(S)===-1&&a.setRequestHeader(S,_)})}else E.headers.forEach(function(_,S){a.setRequestHeader(S,_)});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,d.fetch||(d.fetch=m,d.Headers=p,d.Request=I,d.Response=O),c.Headers=p,c.Request=I,c.Response=O,c.fetch=m,c})({})})(s),s.fetch.ponyfill=!0,delete s.fetch.polyfill;var u=n.fetch?n:s;t=u.fetch,t.default=u.fetch,t.fetch=u.fetch,t.Headers=u.Headers,t.Request=u.Request,t.Response=u.Response,e.exports=t}(C,C.exports)),C.exports}var ze=He();const qe=ke(ze);let T;w?T=e=>Buffer.from(e).toString("base64"):te?T=e=>globalThis.Buffer.from(e).toString("base64"):T=globalThis.btoa;const xe=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(w){const n=e.body?.getReader();if(!n)return e.body;try{const{Readable:s}=await import("stream");return new s({read(){n.read().then(({done:u,value:l})=>{u?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 Je(e){return T(e)}const Xe=(e,t=ee)=>{const n=t==="v1"?me:Pe,s={Authorization:`Basic ${Je(e+":")}`};return{async request(l,c){const{params:d,body:h,formData:A,...b}=c||{},N=d?"?"+new URLSearchParams(d).toString():"",y={...b,headers:{...s,...A?{}:{"Content-Type":"application/json"}},body:A||(h?JSON.stringify(h):void 0)},R=await qe(n+l+N,y);return xe(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 ce=(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))(ce||{}),ue=(e=>(e.RECEIPT="receipt",e.INVOICE="invoice",e.CUSTOMER="customer",e))(ue||{}),fe=(e=>(e.ENABLED="enabled",e.DISABLED="disabled",e))(fe||{});const Z=["v1","v2"];class Ke{static get TaxType(){return U}static get TaxFactor(){return G}static get IepsMode(){return V}static get PaymentForm(){return M}static get PaymentMethod(){return F}static get InvoiceType(){return k}static get InvoiceUse(){return j}static get InvoiceRelation(){return H}static get TaxSystem(){return z}static get InvoiceStatus(){return q}constructor(t,n={}){if(n.apiVersion){if(!Z.includes(n.apiVersion))throw new Error("Invalid API version. Valid values are: "+Z.join(", "));this.apiVersion=n.apiVersion}else this.apiVersion=ee;const s=Xe(t,this.apiVersion);this.customers=new De(s),this.products=new Ce(s),this.invoices=new Te(s),this.organizations=new Le(s),this.catalogs=new Me(s),this.receipts=new Ue(s),this.retentions=new Ge(s),this.tools=new Fe(s),this.webhooks=new Ve(s)}}exports.ApiEventDataType=ue;exports.ApiEventType=ce;exports.CancellationMotive=le;exports.CancellationStatus=se;exports.GlobalInvoicePeriodicity=re;exports.IepsMode=V;exports.InvoiceComplementType=ae;exports.InvoiceRelation=H;exports.InvoiceStatus=q;exports.InvoiceType=k;exports.InvoiceUse=j;exports.InvoicingPeriod=oe;exports.IssuingType=ne;exports.PaymentForm=M;exports.PaymentFormList=je;exports.PaymentMethod=F;exports.ReceiptStatus=ie;exports.TaxFactor=G;exports.TaxSystem=z;exports.TaxType=U;exports.WebhookEndpointStatus=fe;exports.default=Ke;