@eusilvio/cep-lookup 1.2.1 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ CepLookup: () => CepLookup,
24
+ InMemoryCache: () => InMemoryCache,
25
+ lookupCep: () => lookupCep
26
+ });
27
+ module.exports = __toCommonJS(src_exports);
28
+
29
+ // src/cache/index.ts
30
+ var InMemoryCache = class {
31
+ constructor() {
32
+ this.cache = /* @__PURE__ */ new Map();
33
+ }
34
+ /**
35
+ * @method get
36
+ * @description Retrieves an address from the cache.
37
+ * @param {string} key - The CEP to look up.
38
+ * @returns {Address | undefined} The cached address or undefined if not found.
39
+ */
40
+ get(key) {
41
+ return this.cache.get(key);
42
+ }
43
+ /**
44
+ * @method set
45
+ * @description Stores an address in the cache.
46
+ * @param {string} key - The CEP to use as the cache key.
47
+ * @param {Address} value - The address to store.
48
+ */
49
+ set(key, value) {
50
+ this.cache.set(key, value);
51
+ }
52
+ /**
53
+ * @method clear
54
+ * @description Clears the entire cache.
55
+ */
56
+ clear() {
57
+ this.cache.clear();
58
+ }
59
+ };
60
+
61
+ // src/index.ts
62
+ function validateCep(cep) {
63
+ const cleanedCep = cep.replace(/\D/g, "");
64
+ if (cleanedCep.length !== 8) {
65
+ throw new Error("Invalid CEP. It must have 8 digits.");
66
+ }
67
+ return cleanedCep;
68
+ }
69
+ var CepLookup = class {
70
+ /**
71
+ * @constructor
72
+ * @param {CepLookupOptions} options - The options for initializing the CepLookup instance.
73
+ */
74
+ constructor(options) {
75
+ this.providers = options.providers;
76
+ this.fetcher = options.fetcher || (async (url, signal) => {
77
+ const response = await fetch(url, { signal });
78
+ if (!response.ok) {
79
+ throw new Error(`HTTP error! status: ${response.status}`);
80
+ }
81
+ return response.json();
82
+ });
83
+ this.cache = options.cache;
84
+ }
85
+ /**
86
+ * @method lookup
87
+ * @description Looks up an address for a given CEP.
88
+ * @template T - The expected return type, defaults to `Address`.
89
+ * @param {string} cep - The CEP to be queried.
90
+ * @param {(address: Address) => T} [mapper] - An optional function to transform the `Address` object into a custom format `T`.
91
+ * @returns {Promise<T>} A Promise that resolves to the address in the default `Address` format or a custom format `T` if a mapper is provided.
92
+ * @throws {Error} If the CEP is invalid or if all providers fail to find the CEP.
93
+ */
94
+ async lookup(cep, mapper) {
95
+ const cleanedCep = validateCep(cep);
96
+ if (this.cache) {
97
+ const cachedAddress = this.cache.get(cleanedCep);
98
+ if (cachedAddress) {
99
+ return Promise.resolve(mapper ? mapper(cachedAddress) : cachedAddress);
100
+ }
101
+ }
102
+ const controller = new AbortController();
103
+ const { signal } = controller;
104
+ const promises = this.providers.map((provider) => {
105
+ const url = provider.buildUrl(cleanedCep);
106
+ const timeoutPromise = new Promise((resolve, reject) => {
107
+ let timeoutId;
108
+ const onAbort = () => {
109
+ clearTimeout(timeoutId);
110
+ reject(new DOMException("Aborted", "AbortError"));
111
+ };
112
+ if (provider.timeout) {
113
+ timeoutId = setTimeout(() => {
114
+ signal.removeEventListener("abort", onAbort);
115
+ reject(new Error(`Timeout from ${provider.name}`));
116
+ }, provider.timeout);
117
+ signal.addEventListener("abort", onAbort, { once: true });
118
+ } else {
119
+ signal.addEventListener("abort", onAbort, { once: true });
120
+ }
121
+ });
122
+ const fetchPromise = this.fetcher(url, signal).then((response) => provider.transform(response)).then((address) => {
123
+ if (this.cache) {
124
+ this.cache.set(cleanedCep, address);
125
+ }
126
+ return mapper ? mapper(address) : address;
127
+ });
128
+ return Promise.race([fetchPromise, timeoutPromise]);
129
+ });
130
+ try {
131
+ return await Promise.any(promises);
132
+ } finally {
133
+ controller.abort();
134
+ }
135
+ }
136
+ };
137
+ function lookupCep(options) {
138
+ const { cep, providers, fetcher, mapper, cache } = options;
139
+ const cepLookup = new CepLookup({ providers, fetcher, cache });
140
+ return cepLookup.lookup(cep, mapper);
141
+ }
142
+ // Annotate the CommonJS export names for ESM import in node:
143
+ 0 && (module.exports = {
144
+ CepLookup,
145
+ InMemoryCache,
146
+ lookupCep
147
+ });
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/providers/index.ts
21
+ var providers_exports = {};
22
+ __export(providers_exports, {
23
+ apicepProvider: () => apicepProvider,
24
+ brasilApiProvider: () => brasilApiProvider,
25
+ viaCepProvider: () => viaCepProvider
26
+ });
27
+ module.exports = __toCommonJS(providers_exports);
28
+
29
+ // src/providers/viacep.ts
30
+ var viaCepProvider = {
31
+ name: "ViaCEP",
32
+ buildUrl: (cep) => `https://viacep.com.br/ws/${cep}/json/`,
33
+ transform: (response) => {
34
+ if (response.erro) {
35
+ throw new Error("CEP not found");
36
+ }
37
+ return {
38
+ cep: response.cep,
39
+ state: response.uf,
40
+ city: response.localidade,
41
+ neighborhood: response.bairro,
42
+ street: response.logradouro,
43
+ service: "ViaCEP"
44
+ };
45
+ }
46
+ };
47
+
48
+ // src/providers/brasil-api.ts
49
+ var brasilApiProvider = {
50
+ name: "BrasilAPI",
51
+ buildUrl: (cep) => `https://brasilapi.com.br/api/cep/v1/${cep}`,
52
+ transform: (response) => {
53
+ return {
54
+ cep: response.cep,
55
+ state: response.state,
56
+ city: response.city,
57
+ neighborhood: response.neighborhood,
58
+ street: response.street,
59
+ service: "BrasilAPI"
60
+ };
61
+ }
62
+ };
63
+
64
+ // src/providers/apicep.ts
65
+ var apicepProvider = {
66
+ name: "ApiCEP",
67
+ buildUrl: (cep) => `https://cdn.apicep.com/file/apicep/${cep}.json`,
68
+ transform: (response) => {
69
+ return {
70
+ cep: response.code,
71
+ state: response.state,
72
+ city: response.city,
73
+ neighborhood: response.district,
74
+ street: response.address,
75
+ service: "ApiCEP"
76
+ };
77
+ }
78
+ };
79
+ // Annotate the CommonJS export names for ESM import in node:
80
+ 0 && (module.exports = {
81
+ apicepProvider,
82
+ brasilApiProvider,
83
+ viaCepProvider
84
+ });
package/package.json CHANGED
@@ -1,21 +1,12 @@
1
1
  {
2
2
  "name": "@eusilvio/cep-lookup",
3
- "version": "1.2.1",
3
+ "version": "1.2.2",
4
4
  "description": "A modern, flexible, and agnostic CEP lookup library written in TypeScript.",
5
- "main": "./dist/cjs/index.js",
6
- "module": "./dist/esm/index.js",
7
- "types": "./dist/index.d.ts",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
8
7
  "exports": {
9
- ".": {
10
- "import": "./dist/esm/index.js",
11
- "require": "./dist/cjs/index.js",
12
- "types": "./dist/index.d.ts"
13
- },
14
- "./providers": {
15
- "import": "./dist/esm/providers/index.js",
16
- "require": "./dist/cjs/providers/index.js",
17
- "types": "./dist/providers/index.d.ts"
18
- }
8
+ ".": "./dist/index.js",
9
+ "./providers": "./dist/providers/index.js"
19
10
  },
20
11
  "sideEffects": false,
21
12
  "files": [
@@ -26,11 +17,8 @@
26
17
  },
27
18
  "scripts": {
28
19
  "clean": "rm -rf dist",
29
- "type:check": "tsc --noEmit",
30
- "build": "npm run clean && npm run type:check && npm run build:types && npm run build:esm && npm run build:cjs",
31
- "build:types": "tsc --emitDeclarationOnly --outDir dist --rootDir src",
32
- "build:esm": "esbuild src/index.ts --outdir=dist/esm --format=esm --platform=neutral --minify && esbuild src/providers/*.ts --outdir=dist/esm/providers --format=esm --platform=neutral --minify",
33
- "build:cjs": "esbuild src/index.ts --outdir=dist/cjs --format=cjs --platform=node --minify && esbuild src/providers/*.ts --outdir=dist/cjs/providers --format=cjs --platform=node --minify",
20
+ "build": "npm run clean && tsc --emitDeclarationOnly --outDir dist && esbuild src/index.ts src/providers/index.ts --outdir=dist --bundle --platform=node --format=cjs",
21
+ "build:prod": "npm run clean && tsc --emitDeclarationOnly --outDir dist && esbuild src/index.ts src/providers/index.ts --outdir=dist --bundle --platform=node --format=cjs --minify",
34
22
  "test": "jest"
35
23
  },
36
24
  "keywords": [
package/dist/cjs/index.js DELETED
@@ -1 +0,0 @@
1
- "use strict";var p=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var k=Object.getOwnPropertyNames;var P=Object.prototype.hasOwnProperty;var g=(o,e)=>{for(var r in e)p(o,r,{get:e[r],enumerable:!0})},A=(o,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of k(e))!P.call(o,t)&&t!==r&&p(o,t,{get:()=>e[t],enumerable:!(n=C(e,t))||n.enumerable});return o};var b=o=>A(p({},"__esModule",{value:!0}),o);var y={};g(y,{Address:()=>s.Address,Cache:()=>h.Cache,CepLookup:()=>f,CepLookupOptions:()=>s.CepLookupOptions,Fetcher:()=>s.Fetcher,InMemoryCache:()=>h.InMemoryCache,Provider:()=>s.Provider,lookupCep:()=>L});module.exports=b(y);var s=require("./types"),h=require("./cache");function E(o){const e=o.replace(/\D/g,"");if(e.length!==8)throw new Error("Invalid CEP. It must have 8 digits.");return e}class f{constructor(e){this.providers=e.providers,this.fetcher=e.fetcher||(async(r,n)=>{const t=await fetch(r,{signal:n});if(!t.ok)throw new Error(`HTTP error! status: ${t.status}`);return t.json()}),this.cache=e.cache}async lookup(e,r){const n=E(e);if(this.cache){const c=this.cache.get(n);if(c)return Promise.resolve(r?r(c):c)}const t=new AbortController,{signal:i}=t,d=this.providers.map(c=>{const v=c.buildUrl(n),T=new Promise((a,m)=>{let l;const u=()=>{clearTimeout(l),m(new DOMException("Aborted","AbortError"))};c.timeout?(l=setTimeout(()=>{i.removeEventListener("abort",u),m(new Error(`Timeout from ${c.name}`))},c.timeout),i.addEventListener("abort",u,{once:!0})):i.addEventListener("abort",u,{once:!0})}),w=this.fetcher(v,i).then(a=>c.transform(a)).then(a=>(this.cache&&this.cache.set(n,a),r?r(a):a));return Promise.race([w,T])});try{return await Promise.any(d)}finally{t.abort()}}}function L(o){const{cep:e,providers:r,fetcher:n,mapper:t,cache:i}=o;return new f({providers:r,fetcher:n,cache:i}).lookup(e,t)}0&&(module.exports={Address,Cache,CepLookup,CepLookupOptions,Fetcher,InMemoryCache,Provider,lookupCep});
@@ -1 +0,0 @@
1
- "use strict";var e=Object.defineProperty;var o=Object.getOwnPropertyDescriptor;var a=Object.getOwnPropertyNames;var p=Object.prototype.hasOwnProperty;var s=(i,r)=>{for(var d in r)e(i,d,{get:r[d],enumerable:!0})},m=(i,r,d,c)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of a(r))!p.call(i,t)&&t!==d&&e(i,t,{get:()=>r[t],enumerable:!(c=o(r,t))||c.enumerable});return i};var n=i=>m(e({},"__esModule",{value:!0}),i);var v={};s(v,{apicepProvider:()=>P});module.exports=n(v);const P={name:"ApiCEP",buildUrl:i=>`https://cdn.apicep.com/file/apicep/${i}.json`,transform:i=>({cep:i.code,state:i.state,city:i.city,neighborhood:i.district,street:i.address,service:"ApiCEP"})};0&&(module.exports={apicepProvider});
@@ -1 +0,0 @@
1
- "use strict";var a=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var s=Object.getOwnPropertyNames;var c=Object.prototype.hasOwnProperty;var b=(r,i)=>{for(var e in i)a(r,e,{get:i[e],enumerable:!0})},l=(r,i,e,o)=>{if(i&&typeof i=="object"||typeof i=="function")for(let t of s(i))!c.call(r,t)&&t!==e&&a(r,t,{get:()=>i[t],enumerable:!(o=d(i,t))||o.enumerable});return r};var h=r=>l(a({},"__esModule",{value:!0}),r);var p={};b(p,{brasilApiProvider:()=>m});module.exports=h(p);const m={name:"BrasilAPI",buildUrl:r=>`https://brasilapi.com.br/api/cep/v1/${r}`,transform:r=>({cep:r.cep,state:r.state,city:r.city,neighborhood:r.neighborhood,street:r.street,service:"BrasilAPI"})};0&&(module.exports={brasilApiProvider});
@@ -1 +0,0 @@
1
- "use strict";var a=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var t=(f,r,p,x)=>{if(r&&typeof r=="object"||typeof r=="function")for(let m of c(r))!d.call(f,m)&&m!==p&&a(f,m,{get:()=>r[m],enumerable:!(x=b(r,m))||x.enumerable});return f},e=(f,r,p)=>(t(f,r,"default"),p&&t(p,r,"default"));var g=f=>t(a({},"__esModule",{value:!0}),f);var o={};module.exports=g(o);e(o,require("./viacep"),module.exports);e(o,require("./brasil-api"),module.exports);e(o,require("./apicep"),module.exports);0&&(module.exports={...require("./viacep"),...require("./brasil-api"),...require("./apicep")});
@@ -1 +0,0 @@
1
- "use strict";var d=Object.defineProperty;var e=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var n=Object.prototype.hasOwnProperty;var v=(r,o)=>{for(var t in o)d(r,t,{get:o[t],enumerable:!0})},P=(r,o,t,a)=>{if(o&&typeof o=="object"||typeof o=="function")for(let i of c(o))!n.call(r,i)&&i!==t&&d(r,i,{get:()=>o[i],enumerable:!(a=e(o,i))||a.enumerable});return r};var f=r=>P(d({},"__esModule",{value:!0}),r);var m={};v(m,{viaCepProvider:()=>l});module.exports=f(m);const l={name:"ViaCEP",buildUrl:r=>`https://viacep.com.br/ws/${r}/json/`,transform:r=>{if(r.erro)throw new Error("CEP not found");return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouro,service:"ViaCEP"}}};0&&(module.exports={viaCepProvider});
package/dist/esm/index.js DELETED
@@ -1 +0,0 @@
1
- import{Address as f,Fetcher as v,Provider as T,CepLookupOptions as w}from"./types";import{Cache as C,InMemoryCache as k}from"./cache";function P(i){const e=i.replace(/\D/g,"");if(e.length!==8)throw new Error("Invalid CEP. It must have 8 digits.");return e}class g{constructor(e){this.providers=e.providers,this.fetcher=e.fetcher||(async(r,s)=>{const o=await fetch(r,{signal:s});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return o.json()}),this.cache=e.cache}async lookup(e,r){const s=P(e);if(this.cache){const t=this.cache.get(s);if(t)return Promise.resolve(r?r(t):t)}const o=new AbortController,{signal:n}=o,h=this.providers.map(t=>{const d=t.buildUrl(s),m=new Promise((c,u)=>{let p;const a=()=>{clearTimeout(p),u(new DOMException("Aborted","AbortError"))};t.timeout?(p=setTimeout(()=>{n.removeEventListener("abort",a),u(new Error(`Timeout from ${t.name}`))},t.timeout),n.addEventListener("abort",a,{once:!0})):n.addEventListener("abort",a,{once:!0})}),l=this.fetcher(d,n).then(c=>t.transform(c)).then(c=>(this.cache&&this.cache.set(s,c),r?r(c):c));return Promise.race([l,m])});try{return await Promise.any(h)}finally{o.abort()}}}function E(i){const{cep:e,providers:r,fetcher:s,mapper:o,cache:n}=i;return new g({providers:r,fetcher:s,cache:n}).lookup(e,o)}export{f as Address,C as Cache,g as CepLookup,w as CepLookupOptions,v as Fetcher,k as InMemoryCache,T as Provider,E as lookupCep};
@@ -1 +0,0 @@
1
- const e={name:"ApiCEP",buildUrl:i=>`https://cdn.apicep.com/file/apicep/${i}.json`,transform:i=>({cep:i.code,state:i.state,city:i.city,neighborhood:i.district,street:i.address,service:"ApiCEP"})};export{e as apicepProvider};
@@ -1 +0,0 @@
1
- const a={name:"BrasilAPI",buildUrl:r=>`https://brasilapi.com.br/api/cep/v1/${r}`,transform:r=>({cep:r.cep,state:r.state,city:r.city,neighborhood:r.neighborhood,street:r.street,service:"BrasilAPI"})};export{a as brasilApiProvider};
@@ -1 +0,0 @@
1
- export*from"./viacep";export*from"./brasil-api";export*from"./apicep";
@@ -1 +0,0 @@
1
- const d={name:"ViaCEP",buildUrl:r=>`https://viacep.com.br/ws/${r}/json/`,transform:r=>{if(r.erro)throw new Error("CEP not found");return{cep:r.cep,state:r.uf,city:r.localidade,neighborhood:r.bairro,street:r.logradouro,service:"ViaCEP"}}};export{d as viaCepProvider};