1 | (function (global, factory) {
|
2 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
|
3 | typeof define === 'function' && define.amd ? define(factory) :
|
4 | (global = global || self, global.cep = factory());
|
5 | }(this, (function () { 'use strict';
|
6 |
|
7 | function _typeof(obj) {
|
8 | "@babel/helpers - typeof";
|
9 |
|
10 | return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
|
11 | return typeof obj;
|
12 | } : function (obj) {
|
13 | return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
|
14 | }, _typeof(obj);
|
15 | }
|
16 |
|
17 | function _classCallCheck(instance, Constructor) {
|
18 | if (!(instance instanceof Constructor)) {
|
19 | throw new TypeError("Cannot call a class as a function");
|
20 | }
|
21 | }
|
22 |
|
23 | function _defineProperties(target, props) {
|
24 | for (var i = 0; i < props.length; i++) {
|
25 | var descriptor = props[i];
|
26 | descriptor.enumerable = descriptor.enumerable || false;
|
27 | descriptor.configurable = true;
|
28 | if ("value" in descriptor) descriptor.writable = true;
|
29 | Object.defineProperty(target, descriptor.key, descriptor);
|
30 | }
|
31 | }
|
32 |
|
33 | function _createClass(Constructor, protoProps, staticProps) {
|
34 | if (protoProps) _defineProperties(Constructor.prototype, protoProps);
|
35 | if (staticProps) _defineProperties(Constructor, staticProps);
|
36 | Object.defineProperty(Constructor, "prototype", {
|
37 | writable: false
|
38 | });
|
39 | return Constructor;
|
40 | }
|
41 |
|
42 | function _inherits(subClass, superClass) {
|
43 | if (typeof superClass !== "function" && superClass !== null) {
|
44 | throw new TypeError("Super expression must either be null or a function");
|
45 | }
|
46 |
|
47 | subClass.prototype = Object.create(superClass && superClass.prototype, {
|
48 | constructor: {
|
49 | value: subClass,
|
50 | writable: true,
|
51 | configurable: true
|
52 | }
|
53 | });
|
54 | Object.defineProperty(subClass, "prototype", {
|
55 | writable: false
|
56 | });
|
57 | if (superClass) _setPrototypeOf(subClass, superClass);
|
58 | }
|
59 |
|
60 | function _getPrototypeOf(o) {
|
61 | _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
|
62 | return o.__proto__ || Object.getPrototypeOf(o);
|
63 | };
|
64 | return _getPrototypeOf(o);
|
65 | }
|
66 |
|
67 | function _setPrototypeOf(o, p) {
|
68 | _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
|
69 | o.__proto__ = p;
|
70 | return o;
|
71 | };
|
72 |
|
73 | return _setPrototypeOf(o, p);
|
74 | }
|
75 |
|
76 | function _isNativeReflectConstruct() {
|
77 | if (typeof Reflect === "undefined" || !Reflect.construct) return false;
|
78 | if (Reflect.construct.sham) return false;
|
79 | if (typeof Proxy === "function") return true;
|
80 |
|
81 | try {
|
82 | Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
|
83 | return true;
|
84 | } catch (e) {
|
85 | return false;
|
86 | }
|
87 | }
|
88 |
|
89 | function _construct(Parent, args, Class) {
|
90 | if (_isNativeReflectConstruct()) {
|
91 | _construct = Reflect.construct;
|
92 | } else {
|
93 | _construct = function _construct(Parent, args, Class) {
|
94 | var a = [null];
|
95 | a.push.apply(a, args);
|
96 | var Constructor = Function.bind.apply(Parent, a);
|
97 | var instance = new Constructor();
|
98 | if (Class) _setPrototypeOf(instance, Class.prototype);
|
99 | return instance;
|
100 | };
|
101 | }
|
102 |
|
103 | return _construct.apply(null, arguments);
|
104 | }
|
105 |
|
106 | function _isNativeFunction(fn) {
|
107 | return Function.toString.call(fn).indexOf("[native code]") !== -1;
|
108 | }
|
109 |
|
110 | function _wrapNativeSuper(Class) {
|
111 | var _cache = typeof Map === "function" ? new Map() : undefined;
|
112 |
|
113 | _wrapNativeSuper = function _wrapNativeSuper(Class) {
|
114 | if (Class === null || !_isNativeFunction(Class)) return Class;
|
115 |
|
116 | if (typeof Class !== "function") {
|
117 | throw new TypeError("Super expression must either be null or a function");
|
118 | }
|
119 |
|
120 | if (typeof _cache !== "undefined") {
|
121 | if (_cache.has(Class)) return _cache.get(Class);
|
122 |
|
123 | _cache.set(Class, Wrapper);
|
124 | }
|
125 |
|
126 | function Wrapper() {
|
127 | return _construct(Class, arguments, _getPrototypeOf(this).constructor);
|
128 | }
|
129 |
|
130 | Wrapper.prototype = Object.create(Class.prototype, {
|
131 | constructor: {
|
132 | value: Wrapper,
|
133 | enumerable: false,
|
134 | writable: true,
|
135 | configurable: true
|
136 | }
|
137 | });
|
138 | return _setPrototypeOf(Wrapper, Class);
|
139 | };
|
140 |
|
141 | return _wrapNativeSuper(Class);
|
142 | }
|
143 |
|
144 | function _assertThisInitialized(self) {
|
145 | if (self === void 0) {
|
146 | throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
|
147 | }
|
148 |
|
149 | return self;
|
150 | }
|
151 |
|
152 | function _possibleConstructorReturn(self, call) {
|
153 | if (call && (typeof call === "object" || typeof call === "function")) {
|
154 | return call;
|
155 | } else if (call !== void 0) {
|
156 | throw new TypeError("Derived constructors may only return object or undefined");
|
157 | }
|
158 |
|
159 | return _assertThisInitialized(self);
|
160 | }
|
161 |
|
162 | function _createSuper(Derived) {
|
163 | var hasNativeReflectConstruct = _isNativeReflectConstruct();
|
164 |
|
165 | return function _createSuperInternal() {
|
166 | var Super = _getPrototypeOf(Derived),
|
167 | result;
|
168 |
|
169 | if (hasNativeReflectConstruct) {
|
170 | var NewTarget = _getPrototypeOf(this).constructor;
|
171 |
|
172 | result = Reflect.construct(Super, arguments, NewTarget);
|
173 | } else {
|
174 | result = Super.apply(this, arguments);
|
175 | }
|
176 |
|
177 | return _possibleConstructorReturn(this, result);
|
178 | };
|
179 | }
|
180 |
|
181 | function _toConsumableArray(arr) {
|
182 | return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
|
183 | }
|
184 |
|
185 | function _arrayWithoutHoles(arr) {
|
186 | if (Array.isArray(arr)) return _arrayLikeToArray(arr);
|
187 | }
|
188 |
|
189 | function _iterableToArray(iter) {
|
190 | if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
|
191 | }
|
192 |
|
193 | function _unsupportedIterableToArray(o, minLen) {
|
194 | if (!o) return;
|
195 | if (typeof o === "string") return _arrayLikeToArray(o, minLen);
|
196 | var n = Object.prototype.toString.call(o).slice(8, -1);
|
197 | if (n === "Object" && o.constructor) n = o.constructor.name;
|
198 | if (n === "Map" || n === "Set") return Array.from(o);
|
199 | if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
|
200 | }
|
201 |
|
202 | function _arrayLikeToArray(arr, len) {
|
203 | if (len == null || len > arr.length) len = arr.length;
|
204 |
|
205 | for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
|
206 |
|
207 | return arr2;
|
208 | }
|
209 |
|
210 | function _nonIterableSpread() {
|
211 | throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
212 | }
|
213 |
|
214 | function _createForOfIteratorHelper(o, allowArrayLike) {
|
215 | var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
|
216 |
|
217 | if (!it) {
|
218 | if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
|
219 | if (it) o = it;
|
220 | var i = 0;
|
221 |
|
222 | var F = function () {};
|
223 |
|
224 | return {
|
225 | s: F,
|
226 | n: function () {
|
227 | if (i >= o.length) return {
|
228 | done: true
|
229 | };
|
230 | return {
|
231 | done: false,
|
232 | value: o[i++]
|
233 | };
|
234 | },
|
235 | e: function (e) {
|
236 | throw e;
|
237 | },
|
238 | f: F
|
239 | };
|
240 | }
|
241 |
|
242 | throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
|
243 | }
|
244 |
|
245 | var normalCompletion = true,
|
246 | didErr = false,
|
247 | err;
|
248 | return {
|
249 | s: function () {
|
250 | it = it.call(o);
|
251 | },
|
252 | n: function () {
|
253 | var step = it.next();
|
254 | normalCompletion = step.done;
|
255 | return step;
|
256 | },
|
257 | e: function (e) {
|
258 | didErr = true;
|
259 | err = e;
|
260 | },
|
261 | f: function () {
|
262 | try {
|
263 | if (!normalCompletion && it.return != null) it.return();
|
264 | } finally {
|
265 | if (didErr) throw err;
|
266 | }
|
267 | }
|
268 | };
|
269 | }
|
270 |
|
271 | var CepPromiseError = function (_Error) {
|
272 | _inherits(CepPromiseError, _Error);
|
273 |
|
274 | var _super = _createSuper(CepPromiseError);
|
275 |
|
276 | function CepPromiseError() {
|
277 | var _this;
|
278 |
|
279 | var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
|
280 | message = _ref.message,
|
281 | type = _ref.type,
|
282 | errors = _ref.errors;
|
283 |
|
284 | _classCallCheck(this, CepPromiseError);
|
285 |
|
286 | _this = _super.call(this);
|
287 | _this.name = 'CepPromiseError';
|
288 | _this.message = message;
|
289 | _this.type = type;
|
290 | _this.errors = errors;
|
291 | return _this;
|
292 | }
|
293 |
|
294 | return _createClass(CepPromiseError);
|
295 | }( _wrapNativeSuper(Error));
|
296 |
|
297 | function fetch (e, n) {
|
298 | return n = n || {}, new Promise(function (t, r) {
|
299 | var s = new XMLHttpRequest(),
|
300 | o = [],
|
301 | u = [],
|
302 | i = {},
|
303 | a = function a() {
|
304 | return {
|
305 | ok: 2 == (s.status / 100 | 0),
|
306 | statusText: s.statusText,
|
307 | status: s.status,
|
308 | url: s.responseURL,
|
309 | text: function text() {
|
310 | return Promise.resolve(s.responseText);
|
311 | },
|
312 | json: function json() {
|
313 | return Promise.resolve(JSON.parse(s.responseText));
|
314 | },
|
315 | blob: function blob() {
|
316 | return Promise.resolve(new Blob([s.response]));
|
317 | },
|
318 | clone: a,
|
319 | headers: {
|
320 | keys: function keys() {
|
321 | return o;
|
322 | },
|
323 | entries: function entries() {
|
324 | return u;
|
325 | },
|
326 | get: function get(e) {
|
327 | return i[e.toLowerCase()];
|
328 | },
|
329 | has: function has(e) {
|
330 | return e.toLowerCase() in i;
|
331 | }
|
332 | }
|
333 | };
|
334 | };
|
335 |
|
336 | for (var l in s.open(n.method || "get", e, !0), s.onload = function () {
|
337 | s.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm, function (e, n, t) {
|
338 | o.push(n = n.toLowerCase()), u.push([n, t]), i[n] = i[n] ? i[n] + "," + t : t;
|
339 | }), t(a());
|
340 | }, s.onerror = r, s.withCredentials = "include" == n.credentials, n.headers) {
|
341 | s.setRequestHeader(l, n.headers[l]);
|
342 | }
|
343 |
|
344 | s.send(n.body || null);
|
345 | });
|
346 | }
|
347 |
|
348 | var ServiceError = function (_Error) {
|
349 | _inherits(ServiceError, _Error);
|
350 |
|
351 | var _super = _createSuper(ServiceError);
|
352 |
|
353 | function ServiceError() {
|
354 | var _this;
|
355 |
|
356 | var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
|
357 | message = _ref.message,
|
358 | service = _ref.service;
|
359 |
|
360 | _classCallCheck(this, ServiceError);
|
361 |
|
362 | _this = _super.call(this);
|
363 | _this.name = 'ServiceError';
|
364 | _this.message = message;
|
365 | _this.service = service;
|
366 | return _this;
|
367 | }
|
368 |
|
369 | return _createClass(ServiceError);
|
370 | }( _wrapNativeSuper(Error));
|
371 |
|
372 | function fetchCorreiosService(cepWithLeftPad, configurations) {
|
373 | var url = 'https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente';
|
374 | var options = {
|
375 | method: 'POST',
|
376 | body: "<?xml version=\"1.0\"?>\n<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cli=\"http://cliente.bean.master.sigep.bsb.correios.com.br/\">\n <soapenv:Header />\n <soapenv:Body>\n <cli:consultaCEP>\n <cep>".concat(cepWithLeftPad, "</cep>\n </cli:consultaCEP>\n </soapenv:Body>\n</soapenv:Envelope>"),
|
377 | headers: {
|
378 | 'Content-Type': 'text/xml;charset=UTF-8',
|
379 | 'cache-control': 'no-cache'
|
380 | },
|
381 | timeout: configurations.timeout || 30000
|
382 | };
|
383 | return fetch(url, options).then(analyzeAndParseResponse)["catch"](throwApplicationError);
|
384 | }
|
385 |
|
386 | function analyzeAndParseResponse(response) {
|
387 | if (response.ok) {
|
388 | return response.text().then(parseSuccessXML).then(extractValuesFromSuccessResponse);
|
389 | }
|
390 |
|
391 | return response.text().then(parseAndextractErrorMessage).then(throwCorreiosError);
|
392 | }
|
393 |
|
394 | function parseSuccessXML(xmlString) {
|
395 | try {
|
396 | var _xmlString$replace$ma;
|
397 |
|
398 | var returnStatement = (_xmlString$replace$ma = xmlString.replace(/\r?\n|\r/g, '').match(/<return>(.*)<\/return>/)[0]) !== null && _xmlString$replace$ma !== void 0 ? _xmlString$replace$ma : '';
|
399 | var cleanReturnStatement = returnStatement.replace('<return>', '').replace('</return>', '');
|
400 | var parsedReturnStatement = cleanReturnStatement.split(/</).reduce(function (result, exp) {
|
401 | var splittenExp = exp.split('>');
|
402 |
|
403 | if (splittenExp.length > 1 && splittenExp[1].length) {
|
404 | result[splittenExp[0]] = splittenExp[1];
|
405 | }
|
406 |
|
407 | return result;
|
408 | }, {});
|
409 | return parsedReturnStatement;
|
410 | } catch (e) {
|
411 | throw new Error('Não foi possível interpretar o XML de resposta.');
|
412 | }
|
413 | }
|
414 |
|
415 | function parseAndextractErrorMessage(xmlString) {
|
416 | try {
|
417 | var _xmlString$match$;
|
418 |
|
419 | var returnStatement = (_xmlString$match$ = xmlString.match(/<faultstring>(.*)<\/faultstring>/)[0]) !== null && _xmlString$match$ !== void 0 ? _xmlString$match$ : '';
|
420 | var cleanReturnStatement = returnStatement.replace('<faultstring>', '').replace('</faultstring>', '');
|
421 | return cleanReturnStatement;
|
422 | } catch (e) {
|
423 | throw new Error('Não foi possível interpretar o XML de resposta.');
|
424 | }
|
425 | }
|
426 |
|
427 | function throwCorreiosError(translatedErrorMessage) {
|
428 | throw new Error(translatedErrorMessage);
|
429 | }
|
430 |
|
431 | function extractValuesFromSuccessResponse(xmlObject) {
|
432 | return {
|
433 | cep: xmlObject.cep,
|
434 | state: xmlObject.uf,
|
435 | city: xmlObject.cidade,
|
436 | neighborhood: xmlObject.bairro,
|
437 | street: xmlObject.end,
|
438 | service: 'correios'
|
439 | };
|
440 | }
|
441 |
|
442 | function throwApplicationError(error) {
|
443 | var serviceError = new ServiceError({
|
444 | message: error.message,
|
445 | service: 'correios'
|
446 | });
|
447 |
|
448 | if (error.name === 'FetchError') {
|
449 | serviceError.message = 'Erro ao se conectar com o serviço dos Correios.';
|
450 | }
|
451 |
|
452 | throw serviceError;
|
453 | }
|
454 |
|
455 | function fetchViaCepService(cepWithLeftPad, configurations) {
|
456 | var url = "https://viacep.com.br/ws/".concat(cepWithLeftPad, "/json/");
|
457 | var options = {
|
458 | method: 'GET',
|
459 | mode: 'cors',
|
460 | headers: {
|
461 | 'content-type': 'application/json;charset=utf-8'
|
462 | },
|
463 | timeout: configurations.timeout || 30000
|
464 | };
|
465 |
|
466 | if (typeof window == 'undefined') {
|
467 | options.headers['user-agent'] = 'cep-promise';
|
468 | }
|
469 |
|
470 | return fetch(url, options).then(analyzeAndParseResponse$1).then(checkForViaCepError).then(extractCepValuesFromResponse)["catch"](throwApplicationError$1);
|
471 | }
|
472 |
|
473 | function analyzeAndParseResponse$1(response) {
|
474 | if (response.ok) {
|
475 | return response.json();
|
476 | }
|
477 |
|
478 | throw Error('Erro ao se conectar com o serviço ViaCEP.');
|
479 | }
|
480 |
|
481 | function checkForViaCepError(responseObject) {
|
482 | if (responseObject.erro === true) {
|
483 | throw new Error('CEP não encontrado na base do ViaCEP.');
|
484 | }
|
485 |
|
486 | return responseObject;
|
487 | }
|
488 |
|
489 | function extractCepValuesFromResponse(responseObject) {
|
490 | return {
|
491 | cep: responseObject.cep.replace('-', ''),
|
492 | state: responseObject.uf,
|
493 | city: responseObject.localidade,
|
494 | neighborhood: responseObject.bairro,
|
495 | street: responseObject.logradouro,
|
496 | service: 'viacep'
|
497 | };
|
498 | }
|
499 |
|
500 | function throwApplicationError$1(error) {
|
501 | var serviceError = new ServiceError({
|
502 | message: error.message,
|
503 | service: 'viacep'
|
504 | });
|
505 |
|
506 | if (error.name === 'FetchError') {
|
507 | serviceError.message = 'Erro ao se conectar com o serviço ViaCEP.';
|
508 | }
|
509 |
|
510 | throw serviceError;
|
511 | }
|
512 |
|
513 | function fetchWideNetService(cepWithLeftPad, configurations) {
|
514 | var url = "https://ws.apicep.com/busca-cep/api/cep/".concat(cepWithLeftPad, ".json");
|
515 | var options = {
|
516 | method: 'GET',
|
517 | mode: 'cors',
|
518 | headers: {
|
519 | 'content-type': 'application/json;charset=utf-8'
|
520 | },
|
521 | timeout: configurations.timeout || 30000
|
522 | };
|
523 | return fetch(url, options).then(analyzeAndParseResponse$2).then(checkForWideNetError).then(extractCepValuesFromResponse$1)["catch"](throwApplicationError$2);
|
524 | }
|
525 |
|
526 | function analyzeAndParseResponse$2(response) {
|
527 | if (response.ok) {
|
528 | return response.json();
|
529 | }
|
530 |
|
531 | throw Error('Erro ao se conectar com o serviço WideNet.');
|
532 | }
|
533 |
|
534 | function checkForWideNetError(object) {
|
535 | if (object.ok === false || object.status !== 200) {
|
536 | throw new Error('CEP não encontrado na base do WideNet.');
|
537 | }
|
538 |
|
539 | return object;
|
540 | }
|
541 |
|
542 | function extractCepValuesFromResponse$1(object) {
|
543 | return {
|
544 | cep: object.code.replace('-', ''),
|
545 | state: object.state,
|
546 | city: object.city,
|
547 | neighborhood: object.district,
|
548 | street: object.address,
|
549 | service: 'widenet'
|
550 | };
|
551 | }
|
552 |
|
553 | function throwApplicationError$2(error) {
|
554 | var serviceError = new ServiceError({
|
555 | message: error.message,
|
556 | service: 'widenet'
|
557 | });
|
558 |
|
559 | if (error.name === 'FetchError') {
|
560 | serviceError.message = 'Erro ao se conectar com o serviço WideNet.';
|
561 | }
|
562 |
|
563 | throw serviceError;
|
564 | }
|
565 |
|
566 | function fetchBrasilAPIService(cepWithLeftPad, configurations) {
|
567 | var url = "https://brasilapi.com.br/api/cep/v1/".concat(cepWithLeftPad);
|
568 | var options = {
|
569 | method: 'GET',
|
570 | mode: 'cors',
|
571 | headers: {
|
572 | 'content-type': 'application/json;charset=utf-8'
|
573 | },
|
574 | timeout: configurations.timeout || 30000
|
575 | };
|
576 | return fetch(url, options).then(parseResponse).then(extractCepValuesFromResponse$2)["catch"](throwApplicationError$3);
|
577 | }
|
578 |
|
579 | function parseResponse(response) {
|
580 | if (response.ok === false || response.status !== 200) {
|
581 | throw new Error('CEP não encontrado na base do BrasilAPI.');
|
582 | }
|
583 |
|
584 | return response.json();
|
585 | }
|
586 |
|
587 | function extractCepValuesFromResponse$2(response) {
|
588 | return {
|
589 | cep: response.cep,
|
590 | state: response.state,
|
591 | city: response.city,
|
592 | neighborhood: response.neighborhood,
|
593 | street: response.street,
|
594 | service: 'brasilapi'
|
595 | };
|
596 | }
|
597 |
|
598 | function throwApplicationError$3(error) {
|
599 | var serviceError = new ServiceError({
|
600 | message: error.message,
|
601 | service: 'brasilapi'
|
602 | });
|
603 |
|
604 | if (error.name === 'FetchError') {
|
605 | serviceError.message = 'Erro ao se conectar com o serviço BrasilAPI.';
|
606 | }
|
607 |
|
608 | throw serviceError;
|
609 | }
|
610 |
|
611 | function getAvailableServices() {
|
612 | var isBrowser = typeof window !== 'undefined';
|
613 |
|
614 | if (isBrowser) {
|
615 | return {
|
616 | viacep: fetchViaCepService,
|
617 | widenet: fetchWideNetService,
|
618 | brasilapi: fetchBrasilAPIService
|
619 | };
|
620 | }
|
621 |
|
622 | return {
|
623 | correios: fetchCorreiosService,
|
624 | viacep: fetchViaCepService,
|
625 | widenet: fetchWideNetService,
|
626 | brasilapi: fetchBrasilAPIService
|
627 | };
|
628 | }
|
629 |
|
630 | var reverse = function reverse(promise) {
|
631 | return new Promise(function (resolve, reject) {
|
632 | return Promise.resolve(promise).then(reject, resolve);
|
633 | });
|
634 | };
|
635 |
|
636 | Promise.any = function (iterable) {
|
637 | return reverse(Promise.all(_toConsumableArray(iterable).map(reverse)));
|
638 | };
|
639 |
|
640 | var Promise$1 = Promise;
|
641 |
|
642 | var CEP_SIZE = 8;
|
643 | function cepPromise (cepRawValue) {
|
644 | var configurations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
|
645 | return Promise$1.resolve(cepRawValue).then(validateInputType).then(function (cepRawValue) {
|
646 | configurations.providers = configurations.providers ? configurations.providers : [];
|
647 | validateProviders(configurations.providers);
|
648 | return cepRawValue;
|
649 | }).then(removeSpecialCharacters).then(validateInputLength).then(leftPadWithZeros).then(function (cepWithLeftPad) {
|
650 | return fetchCepFromServices(cepWithLeftPad, configurations);
|
651 | })["catch"](handleServicesError)["catch"](throwApplicationError$4);
|
652 | }
|
653 |
|
654 | function validateProviders(providers) {
|
655 | var availableProviders = Object.keys(getAvailableServices());
|
656 |
|
657 | if (!Array.isArray(providers)) {
|
658 | throw new CepPromiseError({
|
659 | message: 'Erro ao inicializar a instância do CepPromise.',
|
660 | type: 'validation_error',
|
661 | errors: [{
|
662 | message: 'O parâmetro providers deve ser uma lista.',
|
663 | service: 'providers_validation'
|
664 | }]
|
665 | });
|
666 | }
|
667 |
|
668 | var _iterator = _createForOfIteratorHelper(providers),
|
669 | _step;
|
670 |
|
671 | try {
|
672 | for (_iterator.s(); !(_step = _iterator.n()).done;) {
|
673 | var provider = _step.value;
|
674 |
|
675 | if (!availableProviders.includes(provider)) {
|
676 | throw new CepPromiseError({
|
677 | message: 'Erro ao inicializar a instância do CepPromise.',
|
678 | type: 'validation_error',
|
679 | errors: [{
|
680 | message: "O provider \"".concat(provider, "\" \xE9 inv\xE1lido. Os providers dispon\xEDveis s\xE3o: [\"").concat(availableProviders.join('", "'), "\"]."),
|
681 | service: 'providers_validation'
|
682 | }]
|
683 | });
|
684 | }
|
685 | }
|
686 | } catch (err) {
|
687 | _iterator.e(err);
|
688 | } finally {
|
689 | _iterator.f();
|
690 | }
|
691 | }
|
692 |
|
693 | function validateInputType(cepRawValue) {
|
694 | var cepTypeOf = _typeof(cepRawValue);
|
695 |
|
696 | if (cepTypeOf === 'number' || cepTypeOf === 'string') {
|
697 | return cepRawValue;
|
698 | }
|
699 |
|
700 | throw new CepPromiseError({
|
701 | message: 'Erro ao inicializar a instância do CepPromise.',
|
702 | type: 'validation_error',
|
703 | errors: [{
|
704 | message: 'Você deve chamar o construtor utilizando uma String ou um Number.',
|
705 | service: 'cep_validation'
|
706 | }]
|
707 | });
|
708 | }
|
709 |
|
710 | function removeSpecialCharacters(cepRawValue) {
|
711 | return cepRawValue.toString().replace(/\D+/g, '');
|
712 | }
|
713 |
|
714 | function leftPadWithZeros(cepCleanValue) {
|
715 | return '0'.repeat(CEP_SIZE - cepCleanValue.length) + cepCleanValue;
|
716 | }
|
717 |
|
718 | function validateInputLength(cepWithLeftPad) {
|
719 | if (cepWithLeftPad.length <= CEP_SIZE) {
|
720 | return cepWithLeftPad;
|
721 | }
|
722 |
|
723 | throw new CepPromiseError({
|
724 | message: "CEP deve conter exatamente ".concat(CEP_SIZE, " caracteres."),
|
725 | type: 'validation_error',
|
726 | errors: [{
|
727 | message: "CEP informado possui mais do que ".concat(CEP_SIZE, " caracteres."),
|
728 | service: 'cep_validation'
|
729 | }]
|
730 | });
|
731 | }
|
732 |
|
733 | function fetchCepFromServices(cepWithLeftPad, configurations) {
|
734 | var providersServices = getAvailableServices();
|
735 |
|
736 | if (configurations.providers.length === 0) {
|
737 | return Promise$1.any(Object.values(providersServices).map(function (provider) {
|
738 | return provider(cepWithLeftPad, configurations);
|
739 | }));
|
740 | }
|
741 |
|
742 | return Promise$1.any(configurations.providers.map(function (provider) {
|
743 | return providersServices[provider](cepWithLeftPad, configurations);
|
744 | }));
|
745 | }
|
746 |
|
747 | function handleServicesError(aggregatedErrors) {
|
748 | if (aggregatedErrors.length !== undefined) {
|
749 | throw new CepPromiseError({
|
750 | message: 'Todos os serviços de CEP retornaram erro.',
|
751 | type: 'service_error',
|
752 | errors: aggregatedErrors
|
753 | });
|
754 | }
|
755 |
|
756 | throw aggregatedErrors;
|
757 | }
|
758 |
|
759 | function throwApplicationError$4(_ref) {
|
760 | var message = _ref.message,
|
761 | type = _ref.type,
|
762 | errors = _ref.errors;
|
763 | throw new CepPromiseError({
|
764 | message: message,
|
765 | type: type,
|
766 | errors: errors
|
767 | });
|
768 | }
|
769 |
|
770 | return cepPromise;
|
771 |
|
772 | })));
|