@vtex/country-forms 0.0.1

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.
@@ -0,0 +1,833 @@
1
+ /**
2
+ * Supported form types within @vtex/country-forms.
3
+ *
4
+ * - `"address"` — delivery or billing address forms
5
+ * - `"personal-data"` — shopper identity forms (document, phone, email, etc.)
6
+ */
7
+ type FormType = 'address' | 'personal-data';
8
+ /**
9
+ * Supported field widget types. The consumer maps each type to a concrete UI component.
10
+ *
11
+ * - `"text"` — plain text input
12
+ * - `"email"` — e-mail text input
13
+ * - `"select"` — dropdown select
14
+ * - `"radio-group"` — radio button group
15
+ */
16
+ type FieldType = 'text' | 'email' | 'select' | 'radio-group';
17
+ /**
18
+ * HTML `inputmode` hint for virtual keyboard optimisation on mobile devices.
19
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode
20
+ */
21
+ type InputMode = 'text' | 'numeric' | 'tel' | 'email';
22
+ /**
23
+ * A single option for `select` and `radio-group` fields.
24
+ *
25
+ * Both `value` and `displayValue` may be plain strings or i18n keys.
26
+ * The consumer resolves display values through `resolveLabel` if needed.
27
+ */
28
+ interface SelectOption {
29
+ /** The raw value stored and submitted. */
30
+ value: string;
31
+ /** Human-readable label or i18n key shown to the user. */
32
+ displayValue: string;
33
+ }
34
+ /**
35
+ * Synchronous validation rules applied to a field.
36
+ *
37
+ * All `message` strings are i18n keys (e.g. `"country-forms.validation.required"`)
38
+ * and must be resolved by the consumer via `resolveLabel`.
39
+ *
40
+ * **No inline functions are allowed** — validators are referenced by name and resolved
41
+ * from the rules registry at runtime. This keeps schemas serializable (JSON-safe).
42
+ */
43
+ interface ValidationRules {
44
+ /** Minimum number of characters required. */
45
+ minLength?: {
46
+ value: number;
47
+ message: string;
48
+ };
49
+ /** Maximum number of characters allowed. */
50
+ maxLength?: {
51
+ value: number;
52
+ message: string;
53
+ };
54
+ /**
55
+ * Regex pattern the value must match.
56
+ * `value` is a serializable regex string without delimiters or flags
57
+ * (e.g. `"^\\d{5}-?\\d{3}$"`).
58
+ */
59
+ pattern?: {
60
+ value: string;
61
+ message: string;
62
+ };
63
+ /**
64
+ * Reference to a named validator function in the rules registry.
65
+ * The engine resolves this string to the concrete function at runtime.
66
+ * @example "validateCPF", "validateCNPJ", "validateCEP", "validateZIP", "validateEmail", "validatePhoneBRA"
67
+ */
68
+ customValidator?: string;
69
+ }
70
+ /**
71
+ * Operators available for {@link ConditionalVisibility} conditions.
72
+ *
73
+ * - `"equals"` / `"notEquals"` — strict equality against a single string value
74
+ * - `"includes"` / `"notIncludes"` — membership test against an array of strings
75
+ */
76
+ type ConditionalOperator = 'equals' | 'notEquals' | 'includes' | 'notIncludes';
77
+ /**
78
+ * Declarative visibility condition evaluated against the current form state.
79
+ *
80
+ * A field with `conditionalVisibility` is shown (and validated) only when this
81
+ * condition evaluates to `true`. Hidden fields are excluded from validation.
82
+ */
83
+ interface ConditionalVisibility {
84
+ /** Name of the sibling field whose current value drives this condition. */
85
+ field: string;
86
+ operator: ConditionalOperator;
87
+ /** The comparison value. Use an array with `"includes"` / `"notIncludes"`. */
88
+ value: string | string[];
89
+ }
90
+ /**
91
+ * A single field definition within a {@link FormSchema}.
92
+ *
93
+ * All fields are fully serializable — no inline functions are allowed.
94
+ * Validators, format/unformat functions, and option lists are referenced by name
95
+ * and resolved by the engine.
96
+ */
97
+ interface FieldDefinition {
98
+ /**
99
+ * Unique field identifier within the schema.
100
+ * Used as the key in form state and error maps.
101
+ * @example "postalCode", "street", "state", "cpf"
102
+ */
103
+ name: string;
104
+ /** Widget type. The consumer maps this to a concrete UI component. */
105
+ type: FieldType;
106
+ /**
107
+ * i18n key for the field label.
108
+ * Resolved by the consumer via `resolveLabel(field.label, bundle, overrides)`.
109
+ * @example "country-forms.address.street.label"
110
+ */
111
+ label: string;
112
+ /**
113
+ * i18n key for the field placeholder text.
114
+ * Resolved via `resolveLabel` by the consumer.
115
+ * @example "country-forms.address.postalCode.placeholder.BRA"
116
+ */
117
+ placeholder?: string;
118
+ /** Whether the field must have a non-empty value before form submission. */
119
+ required: boolean;
120
+ /** HTML `inputmode` hint for virtual keyboard optimisation on mobile. */
121
+ inputMode?: InputMode;
122
+ /**
123
+ * i18n key that overrides the visible `label` for screen readers.
124
+ * Use when the accessible name should differ from the visible label text.
125
+ * @example "country-forms.address.postalCode.ariaLabel"
126
+ */
127
+ ariaLabel?: string;
128
+ /**
129
+ * i18n key for a supplementary screen reader description, linked via `aria-describedby`.
130
+ * Useful for hint text or extended descriptions not shown visually.
131
+ * @example "country-forms.address.postalCode.ariaDescribedBy"
132
+ */
133
+ ariaDescribedBy?: string;
134
+ /**
135
+ * HTML `maxlength` attribute value for the input element.
136
+ * Limits the number of characters the user can type (including any
137
+ * separators introduced by `formatRef`).
138
+ * This is a **UI constraint** applied by the browser, independent of the
139
+ * `validation.maxLength` rule which runs at submit time.
140
+ * @example 9 // CEP with hyphen: "01310-100"
141
+ */
142
+ maxLength?: number;
143
+ /**
144
+ * Synchronous validation rules.
145
+ * All references — no inline functions.
146
+ */
147
+ validation?: ValidationRules;
148
+ /**
149
+ * Reference to a named format function in the masks registry.
150
+ * Used by `formatValue(field.formatRef, raw)` to produce the display string
151
+ * (e.g. `"01310100"` → `"01310-100"`). This **replaces** any declarative
152
+ * mask-pattern prop: the format function is the single source of truth for
153
+ * how the value is displayed.
154
+ * @example "formatCPF", "formatCEP", "formatPhoneBRA"
155
+ */
156
+ formatRef?: string;
157
+ /**
158
+ * Reference to a named unformat function in the masks registry.
159
+ * Used by `unformatValue(field.unformatRef, display)` to produce the raw/API
160
+ * value (e.g. `"01310-100"` → `"01310100"`).
161
+ * @example "unformatCPF", "unformatCEP", "unformatPhoneBRA"
162
+ */
163
+ unformatRef?: string;
164
+ /**
165
+ * Options for `"select"` and `"radio-group"` fields.
166
+ *
167
+ * May be:
168
+ * - An inline `SelectOption[]` array, or
169
+ * - A string reference resolved from the options registry at runtime
170
+ * (e.g. `"BRA.states"` → `SelectOption[]`).
171
+ */
172
+ options?: SelectOption[] | string;
173
+ /**
174
+ * Conditional options keyed by a controller field value.
175
+ * Used for dependent selects such as `state -> city`.
176
+ *
177
+ * Requires {@link FieldDefinition.dependsOn} to identify the controller field.
178
+ * When a matching key exists for the current controller value, it overrides
179
+ * {@link FieldDefinition.options} for option resolution.
180
+ *
181
+ * Values can be inline arrays or option refs from the registry.
182
+ *
183
+ * @example
184
+ * dependsOn: "state"
185
+ * conditionalOptions: {
186
+ * SP: "BRA.cities.SP",
187
+ * RJ: "BRA.cities.RJ",
188
+ * }
189
+ */
190
+ conditionalOptions?: Record<string, SelectOption[] | string>;
191
+ /**
192
+ * Declarative visibility condition.
193
+ * When present, the field is shown and validated only while the condition is `true`.
194
+ * Evaluated by `getVisibleFields(schema, state)`.
195
+ */
196
+ conditionalVisibility?: ConditionalVisibility;
197
+ /**
198
+ * Map from a controller field's value to an i18n label key for this field.
199
+ * Used when the label changes based on another field's selection.
200
+ * Requires {@link FieldDefinition.dependsOn} to identify the controller field.
201
+ *
202
+ * @example
203
+ * // Field "document" changes label depending on "personType"
204
+ * conditionalLabel: {
205
+ * individual: "country-forms.field.document.cpf.label",
206
+ * business: "country-forms.field.document.cnpj.label",
207
+ * }
208
+ */
209
+ conditionalLabel?: Record<string, string>;
210
+ /**
211
+ * Map from a controller field's value to an i18n placeholder key for this field.
212
+ * Same semantics as {@link FieldDefinition.conditionalLabel} but for the placeholder.
213
+ */
214
+ conditionalPlaceholder?: Record<string, string>;
215
+ /**
216
+ * Name of the sibling field that drives {@link FieldDefinition.conditionalLabel},
217
+ * {@link FieldDefinition.conditionalPlaceholder}, and
218
+ * {@link FieldDefinition.conditionalOptions}.
219
+ * Required when any of those properties is set.
220
+ * @example "personType", "state"
221
+ */
222
+ dependsOn?: string;
223
+ }
224
+ /**
225
+ * Top-level declarative form definition for a specific country and form type.
226
+ *
227
+ * Schemas are loaded on demand via `loadSchema(countryCode, formType)`.
228
+ * They are fully serializable — no inline functions.
229
+ *
230
+ * @example
231
+ * const schema: FormSchema = {
232
+ * id: "address-BRA",
233
+ * country: "BRA", // ISO 3166-1 alpha-3
234
+ * formType: "address",
235
+ * fields: [...],
236
+ * }
237
+ */
238
+ interface FormSchema {
239
+ /**
240
+ * Unique schema identifier. Convention: `"<formType>-<COUNTRY>"`.
241
+ * @example "address-BRA", "personal-data-USA"
242
+ */
243
+ id: string;
244
+ /**
245
+ * ISO 3166-1 **alpha-3** country code (3 uppercase letters).
246
+ *
247
+ * @example "BRA", "USA", "CAN", "MEX"
248
+ * @see https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3
249
+ */
250
+ country: string;
251
+ /**
252
+ * Form type. Determines the category of data collected:
253
+ * - `"address"` — delivery/billing address fields
254
+ * - `"personal-data"` — shopper identity fields (document, phone, email, etc.)
255
+ */
256
+ formType: FormType;
257
+ /** Ordered list of fields that make up this form. */
258
+ fields: FieldDefinition[];
259
+ }
260
+
261
+ /**
262
+ * @module types/engine
263
+ *
264
+ * Headless form state management — framework-agnostic, zero UI dependencies.
265
+ *
266
+ * ## Design: immutable state
267
+ *
268
+ * `FormState` is treated as an immutable value object. Every mutating operation
269
+ * (`setValue`) returns a **new** `FormState` instead of modifying the argument.
270
+ * This makes the state safe to use with any reactive system:
271
+ *
272
+ * - React: `const [state, setState] = useState(() => createFormState(schema))`
273
+ * - Svelte: `let state = createFormState(schema)` + `state = setValue(state, schema, ...)`
274
+ * - MobX / Zustand / vanilla: same pattern, store the returned reference
275
+ *
276
+ * The library never holds a reference to state internally — the consumer owns it.
277
+ *
278
+ * ## Error handling
279
+ *
280
+ * Errors (`FormErrors`) are populated by `validate(state, schema)`.
281
+ * `createFormState` initializes errors to an empty map; `setValue` preserves
282
+ * existing errors so the consumer can decide when to re-validate.
283
+ *
284
+ * Typical usage:
285
+ * ```typescript
286
+ * let state = createFormState(schema, existingValues)
287
+ *
288
+ * // On field change
289
+ * state = setValue(state, schema, 'postalCode', '01310-100')
290
+ *
291
+ * // On submit
292
+ * const errors = validate(state, schema)
293
+ * if (Object.keys(errors).length > 0) {
294
+ * state = { ...state, errors } // attach errors for rendering
295
+ * return
296
+ * }
297
+ * // Submit state.values to the application
298
+ * ```
299
+ */
300
+ /**
301
+ * Map of field name → current string value.
302
+ * Keys correspond to `FieldDefinition.name` values in the loaded `FormSchema`.
303
+ *
304
+ * All values are strings: formatted display values before `unformatValue`,
305
+ * or raw values when masks are not applied.
306
+ */
307
+ type FormValues = Record<string, string>;
308
+ /**
309
+ * Map of field name → i18n error key.
310
+ *
311
+ * An entry is present only when a field has a validation error.
312
+ * The value is an i18n key (e.g. `"country-forms.validation.required"`) resolved
313
+ * by the consumer via `resolveLabel`. An empty map means the form is error-free.
314
+ *
315
+ * This map is produced by `validate(state, schema)` and is separate from
316
+ * `FormState` so the consumer can decide whether and when to display errors.
317
+ */
318
+ type FormErrors = Record<string, string>;
319
+ /**
320
+ * Current state of a form instance, derived from a {@link FormSchema}.
321
+ *
322
+ * Treat as an immutable value: never mutate directly, always use `setValue`
323
+ * (or spread manually for error attachment).
324
+ *
325
+ * Created by `createFormState` and updated immutably by `setValue`.
326
+ * Each record is keyed by `FieldDefinition.name`.
327
+ *
328
+ * @example
329
+ * let state = createFormState(schema)
330
+ * state = setValue(state, schema, 'street', 'Av Paulista')
331
+ * // state.values.street === 'Av Paulista'
332
+ */
333
+ interface FormState {
334
+ /**
335
+ * Current field values keyed by field `name`.
336
+ * Initialized with empty strings for every field in the schema.
337
+ */
338
+ values: FormValues;
339
+ /**
340
+ * Sparse validation error map keyed by field `name`.
341
+ * Only fields with errors appear as keys; an empty object means the form is valid.
342
+ * Empty on initialization; populated by the consumer after calling `validate()`.
343
+ */
344
+ errors: FormErrors;
345
+ /** Whether each field has been interacted with by the user. */
346
+ touched: Record<string, boolean>;
347
+ }
348
+ /**
349
+ * Sparse map of field `name` → i18n error key (or custom validator message).
350
+ * Only fields that failed validation appear as keys. An empty object means the
351
+ * form is valid. Alias for {@link FormErrors}.
352
+ */
353
+ type ValidationErrors = FormErrors;
354
+
355
+ /**
356
+ * A flat map of i18n keys to their translated strings.
357
+ * All keys follow the `country-forms.*` prefix convention.
358
+ *
359
+ * The bundle is intentionally `Readonly` — consumers must not mutate it.
360
+ * For custom copy, use the `overrides` parameter of `resolveLabel` instead.
361
+ *
362
+ * @example
363
+ * const bundle = await loadLocale('pt-BR')
364
+ * const label = bundle['country-forms.address.postalCode.label'] // "CEP"
365
+ */
366
+ type I18nBundle = Record<string, string>;
367
+ /**
368
+ * Consumer-supplied overrides with the same key structure as {@link I18nBundle}.
369
+ * Used in `resolveLabel` to override specific labels without forking the library.
370
+ *
371
+ * @example
372
+ * const overrides: I18nOverrides = {
373
+ * 'country-forms.address.postalCode.label': 'ZIP / CEP (custom)',
374
+ * }
375
+ * resolveLabel('country-forms.address.postalCode.label', bundle, overrides)
376
+ */
377
+ type I18nOverrides = Record<string, string>;
378
+
379
+ /**
380
+ * A synchronous field validator function.
381
+ *
382
+ * - Returns `true` when the value is valid.
383
+ * - Returns an **i18n key** string (e.g. `"country-forms.validation.cpf.invalid"`) when invalid.
384
+ * The engine passes this key to the error map; consumers resolve it via `resolveLabel`.
385
+ *
386
+ * Validators must be **pure** and **synchronous**.
387
+ * Async validations (postal code lookups, document checks against external APIs) are the
388
+ * consumer's responsibility and must not live in this registry.
389
+ *
390
+ * @example
391
+ * const validateCEP: ValidatorFn = (value) =>
392
+ * /^\d{5}-?\d{3}$/.test(value) || 'country-forms.validation.postalCode.BRA'
393
+ */
394
+ type ValidatorFn = (value: string) => boolean | string;
395
+ /**
396
+ * A pure formatting function that transforms a raw value into its **display** representation.
397
+ *
398
+ * @example
399
+ * const formatCEP: FormatFn = (value) => value.replace(/^(\d{5})(\d{3})$/, '$1-$2')
400
+ */
401
+ type FormatFn = (value: string) => string;
402
+ /**
403
+ * A pure unformat function that strips display formatting and returns the **raw/API** value.
404
+ * Must be the inverse of the corresponding {@link FormatFn}:
405
+ * `unformat(format(x)) === x` for all valid inputs.
406
+ *
407
+ * @example
408
+ * const unformatCEP: UnformatFn = (value) => value.replace('-', '')
409
+ */
410
+ type UnformatFn = (value: string) => string;
411
+
412
+ /**
413
+ * @module engine/createFormState
414
+ */
415
+
416
+ /**
417
+ * Creates an initial {@link FormState} from a schema, optionally pre-filled
418
+ * with default values.
419
+ *
420
+ * - `values`: initialized to the matching default or empty string for each field
421
+ * - `errors`: empty map (no validation has run yet)
422
+ * - `touched`: all `false` (no user interaction yet)
423
+ *
424
+ * @param schema - The `FormSchema` whose fields define the state shape
425
+ * @param defaults - Optional partial map of field name → initial value
426
+ * @returns A fresh, immutable `FormState`
427
+ *
428
+ * @example
429
+ * const state = createFormState(schema)
430
+ * // state.values → { postalCode: '', street: '', ... }
431
+ * // state.errors → {}
432
+ * // state.touched → { postalCode: false, street: false, ... }
433
+ *
434
+ * @example
435
+ * const state = createFormState(schema, { city: 'São Paulo' })
436
+ * // state.values.city → 'São Paulo'
437
+ */
438
+ declare function createFormState(schema: FormSchema, defaults?: Partial<FormValues>): FormState;
439
+
440
+ /**
441
+ * @module engine/setValue
442
+ */
443
+
444
+ /**
445
+ * Returns a new {@link FormState} with an updated field value.
446
+ *
447
+ * The operation is **immutable** — the original state is never mutated.
448
+ * The updated field is automatically marked as `touched: true`.
449
+ *
450
+ * When the changed field is referenced by another field's `dependsOn` and that
451
+ * field has `conditionalOptions`, the dependent field's value is automatically
452
+ * reset to `''`. This prevents stale values when the controller field changes
453
+ * (e.g. selecting a different state clears the previously selected city).
454
+ *
455
+ * Existing errors are preserved so the consumer can decide when to re-validate.
456
+ * To clear all errors after a change, spread: `{ ...setValue(state, schema, f, v), errors: {} }`.
457
+ *
458
+ * @param state - Current form state (not mutated)
459
+ * @param schema - The form schema (used to detect dependent fields)
460
+ * @param fieldName - `FieldDefinition.name` of the field to update
461
+ * @param value - New value for the field
462
+ * @returns A new `FormState` with the updated value, touched flag, and dependent fields reset
463
+ *
464
+ * @example
465
+ * const next = setValue(state, schema, 'street', 'Rua Augusta')
466
+ * // next.values.street → 'Rua Augusta'
467
+ * // next.touched.street → true
468
+ * // state.values.street → '' (original unchanged)
469
+ *
470
+ * @example
471
+ * // Dependent field reset: changing state clears city
472
+ * const next = setValue(state, braSchema, 'state', 'RJ')
473
+ * // next.values.state → 'RJ'
474
+ * // next.values.city → '' (reset because city depends on state)
475
+ */
476
+ declare function setValue(state: FormState, schema: FormSchema, fieldName: string, value: string): FormState;
477
+
478
+ /**
479
+ * @module engine/validate
480
+ *
481
+ * Synchronous form validation — no network calls, no async, no UI dependencies.
482
+ *
483
+ * ## Validation order (per field, short-circuit on first error)
484
+ *
485
+ * 1. **required** — field is required and value is blank (trim-aware)
486
+ * 2. **minLength** — value is shorter than the minimum
487
+ * 3. **maxLength** — value is longer than the maximum
488
+ * 4. **pattern** — value does not match the regex string
489
+ * 5. **customValidator** — named function resolved from the rules registry
490
+ *
491
+ * Short-circuiting: validation stops at the first failing rule for each field.
492
+ * Only one error key is produced per field at a time.
493
+ *
494
+ * ## Error values
495
+ *
496
+ * Every error in the returned `FormErrors` map is an **i18n key** (or the string
497
+ * returned directly by a `customValidator`). Consumers resolve it via `resolveLabel`.
498
+ *
499
+ * ## Conditional visibility
500
+ *
501
+ * Fields with `conditionalVisibility` are only validated when they are visible.
502
+ * `validate` calls `getVisibleFields(schema, state.values)` internally — hidden
503
+ * required fields are silently skipped and never appear in the returned error map.
504
+ */
505
+
506
+ /**
507
+ * Runs all synchronous validation rules in `schema` against the current `state`.
508
+ *
509
+ * Rules applied per field (in order, short-circuit on first error):
510
+ * `required` → `minLength` → `maxLength` → `pattern` → `customValidator`
511
+ *
512
+ * @param state - Current form state (values to validate against)
513
+ * @param schema - Schema whose validation rules are applied
514
+ * @returns Sparse `FormErrors` map — empty object means the form is valid.
515
+ * Only fields with errors appear as keys.
516
+ *
517
+ * @example
518
+ * const errors = validate(state, schema)
519
+ * if (Object.keys(errors).length > 0) {
520
+ * state = { ...state, errors }
521
+ * return
522
+ * }
523
+ */
524
+ declare function validate(state: FormState, schema: FormSchema): FormErrors;
525
+
526
+ /**
527
+ * @module engine/getVisibleFields
528
+ *
529
+ * Evaluates declarative `conditionalVisibility` expressions to determine which
530
+ * fields should be shown — and therefore validated — given the current form values.
531
+ *
532
+ * ## Supported expressions
533
+ *
534
+ * Each field may declare a `conditionalVisibility` object with one condition
535
+ * referencing a sibling field. The supported operators are:
536
+ *
537
+ * | Operator | Condition value type | Field is visible when… |
538
+ * |----------------|----------------------|------------------------------------------------|
539
+ * | `"equals"` | `string` | `values[field] === value` |
540
+ * | `"notEquals"` | `string` | `values[field] !== value` |
541
+ * | `"includes"` | `string \| string[]` | `condition.value` contains `values[field]` |
542
+ * | `"notIncludes"`| `string \| string[]` | `condition.value` does not contain `values[field]` |
543
+ *
544
+ * A field with **no** `conditionalVisibility` is **always visible**.
545
+ *
546
+ * ## Usage
547
+ *
548
+ * ```typescript
549
+ * const visibleFields = getVisibleFields(schema, state.values)
550
+ * // Render only visibleFields; validate() uses this automatically.
551
+ * ```
552
+ *
553
+ * ## Integration with validate
554
+ *
555
+ * `validate(state, schema)` calls `getVisibleFields` internally before running
556
+ * rules, ensuring that hidden required fields never produce blocking errors.
557
+ *
558
+ * ## Missing controller value
559
+ *
560
+ * If the controller field named in `conditionalVisibility.field` has no value
561
+ * in `values`, it is treated as an empty string `""` when evaluating the condition.
562
+ *
563
+ * ## Composite conditions (future)
564
+ *
565
+ * The current implementation evaluates a single `ConditionalVisibility` object
566
+ * per field (one condition, one operator). Logical composition (`and` / `or`) of
567
+ * multiple conditions is reserved for a future schema version.
568
+ */
569
+
570
+ /**
571
+ * Returns the ordered subset of `schema.fields` that are visible given `values`.
572
+ *
573
+ * Fields without `conditionalVisibility` are always included.
574
+ * Fields whose condition evaluates to `false` are excluded — they will not be
575
+ * rendered by the consumer and will not be validated by `validate()`.
576
+ *
577
+ * @param schema - The form schema containing all field definitions
578
+ * @param values - Current form values keyed by field name
579
+ * @returns Ordered array of visible `FieldDefinition` objects
580
+ *
581
+ * @example
582
+ * // Field "cnpj" is only shown when "personType" === "business"
583
+ * const visible = getVisibleFields(schema, state.values)
584
+ * visible.forEach(field => renderField(field))
585
+ */
586
+ declare function getVisibleFields(schema: FormSchema, values: FormValues): FieldDefinition[];
587
+
588
+ /**
589
+ * @module engine/format
590
+ *
591
+ * Format and unformat helpers that apply mask functions from the rules registry
592
+ * to a field's value, driven by the field's `formatRef` / `unformatRef`.
593
+ *
594
+ * ## Typical usage
595
+ *
596
+ * ```typescript
597
+ * // Display: raw → formatted (e.g. "01310100" → "01310-100")
598
+ * const displayed = formatValue(field.formatRef, rawValue)
599
+ *
600
+ * // Submission: formatted → raw (e.g. "01310-100" → "01310100")
601
+ * const raw = unformatValue(field.unformatRef, displayedValue)
602
+ * ```
603
+ *
604
+ * ## Identity behaviour (no mask)
605
+ *
606
+ * When `ref` is `undefined` (field has no mask) or the ref has not been registered,
607
+ * the function returns the value unchanged. This makes both functions safe to call
608
+ * unconditionally — consumers can always pass `field.formatRef` without guarding.
609
+ */
610
+ /**
611
+ * Returns the **display** representation of `value`.
612
+ *
613
+ * Resolves `ref` from the masks registry and applies the registered format function.
614
+ *
615
+ * `ref` accepts `string | undefined` so callers can forward `field.formatRef` directly
616
+ * without guarding against fields that have no mask. This removes boilerplate at every
617
+ * call site — the trade-off is that passing `undefined` by mistake produces no error signal,
618
+ * returning `value` silently unchanged instead.
619
+ *
620
+ * @param ref - `FieldDefinition.formatRef`, e.g. `"formatCEP"`.
621
+ * Pass `undefined` (or omit the guard) for fields that carry no mask.
622
+ * @param value - Raw value to format (e.g. `"01310100"`).
623
+ * @returns Formatted display string (e.g. `"01310-100"`) when `ref` is a registered key;
624
+ * `value` unchanged (identity) when `ref` is `undefined` or not found in the registry.
625
+ *
626
+ * @example
627
+ * formatValue(field.formatRef, '01310100') // → "01310-100" (mask applied)
628
+ * formatValue(undefined, 'Av Paulista') // → "Av Paulista" (no ref — identity)
629
+ * formatValue('unknownRef', '01310100') // → "01310100" (not registered — identity)
630
+ */
631
+ declare function formatValue(ref: string | undefined, value: string): string;
632
+ /**
633
+ * Returns the **raw/API** representation of `value`, stripping any display formatting.
634
+ *
635
+ * Resolves `ref` from the masks registry and applies the registered unformat function.
636
+ * Symmetric to {@link formatValue} — same `string | undefined` ergonomic contract applies.
637
+ *
638
+ * The round-trip invariant holds when masks are correctly paired:
639
+ * `unformatValue(field.unformatRef, formatValue(field.formatRef, raw)) === raw`
640
+ *
641
+ * @param ref - `FieldDefinition.unformatRef`, e.g. `"unformatCEP"`.
642
+ * Pass `undefined` (or omit the guard) for fields that carry no mask.
643
+ * @param value - Display value to strip (e.g. `"01310-100"`).
644
+ * @returns Raw string suitable for API submission (e.g. `"01310100"`) when `ref` is a registered key;
645
+ * `value` unchanged (identity) when `ref` is `undefined` or not found in the registry.
646
+ *
647
+ * @example
648
+ * unformatValue(field.unformatRef, '01310-100') // → "01310100" (mask applied)
649
+ * unformatValue(undefined, 'Av Paulista') // → "Av Paulista" (no ref — identity)
650
+ * unformatValue('unknownRef', '01310-100') // → "01310-100" (not registered — identity)
651
+ */
652
+ declare function unformatValue(ref: string | undefined, value: string): string;
653
+
654
+ /**
655
+ * @module engine/resolveFieldOptions
656
+ */
657
+
658
+ /**
659
+ * Resolves the effective options for a field, including dependent options.
660
+ *
661
+ * Resolution order:
662
+ * 1) `conditionalOptions` entry matching `values[dependsOn]`
663
+ * 2) `options` fallback on the field
664
+ *
665
+ * @param field - The field definition to resolve options for
666
+ * @param values - Current form values (used to look up the controller field via `dependsOn`)
667
+ * @returns `SelectOption[]` when options are available, `null` when no source is resolvable
668
+ */
669
+ declare function resolveFieldOptions(field: FieldDefinition, values: FormValues): SelectOption[] | null;
670
+
671
+ /**
672
+ * Dynamic import map for address schemas.
673
+ * Each country is loaded on demand via `import()` for code-splitting.
674
+ *
675
+ * When adding a new country schema:
676
+ * 1. Add the ISO 3166-1 alpha-3 code to `SUPPORTED_ADDRESS_COUNTRIES`
677
+ * 2. Add a `case` in `loadAddressSchema` with `import('./<CODE>')`
678
+ * 3. Import the country's rule modules (validators, masks, options) in the case body
679
+ */
680
+
681
+ /**
682
+ * ISO 3166-1 alpha-3 codes for countries with a dedicated address schema.
683
+ * Grows as country schemas are implemented.
684
+ * Consumers can import this to build country selectors or validate input.
685
+ *
686
+ * @example
687
+ * import { SUPPORTED_ADDRESS_COUNTRIES } from '@vtex/country-forms'
688
+ * // currently supported countries: → ['BRA', 'CAN', 'MEX', 'USA']
689
+ */
690
+ declare const SUPPORTED_ADDRESS_COUNTRIES: readonly string[];
691
+
692
+ /**
693
+ * Dynamic import map for personal-data schemas.
694
+ * Each country is loaded on demand via `import()` for code-splitting.
695
+ *
696
+ * When adding a new country schema:
697
+ * 1. Add the ISO 3166-1 alpha-3 code to `SUPPORTED_PERSONAL_DATA_COUNTRIES`
698
+ * 2. Add a `case` in `loadPersonalDataSchema` with dynamic imports
699
+ * 3. Import the country's rule modules (validators, masks, options) in the case body
700
+ */
701
+
702
+ /**
703
+ * ISO 3166-1 alpha-3 codes for countries with a dedicated personal-data schema.
704
+ * Grows as country schemas are implemented.
705
+ *
706
+ * @example
707
+ * import { SUPPORTED_PERSONAL_DATA_COUNTRIES } from '@vtex/country-forms'
708
+ * // currently supported countries: → ['BRA']
709
+ */
710
+ declare const SUPPORTED_PERSONAL_DATA_COUNTRIES: readonly string[];
711
+
712
+ /**
713
+ * @module engine/loadSchema
714
+ *
715
+ * Loads a `FormSchema` for a given country code and form type on demand.
716
+ * Each country's schema is a separate module, enabling **code-splitting**: only the
717
+ * requested country's code enters the consumer's bundle.
718
+ *
719
+ * ## Fallback behaviour
720
+ *
721
+ * If `iso3` is not supported (or `formType` has no dedicated schemas yet),
722
+ * `loadSchema` returns a **deterministic generic fallback schema** — it never throws
723
+ * at runtime for an unknown country code. The fallback carries the requested `iso3`
724
+ * in `schema.country` and provides a minimal set of generic fields.
725
+ */
726
+
727
+ /**
728
+ * Loads and returns the `FormSchema` for the given country code and form type.
729
+ *
730
+ * - Uses dynamic `import()` internally for each country module (code-splitting).
731
+ * - Returns a **generic fallback schema** for unsupported country codes — never throws.
732
+ *
733
+ * @param iso3 - ISO 3166-1 alpha-3 country code (e.g. `"BRA"`, `"USA"`)
734
+ * @param formType - Form category: `"address"` or `"personal-data"`
735
+ * @returns Promise resolving to the country's `FormSchema`
736
+ *
737
+ * @example
738
+ * const schema = await loadSchema('BRA', 'address')
739
+ * // → FormSchema { id: "address-BRA", country: "BRA", formType: "address", fields: [...] }
740
+ *
741
+ * const unknown = await loadSchema('XYZ', 'address')
742
+ * // → fallback FormSchema { id: "address-XYZ", country: "XYZ", ... }
743
+ */
744
+ declare function loadSchema(iso3: string, formType: FormType): Promise<FormSchema>;
745
+
746
+ /**
747
+ * @module i18n/loader
748
+ *
749
+ * `loadLocale(locale)` — dynamically imports the i18n bundle for the requested
750
+ * BCP 47 locale tag, enabling code-splitting: only the locale actually used
751
+ * enters the consumer's bundle.
752
+ *
753
+ * ## Resolution order
754
+ *
755
+ * 1. **Exact match** on the canonical supported tag (`en-US`, `es-MX`, `fr-FR`, `pt-BR`).
756
+ * 2. **Language-subtag fallback** — the language portion before the `-` is used
757
+ * to match a bundle, so regional variants resolve gracefully:
758
+ * - `en-GB`, `en-AU` → `en-US` bundle
759
+ * - `es-419`, `es-ES` → `es-MX` bundle
760
+ * - `fr-CA` → `fr-FR` bundle
761
+ * - `pt-PT` → `pt-BR` bundle
762
+ * 3. **Default fallback** — any unrecognized tag returns the `en-US` bundle.
763
+ *
764
+ * The function **never throws** for an unsupported locale.
765
+ *
766
+ * @param locale - BCP 47 locale tag (e.g. `"pt-BR"`, `"en-US"`, `"es-419"`)
767
+ * @returns Resolved `I18nBundle` for the best-matching locale
768
+ *
769
+ * @example
770
+ * const bundle = await loadLocale('pt-BR')
771
+ * bundle['country-forms.address.postalCode.label'] // "CEP"
772
+ *
773
+ * @example
774
+ * const bundle = await loadLocale('de-DE') // → en-US bundle (fallback)
775
+ */
776
+
777
+ declare function loadLocale(locale: string): Promise<I18nBundle>;
778
+
779
+ /**
780
+ * @module i18n/resolveLabel
781
+ *
782
+ * Resolves an i18n key to its display string using a three-level cascade:
783
+ *
784
+ * 1. **Consumer override** — `overrides[key]` wins if present.
785
+ * 2. **Bundle value** — `bundle[key]` from `loadLocale()`.
786
+ * 3. **Raw key** — the key itself is returned as a last resort, so the UI
787
+ * never shows `undefined` or crashes.
788
+ *
789
+ * This design lets consumers customize individual labels without forking the
790
+ * library or replacing the entire bundle.
791
+ *
792
+ * @param key - i18n key (e.g. `"country-forms.address.postalCode.label"`)
793
+ * @param bundle - Locale bundle loaded via `loadLocale()`
794
+ * @param overrides - Optional consumer-supplied overrides
795
+ * @returns Resolved display string
796
+ *
797
+ * @example
798
+ * const bundle = await loadLocale('pt-BR')
799
+ * resolveLabel('country-forms.address.postalCode.label', bundle)
800
+ * // → "CEP"
801
+ *
802
+ * @example
803
+ * const overrides = { 'country-forms.address.postalCode.label': 'ZIP / CEP' }
804
+ * resolveLabel('country-forms.address.postalCode.label', bundle, overrides)
805
+ * // → "ZIP / CEP" (override wins)
806
+ *
807
+ * @example
808
+ * resolveLabel('country-forms.unknown.key', bundle)
809
+ * // → "country-forms.unknown.key" (raw key fallback)
810
+ */
811
+
812
+ declare function resolveLabel(key: string, bundle: I18nBundle, overrides?: I18nOverrides): string;
813
+
814
+ /**
815
+ * BCP 47 locale tags supported by the library's built-in translation bundles.
816
+ *
817
+ * | Tag | Language |
818
+ * |----------|---------------------------|
819
+ * | `en-US` | English (United States) |
820
+ * | `es-MX` | Spanish (Mexico) |
821
+ * | `fr-FR` | French (France) |
822
+ * | `pt-BR` | Portuguese (Brazil) |
823
+ *
824
+ * Any other tag passed to `loadLocale` falls back to `en-US`.
825
+ * Regional variants (e.g. `en-GB`, `es-419`) also resolve via the language
826
+ * subtag — see `loadLocale` for details.
827
+ */
828
+ /** @const BCP 47 tags with built-in bundles. See `loadLocale` for resolution. */
829
+ declare const SUPPORTED_LOCALES: readonly ["en-US", "es-MX", "fr-FR", "pt-BR"];
830
+ /** Union of BCP 47 tags with dedicated built-in bundles. */
831
+ type SupportedLocale = (typeof SUPPORTED_LOCALES)[number];
832
+
833
+ export { type ConditionalOperator, type ConditionalVisibility, type FieldDefinition, type FieldType, type FormErrors, type FormSchema, type FormState, type FormType, type FormValues, type FormatFn, type I18nBundle, type I18nOverrides, type InputMode, SUPPORTED_ADDRESS_COUNTRIES, SUPPORTED_LOCALES, SUPPORTED_PERSONAL_DATA_COUNTRIES, type SelectOption, type SupportedLocale, type UnformatFn, type ValidationErrors, type ValidationRules, type ValidatorFn, createFormState, formatValue, getVisibleFields, loadLocale, loadSchema, resolveFieldOptions, resolveLabel, setValue, unformatValue, validate };