@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.
package/README.md ADDED
@@ -0,0 +1,276 @@
1
+ # `@vtex/country-forms`
2
+
3
+ A fully headless, framework-agnostic form engine that serves as VTEX's **single source of truth** for address and personal data forms. It provides declarative, per-country schemas with built-in synchronous validation, masks (format/unformat), and i18n with on-demand locale loading and consumer-level label overrides.
4
+
5
+ **Zero runtime dependencies.** Works in browsers, Node.js, and React Native.
6
+
7
+ ---
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ # npm
13
+ npm install @vtex/country-forms
14
+
15
+ # yarn
16
+ yarn add @vtex/country-forms
17
+
18
+ # pnpm
19
+ pnpm add @vtex/country-forms
20
+ ```
21
+
22
+ ---
23
+
24
+ ## Quick Start
25
+
26
+ ```typescript
27
+ import {
28
+ loadSchema,
29
+ loadLocale,
30
+ createFormState,
31
+ setValue,
32
+ validate,
33
+ getVisibleFields,
34
+ formatValue,
35
+ unformatValue,
36
+ resolveLabel,
37
+ } from '@vtex/country-forms'
38
+
39
+ // 1. Load schema and locale (code-split via dynamic import)
40
+ const schema = await loadSchema('BRA', 'address')
41
+ const i18n = await loadLocale('pt-BR')
42
+
43
+ // 2. Create form state
44
+ let state = createFormState(schema)
45
+
46
+ // 3. Render visible fields
47
+ const fields = getVisibleFields(schema, state.values)
48
+ fields.forEach(field => {
49
+ const label = resolveLabel(field.label, i18n)
50
+ // render your UI component with label, value, options, etc.
51
+ })
52
+
53
+ // 4. Update state on user input
54
+ state = setValue(state, schema, 'postalCode', '01001000')
55
+
56
+ // 5. Format for display
57
+ const display = formatValue(field.formatRef, '01001000') // → "01001-000"
58
+
59
+ // 6. Validate on submit
60
+ const errors = validate(state, schema)
61
+ if (Object.keys(errors).length === 0) {
62
+ // form is valid — unformat values before submitting to your API
63
+ const raw = unformatValue(field.unformatRef, display) // → "01001000"
64
+ }
65
+ ```
66
+
67
+ Both `loadSchema` and `loadLocale` use dynamic `import()` internally — only the requested country and locale enter your bundle.
68
+
69
+ ---
70
+
71
+ ## API Reference
72
+
73
+ ### Functions
74
+
75
+ | Function | Signature | Description |
76
+ |----------|-----------|-------------|
77
+ | `loadSchema` | `(countryCode, formType) → Promise<FormSchema>` | Loads a country-specific schema. Returns a generic fallback for unknown countries (never throws). |
78
+ | `loadLocale` | `(locale) → Promise<I18nBundle>` | Loads an i18n bundle. Falls back to `en-US` for unsupported locales (never throws). |
79
+ | `createFormState` | `(schema, defaults?) → FormState` | Creates initial form state from a schema, optionally pre-filled. |
80
+ | `setValue` | `(state, schema, fieldName, value) → FormState` | Returns a new state with the updated value. Automatically resets dependent fields with `conditionalOptions`. |
81
+ | `validate` | `(state, schema) → FormErrors` | Synchronous validation. Returns a sparse error map — empty object means valid. Hidden fields are skipped. |
82
+ | `getVisibleFields` | `(schema, values) → FieldDefinition[]` | Returns fields visible for the current values (evaluates `conditionalVisibility`). |
83
+ | `formatValue` | `(ref, value) → string` | Applies display mask (e.g. `"01001000"` → `"01001-000"`). Identity if `ref` is undefined. |
84
+ | `unformatValue` | `(ref, value) → string` | Strips mask for submission (e.g. `"01001-000"` → `"01001000"`). Identity if `ref` is undefined. |
85
+ | `resolveLabel` | `(key, bundle, overrides?) → string` | Resolves i18n label. Fallback: override → bundle → raw key. |
86
+ | `resolveFieldOptions` | `(field, values) → SelectOption[] \| null` | Resolves static or conditional options for a field. |
87
+
88
+ ### Constants
89
+
90
+ | Constant | Type | Description |
91
+ |----------|------|-------------|
92
+ | `SUPPORTED_ADDRESS_COUNTRIES` | `readonly string[]` | Countries with a dedicated address schema (`['BRA', 'CAN', 'MEX', 'USA']`). |
93
+ | `SUPPORTED_PERSONAL_DATA_COUNTRIES` | `readonly string[]` | Countries with a dedicated personal-data schema (`['BRA']`). |
94
+ | `SUPPORTED_LOCALES` | `readonly string[]` | Built-in locale tags (`['en-US', 'es-MX', 'fr-FR', 'pt-BR']`). |
95
+
96
+ ### Types
97
+
98
+ All types are exported from the package root:
99
+
100
+ ```typescript
101
+ import type {
102
+ FormSchema,
103
+ FieldDefinition,
104
+ FieldType, // 'text' | 'email' | 'select' | 'radio-group'
105
+ FormType, // 'address' | 'personal-data'
106
+ InputMode, // 'text' | 'numeric' | 'tel' | 'email'
107
+ ValidationRules,
108
+ ConditionalVisibility,
109
+ SelectOption,
110
+ FormValues,
111
+ FormErrors,
112
+ FormState,
113
+ I18nBundle,
114
+ I18nOverrides,
115
+ SupportedLocale,
116
+ ValidatorFn,
117
+ FormatFn,
118
+ UnformatFn,
119
+ } from '@vtex/country-forms'
120
+ ```
121
+
122
+ ---
123
+
124
+ ## Supported Countries
125
+
126
+ | Country | ISO3 | Address | Personal Data | Validators | Masks |
127
+ |---------|------|:-------:|:-------------:|------------|-------|
128
+ | Brazil | `BRA` | Yes | Yes | CEP, CPF, CNPJ, Email, Phone | CEP, CPF, CNPJ, Phone |
129
+ | United States | `USA` | Yes | — | ZIP | ZIP |
130
+ | Canada | `CAN` | Yes | — | Postal code | Postal code |
131
+ | Mexico | `MEX` | Yes | — | Postal code | — |
132
+
133
+ For unknown countries, `loadSchema` returns a generic fallback schema with basic address or personal-data fields.
134
+
135
+ ---
136
+
137
+ ## Supported Locales
138
+
139
+ | Tag | Language |
140
+ |-----|----------|
141
+ | `en-US` | English (reference and default fallback) |
142
+ | `pt-BR` | Portuguese (Brazil) |
143
+ | `es-MX` | Spanish (Mexico) |
144
+ | `fr-FR` | French (France) |
145
+
146
+ `loadLocale` resolves regional variants to the closest match:
147
+ - `en-GB`, `en-AU` → `en-US`
148
+ - `es-419`, `es-ES` → `es-MX`
149
+ - `fr-CA` → `fr-FR`
150
+ - `pt-PT` → `pt-BR`
151
+ - Unknown language → `en-US`
152
+
153
+ ---
154
+
155
+ ## Example Usage
156
+
157
+ ### Country and locale selector
158
+
159
+ Use the constants to build dropdowns driven entirely by the library — no hardcoded lists in your application:
160
+
161
+ ```typescript
162
+ import {
163
+ SUPPORTED_ADDRESS_COUNTRIES,
164
+ SUPPORTED_LOCALES,
165
+ loadSchema,
166
+ loadLocale,
167
+ createFormState,
168
+ } from '@vtex/country-forms'
169
+
170
+ // Country selector options — always in sync with what the library supports
171
+ const countryOptions = SUPPORTED_ADDRESS_COUNTRIES.map(iso3 => ({
172
+ value: iso3,
173
+ label: iso3, // replace with your own display names
174
+ }))
175
+
176
+ // Locale selector options
177
+ const localeOptions = SUPPORTED_LOCALES.map(tag => ({
178
+ value: tag,
179
+ label: tag, // replace with your own display names, e.g. "Português"
180
+ }))
181
+
182
+ // Load schema and locale when the user selects a country/locale
183
+ async function onCountryChange(iso3: string, locale: string) {
184
+ const [schema, i18n] = await Promise.all([
185
+ loadSchema(iso3, 'address'),
186
+ loadLocale(locale),
187
+ ])
188
+ const state = createFormState(schema)
189
+ // update your UI with schema, i18n, state
190
+ }
191
+ ```
192
+
193
+ ### Guard before loading (optional)
194
+
195
+ `loadSchema` never throws — it returns a generic fallback for unknown countries. You can still guard with the constant if you want to show different UI for unsupported countries:
196
+
197
+ ```typescript
198
+ import { SUPPORTED_ADDRESS_COUNTRIES, loadSchema } from '@vtex/country-forms'
199
+
200
+ if (SUPPORTED_ADDRESS_COUNTRIES.includes(iso3)) {
201
+ // dedicated schema with country-specific fields and validators
202
+ const schema = await loadSchema(iso3, 'address')
203
+ } else {
204
+ // generic fallback schema — loadSchema works here too, no need to skip
205
+ const schema = await loadSchema(iso3, 'address')
206
+ }
207
+ ```
208
+
209
+ ---
210
+
211
+ ## i18n Overrides
212
+
213
+ Override any label or message without forking the library:
214
+
215
+ ```typescript
216
+ const overrides = {
217
+ 'country-forms.address.street.label': 'Delivery street',
218
+ 'country-forms.validation.required': 'This field is mandatory',
219
+ }
220
+
221
+ const label = resolveLabel(field.label, i18n, overrides)
222
+ // → "Delivery street" (override wins over bundle)
223
+ ```
224
+
225
+ Fallback order: **consumer override → library bundle → raw key**.
226
+
227
+ ---
228
+
229
+ ## Consumer Responsibilities
230
+
231
+ ### Async Validation
232
+
233
+ The library provides **synchronous validation only**. Async validations such as postal code lookup via API, document verification against external services, or server-side uniqueness checks must be implemented in your application.
234
+
235
+ ```typescript
236
+ const errors = validate(state, schema)
237
+
238
+ // Add your async validations
239
+ const postalCode = state.values.postalCode
240
+ const apiResult = await myApi.validatePostalCode(postalCode)
241
+ if (!apiResult.valid) {
242
+ errors.postalCode = 'My custom async error message'
243
+ }
244
+ ```
245
+
246
+ ### UI Rendering
247
+
248
+ The library is **headless** — it never renders UI components. You map each `field.type` to your own component:
249
+
250
+ ```typescript
251
+ const renderers = {
252
+ text: MyTextInput,
253
+ email: MyEmailInput,
254
+ select: MySelect,
255
+ 'radio-group': MyRadioGroup,
256
+ }
257
+
258
+ getVisibleFields(schema, state.values).forEach(field => {
259
+ const Component = renderers[field.type]
260
+ // render <Component label={...} value={...} options={...} />
261
+ })
262
+ ```
263
+
264
+ ### Persistence
265
+
266
+ How you save form data to your API or backend is your concern. The library defines form-layer field names only — it does not prescribe REST/GraphQL payload shapes or database schemas. If your API uses different property names, implement the mapping in your application.
267
+
268
+ ---
269
+
270
+ ## Code-Splitting
271
+
272
+ The library is designed for tree-shaking and code-splitting:
273
+
274
+ - `loadSchema('BRA', 'address')` only loads the BRA address schema and its rules
275
+ - `loadLocale('pt-BR')` only loads the Portuguese bundle
276
+ - Unused schemas, rules, and locales are excluded by modern bundlers (Webpack, Vite, etc.)