1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
|
/**
* Drop-in address autofill for Brazilian checkouts, on top of the public CEP
* API at cep.is.
*
* The shopper types a CEP; the widget fills the street, neighbourhood, city and
* state fields you point it at. Field mapping is configuration: nothing about
* any particular e-commerce platform is baked in.
*
* @module
*/
/** Version of this widget. */
export const VERSION = "0.2.0";
const DEFAULT_BASE_URL = "https://cep.is";
const DEFAULT_DEBOUNCE_MS = 250;
const DEFAULT_TIMEOUT_MS = 8000;
const NOT_DIGIT = /\D+/g;
const DIACRITIC = /[\u0300-\u036f]/g;
const EIGHT_DIGITS = /^\d{8}$/;
const PLACEHOLDER = /\{(localidade|uf|cep_ini|cep_fim)\}/g;
const ADDRESS_FIELDS = [
"cep",
"logradouro",
"complemento",
"unidade",
"bairro",
"localidade",
"uf",
"estado",
"regiao",
"ibge",
"gia",
"ddd",
"siafi",
];
/**
* The message shown for each state, in Portuguese. Override any of them
* through the `messages` option of {@link attach}.
*
* `not_found_city` and `not_found_city_range` are not states of their own:
* they are the wording used for the `not_found` state when the API tells us
* which municipality the CEP would have belonged to. `{localidade}`, `{uf}`,
* `{cep_ini}` and `{cep_fim}` are filled in; the two CEPs are masked. Whenever
* that information is missing, plain `not_found` is used instead.
*/
export const MESSAGES = {
idle: "",
loading: "Buscando endereço…",
found: "Endereço encontrado.",
not_found: "CEP não encontrado. Confira o número ou preencha o endereço manualmente.",
not_found_city: "CEP não encontrado. Esse número seria de {localidade}/{uf}.",
not_found_city_range:
"CEP não encontrado. Esse número seria de {localidade}/{uf}, que tem CEPs de {cep_ini} a {cep_fim}.",
invalid: "CEP inválido. Digite os 8 dígitos.",
rate_limited: "Muitas consultas em pouco tempo. Aguarde alguns segundos e tente de novo.",
server: "O serviço de CEP está indisponível. Preencha o endereço manualmente.",
network: "Não foi possível consultar o CEP. Verifique sua conexão e tente de novo.",
timeout: "A consulta do CEP demorou demais. Tente de novo ou preencha manualmente.",
invalid_response: "Resposta inesperada do serviço de CEP. Preencha o endereço manualmente.",
};
/**
* Everything this widget throws or hands to `onError`.
*
* `code` is what you branch on. It is the decision, not the HTTP status:
*
* | code | when | worth retrying? |
* | --- | --- | --- |
* | `invalid` | not 8 digits, or the API rejected the format | no |
* | `not_found` | well-formed, absent from the DNE database | no |
* | `rate_limited` | 429; `retryAfterMs` carries what the server asked for | later |
* | `server` | 5xx; `status` carries the code | later |
* | `network` | DNS, refused connection, TLS, offline | later |
* | `timeout` | the request outlived `timeoutMs` | later |
* | `invalid_response` | a success status with an unreadable body | probably not |
* | `aborted` | superseded by a newer keystroke; never surfaced to the shopper | no |
*
* A `not_found` may carry `faixa`: the municipality the CEP would have
* belonged to. See {@link CepisAutofillError#faixa}.
*/
export class CepisAutofillError extends Error {
/**
* @param {string} code One of the codes in the table above.
* @param {string} message Human message, in Portuguese.
* @param {{status?: number, retryAfterMs?: number, cep?: string, faixa?: Record<string, any>, cause?: unknown}} [details]
*/
constructor(code, message, details = {}) {
super(message, details.cause === undefined ? undefined : { cause: details.cause });
this.name = "CepisAutofillError";
this.code = code;
this.status = details.status;
this.retryAfterMs = details.retryAfterMs;
this.cep = details.cep;
/**
* On a `not_found`, the municipality whose CEP range brackets the number
* asked for — `{localidade, uf}` plus whichever of `estado`, `regiao`,
* `ibge`, `cep_ini`, `cep_fim` and `ceps` the API sent. Absent whenever
* the CEP falls outside every municipality, or the API said nothing
* usable.
*
* **This is context for a failure, not an address.** The CEP asked for
* does not exist, so neither does the address it would have had: the
* widget never writes any of this into a form field, and neither should
* you. `cep_ini` and `cep_fim` are the lowest and highest CEP that really
* exist in that municipality, not a contiguous run — Areal/RJ has 118 of
* them spread over some 4,900 numbers — so they are worth showing as a
* hint of where the right CEP lies, never as a list to pick from.
*
* @type {Record<string, any>|undefined}
*/
this.faixa = details.faixa;
}
}
/**
* Return the CEP's 8 digits, accepting the `01001-000` mask.
*
* @param {string} value Anything the shopper typed.
* @returns {string} The 8 digits.
* @throws {CepisAutofillError} code `invalid`, when 8 digits do not remain.
*/
export function normalizeCep(value) {
const digits = String(value == null ? "" : value).replace(NOT_DIGIT, "");
if (digits.length !== 8) {
throw new CepisAutofillError("invalid", MESSAGES.invalid, { cep: digits });
}
return digits;
}
const cache = new Map();
/** Drop every cached lookup. Rarely needed: the cache dies with the page. */
export function clearCache() {
cache.clear();
}
function retryAfterMs(header) {
if (!header) {
return undefined;
}
const value = header.trim();
if (/^\d+$/.test(value)) {
return Number(value) * 1000;
}
const target = Date.parse(value);
return Number.isNaN(target) ? undefined : Math.max(0, target - Date.now());
}
function trimmed(value) {
return typeof value === "string" ? value.trim() : "";
}
function maskCep(digits) {
return `${digits.slice(0, 5)}-${digits.slice(5)}`;
}
/**
* Read the `faixa` a 404 may carry: the municipality the CEP would have
* belonged to, had it existed.
*
* Every field is optional and none is trusted. A body that is not JSON, a
* `faixa` that is not an object, a missing `localidade` or `uf` — all of it
* yields `undefined`, and the caller falls back to the plain "não encontrado".
* This never throws.
*
* @param {string} body The raw 404 body.
* @returns {Record<string, any>|undefined}
*/
function parseFaixa(body) {
let data;
try {
data = JSON.parse(body);
} catch {
return undefined;
}
const raw = data && typeof data === "object" ? data.faixa : undefined;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
return undefined;
}
const localidade = trimmed(raw.localidade);
const uf = trimmed(raw.uf);
if (localidade === "" || uf === "") {
return undefined;
}
const faixa = { localidade, uf };
for (const field of ["estado", "regiao", "ibge"]) {
const value = trimmed(raw[field]);
if (value !== "") {
faixa[field] = value;
}
}
const ini = trimmed(raw.cep_ini);
const fim = trimmed(raw.cep_fim);
if (EIGHT_DIGITS.test(ini) && EIGHT_DIGITS.test(fim)) {
faixa.cep_ini = ini;
faixa.cep_fim = fim;
}
if (typeof raw.ceps === "number" && Number.isFinite(raw.ceps)) {
faixa.ceps = raw.ceps;
}
return faixa;
}
/**
* Word the `not_found` state, naming the municipality when we know it.
*
* @param {Record<string, any>|undefined} faixa From {@link parseFaixa}.
* @param {Record<string, string>} messages The message table in force.
* @returns {string}
*/
function notFoundMessage(faixa, messages) {
if (!faixa) {
return messages.not_found;
}
const template = faixa.cep_ini ? messages.not_found_city_range : messages.not_found_city;
if (typeof template !== "string" || template === "") {
return messages.not_found;
}
return template.replace(PLACEHOLDER, (_, key) => {
const value = faixa[key];
if (typeof value !== "string") {
return "";
}
return key === "cep_ini" || key === "cep_fim" ? maskCep(value) : value;
});
}
function apiMessage(body, fallback) {
try {
const data = JSON.parse(body);
if (data && typeof data.mensagem === "string" && data.mensagem !== "") {
return data.mensagem;
}
} catch {
return fallback;
}
return fallback;
}
/**
* Look up one CEP on the API.
*
* Successful answers and "does not exist" are cached in memory for the life of
* the page, keyed by CEP and base URL; transient failures are not. Callers get
* the address object exactly as the API returns it — Portuguese field names,
* empty strings rather than nulls, and `geo` present only for the CEPs that
* have a coordinate.
*
* A `not_found` may carry a `faixa` naming the municipality the CEP would have
* belonged to — context for the failure, never an address to fill in.
*
* @param {string} cep Masked or unmasked.
* @param {{baseUrl?: string, timeoutMs?: number, signal?: AbortSignal}} [options]
* @returns {Promise<Record<string, any>>} The address.
* @throws {CepisAutofillError} See the table on {@link CepisAutofillError}.
*/
export async function lookup(cep, options = {}) {
const digits = normalizeCep(cep);
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
const key = `${baseUrl}|${digits}`;
const hit = cache.get(key);
if (hit) {
if (hit.address) {
return hit.address;
}
throw new CepisAutofillError(hit.code, hit.message, { cep: digits, faixa: hit.faixa });
}
const controller = new AbortController();
const forward = () => controller.abort();
if (options.signal) {
if (options.signal.aborted) {
throw new CepisAutofillError("aborted", "consulta cancelada", { cep: digits });
}
options.signal.addEventListener("abort", forward);
}
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
controller.abort();
}, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
let response;
let body;
try {
response = await fetch(`${baseUrl}/${digits}`, {
method: "GET",
credentials: "omit",
headers: { Accept: "application/json" },
signal: controller.signal,
});
body = await response.text();
} catch (error) {
if (timedOut) {
throw new CepisAutofillError("timeout", MESSAGES.timeout, { cep: digits, cause: error });
}
if (controller.signal.aborted) {
throw new CepisAutofillError("aborted", "consulta cancelada", { cep: digits });
}
throw new CepisAutofillError("network", MESSAGES.network, { cep: digits, cause: error });
} finally {
clearTimeout(timer);
if (options.signal) {
options.signal.removeEventListener("abort", forward);
}
}
if (response.status === 404) {
// A 404 may name the municipality the CEP would have belonged to. It stays
// an error: the address does not exist, so nothing here is ever filled in.
const faixa = parseFaixa(body);
const message = notFoundMessage(faixa, MESSAGES);
cache.set(key, { code: "not_found", message, faixa });
throw new CepisAutofillError("not_found", message, { cep: digits, faixa });
}
if (response.status === 400) {
throw new CepisAutofillError("invalid", apiMessage(body, MESSAGES.invalid), { cep: digits });
}
if (response.status === 429) {
throw new CepisAutofillError("rate_limited", MESSAGES.rate_limited, {
cep: digits,
retryAfterMs: retryAfterMs(response.headers.get("Retry-After")),
});
}
if (response.status >= 500) {
throw new CepisAutofillError("server", MESSAGES.server, {
cep: digits,
status: response.status,
});
}
if (!response.ok) {
throw new CepisAutofillError("invalid_response", MESSAGES.invalid_response, {
cep: digits,
status: response.status,
});
}
let address;
try {
address = JSON.parse(body);
} catch (error) {
throw new CepisAutofillError("invalid_response", MESSAGES.invalid_response, {
cep: digits,
cause: error,
});
}
if (!address || typeof address !== "object" || Array.isArray(address)) {
throw new CepisAutofillError("invalid_response", MESSAGES.invalid_response, { cep: digits });
}
cache.set(key, { address });
return address;
}
function resolve(target) {
if (!target) {
return null;
}
if (typeof target === "string") {
return document.querySelector(target);
}
return target.nodeType === 1 ? target : null;
}
function fold(value) {
return String(value ?? "")
.normalize("NFD")
.replace(DIACRITIC, "")
.trim()
.toLowerCase();
}
function assign(element, value) {
const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(element), "value");
if (setter && setter.set) {
setter.set.call(element, value);
} else {
element.value = value;
}
element.dispatchEvent(new Event("input", { bubbles: true }));
element.dispatchEvent(new Event("change", { bubbles: true }));
}
function selectOption(element, candidates) {
const wanted = candidates.filter(Boolean).map(fold);
for (const option of Array.from(element.options)) {
if (wanted.includes(fold(option.value)) || wanted.includes(fold(option.textContent))) {
assign(element, option.value);
return option.value;
}
}
return null;
}
function writable(element, mode, written) {
const current = String(element.value ?? "");
if (mode === true) {
return true;
}
if (current.trim() === "") {
return true;
}
if (mode === false) {
return false;
}
return written.get(element) === current;
}
let regionCount = 0;
/**
* Attach the widget to a form.
*
* Every selector accepts a CSS string or an element. Strings are resolved on
* every use and the CEP listener is delegated from `document`, so a checkout
* that re-renders its form keeps working; elements are held directly and stop
* working if that node is replaced.
*
* ```js
* const handle = CepisAutofill.attach({
* cep: "#billing_postcode",
* logradouro: "#billing_address_1",
* bairro: "#billing_neighborhood",
* localidade: "#billing_city",
* uf: "#billing_state",
* numero: "#billing_number",
* });
* ```
*
* @param {object} options
* @param {string|Element} options.cep The field the shopper types into. Required.
* @param {string|Element} [options.logradouro] Street field.
* @param {string|Element} [options.complemento] Complement field.
* @param {string|Element} [options.unidade] Unit field.
* @param {string|Element} [options.bairro] Neighbourhood field.
* @param {string|Element} [options.localidade] City field.
* @param {string|Element} [options.uf] State field. A `<select>` is matched by
* option value or label, against both the two-letter UF and the state name.
* @param {string|Element} [options.estado] State-name field.
* @param {string|Element} [options.regiao] Region field.
* @param {string|Element} [options.ibge] IBGE code field.
* @param {string|Element} [options.gia] GIA code field.
* @param {string|Element} [options.ddd] Area code field.
* @param {string|Element} [options.siafi] SIAFI code field.
* @param {string|Element} [options.numero] House-number field. Never written
* to — only used by `focusNumero`.
* @param {string} [options.baseUrl] API root. Default `https://cep.is`; point
* it at a local instance to test.
* @param {number} [options.debounceMs] Quiet period after the last keystroke
* before a request goes out. Default `250`.
* @param {number} [options.timeoutMs] Deadline for one request. Default `8000`.
* @param {boolean|"auto"} [options.overwrite] What to do with a field that
* already has a value. `"auto"` (default) replaces empty fields and values
* this widget wrote itself, and leaves anything the shopper typed alone;
* `false` only ever fills empty fields; `true` always overwrites.
* @param {boolean} [options.focusNumero] Move focus to the `numero` field
* after a successful lookup, and only while the CEP field still has focus.
* Default `false`.
* @param {string|Element|false} [options.status] Where to announce progress.
* Omit to have an `aria-live` region created right after the CEP field, pass
* a selector or element to use your own, or `false` to render nothing and
* drive your own UI from `onStatus`.
* @param {Record<string, string>} [options.messages] Overrides for
* {@link MESSAGES}.
* @param {(address: Record<string, any>, context: {cep: string}) => void} [options.onResult]
* Called after a successful lookup, once the fields are filled.
* @param {(error: CepisAutofillError, context: {cep: string}) => void} [options.onError]
* Called for every failure the shopper sees. Never called for `aborted`. A
* `not_found` may carry `error.faixa`; see {@link CepisAutofillError#faixa}
* for why it must not be filled into the form.
* @param {(state: string, message: string) => void} [options.onStatus] Called
* on every state change: `idle`, `loading`, `found`, or an error code.
* @returns {{detach: () => void, lookup: (cep?: string) => Promise<Record<string, any>|null>, element: () => Element|null}}
* `detach()` removes every listener, aborts anything in flight and removes a
* status region it created. `lookup()` runs the whole pipeline immediately,
* skipping the debounce, for checkouts that fill the CEP field without
* firing events.
*/
export function attach(options) {
if (!options || !options.cep) {
throw new TypeError("attach() needs a `cep` selector or element");
}
const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const overwrite = options.overwrite ?? "auto";
const messages = { ...MESSAGES, ...(options.messages ?? {}) };
const written = new WeakMap();
const state = {
seq: 0,
timer: 0,
controller: null,
region: null,
describedBy: false,
detached: false,
};
const source = () => resolve(options.cep);
function region() {
if (options.status === false) {
return null;
}
if (state.region && state.region.isConnected) {
return state.region;
}
if (options.status) {
state.region = resolve(options.status);
} else {
const anchor = source();
if (!anchor) {
return null;
}
const node = document.createElement("div");
node.className = "cepis-autofill-status";
node.style.minHeight = "1.25em";
anchor.insertAdjacentElement("afterend", node);
state.region = node;
}
const node = state.region;
if (!node) {
return null;
}
node.setAttribute("role", "status");
node.setAttribute("aria-live", "polite");
node.setAttribute("aria-atomic", "true");
if (!node.id) {
regionCount += 1;
node.id = `cepis-autofill-status-${regionCount}`;
}
const anchor = source();
if (anchor && !(anchor.getAttribute("aria-describedby") ?? "").includes(node.id)) {
const previous = anchor.getAttribute("aria-describedby");
anchor.setAttribute("aria-describedby", previous ? `${previous} ${node.id}` : node.id);
state.describedBy = true;
}
return node;
}
function announce(kind, text) {
const message = text ?? messages[kind] ?? "";
const node = region();
if (node) {
node.setAttribute(
"data-cepis-state",
kind === "found" || kind === "loading" ? kind : kind === "idle" ? "idle" : "error",
);
node.textContent = message;
}
const anchor = source();
if (anchor) {
if (kind === "loading") {
anchor.setAttribute("aria-busy", "true");
} else {
anchor.removeAttribute("aria-busy");
}
anchor.setAttribute(
"aria-invalid",
kind === "invalid" || kind === "not_found" ? "true" : "false",
);
}
if (options.onStatus) {
options.onStatus(kind, message);
}
}
// Only ever called with an address the API confirmed exists. A `faixa` from a
// 404 must never reach it: naming the city of a CEP that does not exist is a
// hint for the shopper, and silently writing it into the form would be a
// wrong address.
function fill(address) {
for (const field of ADDRESS_FIELDS) {
if (field === "cep" || !options[field]) {
continue;
}
const element = resolve(options[field]);
const value = address[field];
if (!element || typeof value !== "string" || value === "") {
continue;
}
if (!writable(element, overwrite, written)) {
continue;
}
if (element.tagName === "SELECT") {
const chosen = selectOption(
element,
field === "uf"
? [value, address.estado]
: field === "estado"
? [value, address.uf]
: [value],
);
if (chosen !== null) {
written.set(element, element.value);
}
continue;
}
assign(element, value);
written.set(element, value);
}
}
async function run(digits) {
state.seq += 1;
const seq = state.seq;
if (state.controller) {
state.controller.abort();
}
const controller = new AbortController();
state.controller = controller;
announce("loading");
try {
const address = await lookup(digits, { baseUrl, timeoutMs, signal: controller.signal });
if (seq !== state.seq || state.detached) {
return null;
}
fill(address);
announce("found");
if (options.onResult) {
options.onResult(address, { cep: digits });
}
const numero = resolve(options.numero);
if (options.focusNumero && numero && document.activeElement === source()) {
numero.focus();
}
return address;
} catch (error) {
if (seq !== state.seq || state.detached || error.code === "aborted") {
return null;
}
const code = error instanceof CepisAutofillError ? error.code : "network";
// No field is touched on this path — a `not_found` only changes the
// wording of the message, never the form.
announce(code, code === "not_found" ? notFoundMessage(error.faixa, messages) : undefined);
if (options.onError) {
options.onError(error, { cep: digits });
}
return null;
} finally {
if (state.controller === controller) {
state.controller = null;
}
}
}
function handle(event) {
const target = event.target;
const matches =
typeof options.cep === "string"
? target && target.nodeType === 1 && target.matches(options.cep)
: target === options.cep;
if (!matches) {
return;
}
schedule(String(target.value ?? ""));
}
function schedule(value) {
clearTimeout(state.timer);
const digits = value.replace(NOT_DIGIT, "");
if (digits.length !== 8) {
state.seq += 1;
if (state.controller) {
state.controller.abort();
state.controller = null;
}
announce(digits.length > 8 ? "invalid" : "idle");
return;
}
state.timer = setTimeout(() => run(digits), debounceMs);
}
announce("idle");
document.addEventListener("input", handle, true);
document.addEventListener("change", handle, true);
return {
detach() {
state.detached = true;
state.seq += 1;
clearTimeout(state.timer);
if (state.controller) {
state.controller.abort();
state.controller = null;
}
document.removeEventListener("input", handle, true);
document.removeEventListener("change", handle, true);
const anchor = source();
if (anchor) {
anchor.removeAttribute("aria-busy");
anchor.removeAttribute("aria-invalid");
}
if (state.region && state.describedBy && anchor) {
const remaining = (anchor.getAttribute("aria-describedby") ?? "")
.split(/\s+/)
.filter((id) => id && id !== state.region.id)
.join(" ");
if (remaining) {
anchor.setAttribute("aria-describedby", remaining);
} else {
anchor.removeAttribute("aria-describedby");
}
}
if (state.region && !options.status) {
state.region.remove();
}
state.region = null;
},
lookup(cep) {
clearTimeout(state.timer);
const anchor = source();
const value = cep ?? (anchor ? anchor.value : "");
let digits;
try {
digits = normalizeCep(value);
} catch (error) {
announce("invalid");
if (options.onError) {
options.onError(error, { cep: String(value) });
}
return Promise.resolve(null);
}
return run(digits);
},
element: source,
};
}
export default { attach, lookup, normalizeCep, clearCache, CepisAutofillError, MESSAGES, VERSION };
|