{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "address-input",
  "title": "Address Input",
  "description": "A postal address form that renders the fields the chosen country actually writes, in that country's order, with that country's labels, and with only that country's fields required. Japan asks for a postal code, then a prefecture, then the address — and no city at all. The United Kingdom has no state and calls its city a post town. Hong Kong has no postal code but requires an area. Singapore has no state but requires a six-digit postal code. Ireland has a townland line above the town and an optional Eircode. Reach for it wherever a form collects somewhere a letter or a parcel could actually arrive: checkout shipping and billing addresses; sign-up and onboarding; KYC, AML and identity verification; a company, store, clinic or venue's registered address; invoicing, VAT and tax details; bank, payout and remittance details; delivery, collection and installation; the address row on a profile, customer or organisation record; insurance, loan and mortgage applications; a change-of-address or moving form; shipping labels and customs declarations; and the address block on any admin or CRM record. Common asks it answers: \"address form react\", \"address input component\", \"international address form\", \"shadcn address form\", \"shadcn address input\", \"shadcn address fields\", \"country specific address fields\", \"address fields by country\", \"dynamic address form by country\", \"address form i18n\", \"localized address form react\", \"address form that changes by country\", \"postal code validation react\", \"zip code validation by country\", \"validate postcode regex by country\", \"state field optional for international addresses\", \"address form without state field\", \"required state breaks international checkout\", \"japan address form react\", \"japanese address no city field\", \"prefecture field react\", \"uk address form post town\", \"hong kong address no postal code\", \"singapore address form\", \"ireland eircode optional\", \"address autocomplete attributes react\", \"autocomplete address-level1 address-level2\", \"autocomplete street-address vs address-line1\", \"browser autofill address form react\", \"autofill puts city in the wrong field\", \"shipping and billing autofill same page\", \"autocomplete section prefix shipping billing\", \"react address form validation\", \"google libaddressinput react\", \"libaddressinput data react component\", \"i18n-postal-address alternative\", \"@shopify/address react component\", \"react-country-region-selector alternative\", \"use-places-autocomplete alternative\", \"react-google-places-autocomplete alternative\", \"address form without google places api\", \"address form no api key\", \"accessible address form labels\", \"住所 フォーム react\", \"住所入力 コンポーネント\", \"国別 住所 項目 変わる\", \"海外 住所 入力 フォーム\", \"都道府県 入力 フォーム\", \"郵便番号 バリデーション 国別\", \"住所 autocomplete 属性\", \"自動入力 住所 ずれる\", \"州 必須 海外 住所 入力できない\", \"post town イギリス 住所\", \"請求先 配送先 住所 フォーム\". Official shadcn/ui has nothing of the kind, measured today rather than remembered. Fetching every entry in its registry — 65 listed, 62 fetchable, code-block, questionnaire and trace 404 on both style tracks — and searching all 223,287 bytes of files[].content, address, postalCode, postcode, locality, administrativeArea, addressLine, street, zip, address-level1, street-address, prefecture, province, county, Eircode and CLDR are every one of them a zero hit: its field, input-group and native-select are empty containers that know nothing about where anything is. The decision everything else follows from: there is no such thing as the fields of an address, so the field list is data and not layout. A form with a required State and a required ZIP is a form a large part of the world cannot complete, and the usual workaround — marking them optional and hiding the rest behind an \"international\" branch — moves the problem into the data instead of solving it. So the field set, the order, the labels, the required flags and the shape of the postal code all come out of a 252-country table derived from the dataset Chrome's own address autofill uses (Google's Address Data Service, the data behind libaddressinput, Apache-2.0). It is re-derivable rather than a snapshot nobody can check: scripts/address-data.mjs prints the table, and --check diffs the shipped one against upstream and names every country that has drifted. Nothing in it was written from memory, and that is not a figure of speech — this component's own design note had Japan down as postal code, prefecture, municipality and had Hong Kong as having neither a state nor a postal code, and the measured data contradicts both. What the data decides, field by field: the order (Japan ZSA, the US ACSZ, Hong Kong SCA — largest unit first in the countries that write it that way), which fields exist at all, which may be left empty (Ireland overrides nothing and so inherits street-and-town, leaving its county and Eircode optional), and what the field is called — twelve different names for the administrative area alone, so prefecture, state, province, county, parish, island, department, emirate, area, oblast and Do / Si each read as themselves, and ZIP code, PIN code, Eircode and postal code likewise. Labels are keyed by the name upstream gives the field rather than by country, so labels={{ prefecture: \"都道府県\" }} translates every country that calls it that in one line. The second half is browser autofill, which matters more here than in any other field because there are six of them: each input carries the token the browser fills it from — street-address when there is one address line and address-line1/2/3 when there are several, address-level1 for the administrative area even in the countries that do not call it a state, address-level2 for the locality, address-level3 for the line above it, postal-code for the code — and autoCompleteSection prefixes every one of them, because a page with a shipping and a billing address otherwise hands the browser two fields both claiming to be postal-code and it fills one of them. The country is a native select for the same reason: a custom combobox cannot be autofilled, and autocomplete=\"country\" on the field that decides every other field is worth more than a searchable list. It is asked first whatever order that country writes it in, because it is what the rest of the form is; changing it clears the fields the new country does not have, since keeping them means the value carries a US state while the address is in Hong Kong and that is what eventually gets submitted. Postal codes are checked against their own country's pattern, and the anchoring is the part worth stating: several patterns upstream are a top-level alternation — the UK's is GIR ?0AA|(?:AB|AL|…)…|BFPO ?\\d{1,4} — so anchors written straight onto one bind the first and last branch only, and \"nonsense SW1A 1AA nonsense\" sails through. They are wrapped before they are anchored, and a test fails if the wrapper is removed. Codes are matched in capitals because no postal code is case-sensitive, and capitalised on the way out only where upstream says that country capitalises them — an Eircode is left as typed, because overriding the data there would be this component's opinion rather than the data's. An empty code is the required check's business and not the shape check's, so an optional code can actually be left empty. The mobile keyboard goes numeric only where the pattern cannot contain a letter: numeric for Japan, Germany and Singapore, text for the UK, Canada and the Netherlands. Controlled or uncontrolled, and typable in both — the value carries every field including the ones the country does not use, so a half-filled address round-trips through a controlled parent without losing a keystroke, and the re-seed compares field by field so a parent that rebuilds an equal object on every render does not reset the field being typed in. That is a bug this registry has shipped once already and it has a test here. Accessibility is the rest of it: a labelled role=\"group\", a real label pointing at every input, optional fields saying so in their label, aria-required, and an error that appears once a field has been visited — announced through role=\"alert\" and wired into aria-describedby and aria-invalid — with showErrors to surface every problem at once on submit. What it deliberately does not do: no subdivision lists (the administrative area is a text input with address-level1 so the browser can fill it; pass administrativeAreaOptions to make it a select where you do have the list), no recipient name or organisation (almost always already collected elsewhere in the form, and bundling them produces two name fields — in the countries that write largest-unit-first the recipient conventionally comes last), no address lookup, no Places call, no network, and no claim that a real address exists at that code. Within this registry the neighbours are each one field of this one: country-select picks the country and supplies the country names used here, phone-input collects a number, masked-input enforces a shape, slug-input a character set, and filter-builder and sort-builder build queries rather than addresses. None of them knows what fields an address has. The API: value and onChange make it controlled, or defaultValue uncontrolled, over a flat { country, addressLine1, addressLine2, addressLine3, dependentLocality, locality, administrativeArea, postalCode }; addressLines picks 1 to 3 street lines; countries narrows the list; locale names the countries; labels and messages cover the wording; autoCompleteSection, namePrefix, legend, showErrors, administrativeAreaOptions and disabled cover the rest, and namePrefix posts the whole address through a plain form or a server action. The rules are exported as pure functions so a server route, a shipping-label renderer, a confirmation screen or a test can have the same answers without mounting anything: rulesFor, fieldsFor, validateAddress, isValidPostalCode, postalCodePattern, normalizePostalCode and emptyAddress. Styled entirely with shadcn tokens (input, ring, destructive, muted-foreground, background) so it follows light and dark mode, and it ships zero npm dependencies — no address library, no country-data package, no icon package, one file.",
  "dependencies": [],
  "registryDependencies": [
    "https://pulld.pages.dev/r/country-select.json"
  ],
  "files": [
    {
      "path": "registry/ui/address-input.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\nimport { COUNTRY_CODES, getCountryName } from \"@/registry/ui/country-select\"\n\n/**\n * A postal address form whose fields are the ones the selected country actually writes.\n *\n * The reason this is a component and not a street/city/state/zip layout with a country dropdown on\n * top is that there is no such thing as the fields of an address. Japan writes the postal code\n * first, then the prefecture, and has **no city field at all** — the municipality belongs to the\n * street-address block. The United Kingdom has no state. Hong Kong has no postal code but\n * *requires* an area. Singapore has no state but requires a six-digit postal code. Ireland's\n * Eircode is optional, and Ireland has a townland line above the town that almost nothing else\n * does. A form with a required \"State\" and a required \"ZIP\" is a form a large part of the world\n * cannot complete, and the usual workaround — marking them optional and hiding them behind\n * \"international\" — moves the problem into the data instead of solving it.\n *\n * So the field list, the order, the labels, which fields may be left empty and the shape of the\n * postal code all come out of `COUNTRY_RULES` below, which is derived from the dataset Chrome's own\n * address autofill uses (Google's Address Data Service, the data behind libaddressinput). It is\n * re-derivable: `node scripts/address-data.mjs` prints the table and `--check` diffs the shipped\n * one against upstream and names any country that has drifted. Nothing in it was written from\n * memory, which matters more than it sounds — the first draft of this component's own design note\n * had Japan's fields as \"postal code, prefecture, municipality\" and had Hong Kong down as having\n * neither a state nor a postal code, and both are wrong in the measured data.\n *\n * What it deliberately does not do:\n *\n *   - **No subdivision lists.** The administrative area is a text input, not a select of the 47\n *     prefectures or the 50 states. Those lists are a different component's worth of data, they go\n *     stale, and `autocomplete=\"address-level1\"` already lets the browser fill the field. Pass\n *     `administrativeAreaOptions` to turn it into a select where you do have the list.\n *   - **No recipient name or organisation.** They are part of a printed address label but they are\n *     almost always already collected elsewhere in the form, and bundling them here produces two\n *     name fields. Render them yourself; in the countries that write the address largest-unit-first\n *     (`order` starting with `S` or `Z` — Japan, China, Korea, Hong Kong, Taiwan) the recipient\n *     conventionally comes *last*, after the street.\n *   - **No address lookup.** No postal-code-to-address call, no autocomplete service, no network.\n *\n * ```tsx\n * const [address, setAddress] = React.useState(() => emptyAddress(\"US\"))\n *\n * <AddressInput\n *   value={address}\n *   onChange={setAddress}\n *   autoCompleteSection=\"shipping\"\n *   namePrefix=\"shipping\"\n * />\n * ```\n *\n * Validate on submit with the same rules the fields show on blur:\n *\n * ```tsx\n * const errors = validateAddress(address)\n * if (Object.keys(errors).length) return setShowErrors(true)\n * ```\n */\n\n/** The locale country names are resolved in before hydration. See `namesReady` below. */\nconst HYDRATION_LOCALE = \"en-US\"\n\n/** The parts of a postal address this component collects, named as HTML autofill names them. */\nexport type AddressField =\n  | \"addressLine1\"\n  | \"addressLine2\"\n  | \"addressLine3\"\n  | \"dependentLocality\"\n  | \"locality\"\n  | \"administrativeArea\"\n  | \"postalCode\"\n\n/**\n * A whole address. Every field is always present, even the ones the country does not use, so a\n * partly-filled address is fully representable and a controlled parent can store it without\n * dropping keystrokes.\n */\nexport type AddressValue = { country: string } & Record<AddressField, string>\n\n/**\n * One country's deviations from the default.\n *\n * `order` is the address fields that country writes, in its own order, as letters: `A` street\n * address, `D` dependent locality, `C` locality, `S` administrative area, `Z` postal code. `US` is\n * `\"ACSZ\"`, `JP` is `\"ZSA\"`, `HK` is `\"SCA\"`. `required` is the subset that may not be empty, and\n * when absent the country inherits the default. The three `*Type` keys name the field rather than\n * labelling it — `state: \"prefecture\"` resolves through `FIELD_LABELS`, so one override translates\n * every country that calls it that.\n */\ntype CountryRule = {\n  order: string\n  required?: string\n  state?: string\n  locality?: string\n  postal?: string\n  sub?: string\n  pattern?: string\n  upperPostal?: boolean\n}\n\n/**\n * What a country inherits where it says nothing: a street address and a city, both required.\n *\n * This is upstream's `ZZ` entry, and it is the entry 54 countries rely on entirely — they ship no\n * format of their own. Four of those still override `require` (Antigua and Barbuda asks only for\n * the street), which is why the order and the required set are inherited separately.\n */\nconst DEFAULT_ORDER = \"AC\"\nconst DEFAULT_REQUIRED = \"AC\"\nconst DEFAULT_LABEL_TYPES = {\n  state: \"province\",\n  locality: \"city\",\n  postal: \"postal\",\n  sub: \"suburb\",\n} as const\n\n/**\n * Derived from Google's Address Data Service (Apache-2.0), 252 countries, by\n * `node scripts/address-data.mjs`. Run that with `--check` to diff this against upstream.\n *\n * The literal decoration upstream carries in its format strings — the 〒 before a Japanese postal\n * code, the word SINGAPORE, the comma in \"Springfield, IL 62704\" — is dropped on purpose. It is\n * for *printing* an address label; a form needs the order and the presence, not the punctuation.\n */\nconst COUNTRY_RULES: Record<string, CountryRule> = {\n  AC: { order: \"ACZ\", pattern: \"ASCN 1ZZ\" },\n  AD: { order: \"AZC\", pattern: \"AD[1-7]0\\\\d\" },\n  AE: { order: \"AS\", required: \"AS\", state: \"emirate\" },\n  AF: { order: \"ACZ\", pattern: \"\\\\d{4}\" },\n  AG: { order: \"AC\", required: \"A\" },\n  AI: { order: \"ACZ\", pattern: \"(?:AI-)?2640\" },\n  AL: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  AM: { order: \"AZCS\", pattern: \"(?:37)?\\\\d{4}\" },\n  AO: { order: \"AC\" },\n  AQ: { order: \"AC\" },\n  AR: { order: \"AZCS\", pattern: \"[A-HJ-NP-Z]\\\\d{4}[A-Z]{3}\", upperPostal: true },\n  AS: { order: \"ACSZ\", required: \"ACSZ\", state: \"state\", postal: \"zip\", pattern: \"(96799)(?:[ \\\\-](\\\\d{4}))?\" },\n  AT: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{4}\" },\n  AU: { order: \"ACSZ\", required: \"ACSZ\", state: \"state\", locality: \"suburb\", pattern: \"\\\\d{4}\" },\n  AW: { order: \"AC\" },\n  AX: { order: \"AZC\", required: \"ACZ\", pattern: \"22\\\\d{3}\" },\n  AZ: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  BA: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  BB: { order: \"ACSZ\", state: \"parish\", pattern: \"BB\\\\d{5}\" },\n  BD: { order: \"ACZ\", pattern: \"\\\\d{4}\" },\n  BE: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{4}\" },\n  BF: { order: \"AC\" },\n  BG: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  BH: { order: \"ACZ\", pattern: \"(?:^|\\\\b)(?:1[0-2]|[1-9])\\\\d{2}(?:$|\\\\b)\" },\n  BI: { order: \"AC\" },\n  BJ: { order: \"AC\" },\n  BL: { order: \"AZC\", required: \"ACZ\", pattern: \"9[78][01]\\\\d{2}\" },\n  BM: { order: \"ACZ\", pattern: \"[A-Z]{2} ?[A-Z0-9]{2}\" },\n  BN: { order: \"ACZ\", pattern: \"[A-Z]{2} ?\\\\d{4}\" },\n  BO: { order: \"AC\" },\n  BQ: { order: \"AC\" },\n  BR: { order: \"ADCSZ\", required: \"ASCZ\", state: \"state\", sub: \"neighborhood\", pattern: \"\\\\d{5}-?\\\\d{3}\" },\n  BS: { order: \"ACS\", state: \"island\" },\n  BT: { order: \"ACZ\", pattern: \"\\\\d{5}\" },\n  BV: { order: \"AC\" },\n  BW: { order: \"AC\" },\n  BY: { order: \"AZCS\", pattern: \"\\\\d{6}\" },\n  BZ: { order: \"AC\" },\n  CA: { order: \"ACSZ\", required: \"ACSZ\", pattern: \"[ABCEGHJKLMNPRSTVXY]\\\\d[ABCEGHJ-NPRSTV-Z] ?\\\\d[ABCEGHJ-NPRSTV-Z]\\\\d\", upperPostal: true },\n  CC: { order: \"ACSZ\", pattern: \"6799\" },\n  CD: { order: \"AC\" },\n  CF: { order: \"AC\" },\n  CG: { order: \"AC\" },\n  CH: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{4}\" },\n  CI: { order: \"AC\" },\n  CK: { order: \"AC\" },\n  CL: { order: \"AZCS\", pattern: \"\\\\d{7}\" },\n  CM: { order: \"AC\" },\n  CN: { order: \"ZSCDA\", required: \"ACSZ\", sub: \"district\", pattern: \"\\\\d{6}\" },\n  CO: { order: \"ADCSZ\", required: \"AS\", state: \"department\", pattern: \"\\\\d{6}\" },\n  CR: { order: \"ASCZ\", required: \"ACS\", pattern: \"\\\\d{4,5}|\\\\d{3}-\\\\d{4}\" },\n  CU: { order: \"ACSZ\", pattern: \"\\\\d{5}\" },\n  CV: { order: \"AZCS\", state: \"island\", pattern: \"\\\\d{4}\" },\n  CW: { order: \"AC\" },\n  CX: { order: \"ACSZ\", pattern: \"6798\" },\n  CY: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  CZ: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{3} ?\\\\d{2}\" },\n  DE: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{5}\" },\n  DJ: { order: \"AC\" },\n  DK: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{4}\" },\n  DM: { order: \"AC\" },\n  DO: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  DZ: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  EC: { order: \"AZC\", pattern: \"\\\\d{6}\", upperPostal: true },\n  EE: { order: \"AZCS\", required: \"ACZ\", pattern: \"\\\\d{5}\" },\n  EG: { order: \"ACSZ\", pattern: \"\\\\d{7}|\\\\d{5}\" },\n  EH: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  ER: { order: \"AC\" },\n  ES: { order: \"AZCS\", required: \"ACSZ\", pattern: \"\\\\d{5}\" },\n  ET: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  FI: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{5}\" },\n  FJ: { order: \"AC\" },\n  FK: { order: \"ACZ\", required: \"ACZ\", pattern: \"FIQQ 1ZZ\", upperPostal: true },\n  FM: { order: \"ACSZ\", required: \"ACSZ\", state: \"state\", postal: \"zip\", pattern: \"(9694[1-4])(?:[ \\\\-](\\\\d{4}))?\" },\n  FO: { order: \"AZC\", pattern: \"\\\\d{3}\" },\n  FR: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{2} ?\\\\d{3}\" },\n  GA: { order: \"AC\" },\n  GB: { order: \"ACZ\", required: \"ACZ\", locality: \"post_town\", pattern: \"GIR ?0AA|(?:(?:AB|AL|B|BA|BB|BD|BF|BH|BL|BN|BR|BS|BT|BX|CA|CB|CF|CH|CM|CO|CR|CT|CV|CW|DA|DD|DE|DG|DH|DL|DN|DT|DY|E|EC|EH|EN|EX|FK|FY|G|GL|GY|GU|HA|HD|HG|HP|HR|HS|HU|HX|IG|IM|IP|IV|JE|KA|KT|KW|KY|L|LA|LD|LE|LL|LN|LS|LU|M|ME|MK|ML|N|NE|NG|NN|NP|NR|NW|OL|OX|PA|PE|PH|PL|PO|PR|RG|RH|RM|S|SA|SE|SG|SK|SL|SM|SN|SO|SP|SR|SS|ST|SW|SY|TA|TD|TF|TN|TQ|TR|TS|TW|UB|W|WA|WC|WD|WF|WN|WR|WS|WV|YO|ZE)(?:\\\\d[\\\\dA-Z]? ?\\\\d[ABD-HJLN-UW-Z]{2}))|BFPO ?\\\\d{1,4}\", upperPostal: true },\n  GD: { order: \"AC\" },\n  GE: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  GF: { order: \"AZC\", required: \"ACZ\", pattern: \"9[78]3\\\\d{2}\" },\n  GG: { order: \"ACZ\", required: \"ACZ\", pattern: \"GY\\\\d[\\\\dA-Z]? ?\\\\d[ABD-HJLN-UW-Z]{2}\", upperPostal: true },\n  GH: { order: \"AC\" },\n  GI: { order: \"AZ\", required: \"A\", pattern: \"GX11 1AA\" },\n  GL: { order: \"AZC\", required: \"ACZ\", pattern: \"39\\\\d{2}\" },\n  GM: { order: \"AC\" },\n  GN: { order: \"ZAC\", pattern: \"\\\\d{3}\" },\n  GP: { order: \"AZC\", required: \"ACZ\", pattern: \"9[78][01]\\\\d{2}\" },\n  GQ: { order: \"AC\" },\n  GR: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{3} ?\\\\d{2}\" },\n  GS: { order: \"ACZ\", required: \"ACZ\", pattern: \"SIQQ 1ZZ\", upperPostal: true },\n  GT: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  GU: { order: \"ACZ\", required: \"ACZ\", postal: \"zip\", pattern: \"(969(?:[12]\\\\d|3[12]))(?:[ \\\\-](\\\\d{4}))?\" },\n  GW: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  GY: { order: \"AC\" },\n  HK: { order: \"SCA\", required: \"AS\", state: \"area\", locality: \"district\" },\n  HM: { order: \"ACSZ\", pattern: \"\\\\d{4}\" },\n  HN: { order: \"ACSZ\", required: \"ACS\", state: \"department\", pattern: \"\\\\d{5}\" },\n  HR: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  HT: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  HU: { order: \"CAZ\", required: \"ACZ\", pattern: \"\\\\d{4}\" },\n  ID: { order: \"ACSZ\", required: \"AS\", pattern: \"\\\\d{5}\" },\n  IE: { order: \"ADCSZ\", state: \"county\", postal: \"eircode\", sub: \"townland\", pattern: \"[\\\\dA-Z]{3} ?[\\\\dA-Z]{4}\" },\n  IL: { order: \"ACZ\", pattern: \"\\\\d{5}(?:\\\\d{2})?\" },\n  IM: { order: \"ACZ\", required: \"ACZ\", pattern: \"IM\\\\d[\\\\dA-Z]? ?\\\\d[ABD-HJLN-UW-Z]{2}\", upperPostal: true },\n  IN: { order: \"ACZS\", required: \"ACSZ\", state: \"state\", postal: \"pin\", pattern: \"\\\\d{6}\" },\n  IO: { order: \"ACZ\", required: \"ACZ\", pattern: \"BBND 1ZZ\", upperPostal: true },\n  IQ: { order: \"ACSZ\", required: \"ACS\", pattern: \"\\\\d{5}\" },\n  IR: { order: \"SCDAZ\", sub: \"neighborhood\", pattern: \"\\\\d{5}-?\\\\d{5}\" },\n  IS: { order: \"AZC\", pattern: \"\\\\d{3}\" },\n  IT: { order: \"AZCS\", required: \"ACSZ\", pattern: \"\\\\d{5}\" },\n  JE: { order: \"ACZ\", required: \"ACZ\", pattern: \"JE\\\\d[\\\\dA-Z]? ?\\\\d[ABD-HJLN-UW-Z]{2}\", upperPostal: true },\n  JM: { order: \"ACS\", required: \"ACS\", state: \"parish\" },\n  JO: { order: \"ACZ\", pattern: \"\\\\d{5}\" },\n  JP: { order: \"ZSA\", required: \"ASZ\", state: \"prefecture\", pattern: \"\\\\d{3}-?\\\\d{4}\" },\n  KE: { order: \"ACZ\", pattern: \"\\\\d{5}\" },\n  KG: { order: \"AZC\", pattern: \"\\\\d{6}\" },\n  KH: { order: \"ACZ\", pattern: \"\\\\d{5,6}\" },\n  KI: { order: \"ASC\", state: \"island\" },\n  KM: { order: \"AC\" },\n  KN: { order: \"ACS\", required: \"ACS\", state: \"island\" },\n  KP: { order: \"ZSCA\" },\n  KR: { order: \"SCDAZ\", required: \"ACSZ\", state: \"do_si\", sub: \"district\", pattern: \"\\\\d{5}\", upperPostal: true },\n  KW: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  KY: { order: \"ASZ\", required: \"AS\", state: \"island\", pattern: \"KY\\\\d-\\\\d{4}\" },\n  KZ: { order: \"ZSCA\", pattern: \"[A-Z]\\\\d{2}[A-Z0-9]{4}|\\\\d{6}\" },\n  LA: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  LB: { order: \"ACZ\", pattern: \"(?:\\\\d{4})(?: ?(?:\\\\d{4}))?\" },\n  LC: { order: \"AC\" },\n  LI: { order: \"AZC\", required: \"ACZ\", pattern: \"948[5-9]|949[0-8]\" },\n  LK: { order: \"ACZ\", pattern: \"\\\\d{5}\" },\n  LR: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  LS: { order: \"ACZ\", pattern: \"\\\\d{3}\" },\n  LT: { order: \"AZCS\", required: \"ACZ\", pattern: \"\\\\d{5}\" },\n  LU: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{4}\" },\n  LV: { order: \"ASCZ\", required: \"ACZ\", pattern: \"LV-\\\\d{4}\" },\n  LY: { order: \"AC\" },\n  MA: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  MC: { order: \"AZC\", pattern: \"980\\\\d{2}\" },\n  MD: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  ME: { order: \"AZC\", pattern: \"8\\\\d{4}\" },\n  MF: { order: \"AZC\", required: \"ACZ\", pattern: \"9[78][01]\\\\d{2}\" },\n  MG: { order: \"AZC\", pattern: \"\\\\d{3}\" },\n  MH: { order: \"ACSZ\", required: \"ACSZ\", state: \"state\", postal: \"zip\", pattern: \"(969[67]\\\\d)(?:[ \\\\-](\\\\d{4}))?\" },\n  MK: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  ML: { order: \"AC\" },\n  MM: { order: \"ACZ\", pattern: \"\\\\d{5}\" },\n  MN: { order: \"ACSZ\", pattern: \"\\\\d{5}\" },\n  MO: { order: \"A\", required: \"A\" },\n  MP: { order: \"ACSZ\", required: \"ACSZ\", state: \"state\", postal: \"zip\", pattern: \"(9695[012])(?:[ \\\\-](\\\\d{4}))?\" },\n  MQ: { order: \"AZC\", required: \"ACZ\", pattern: \"9[78]2\\\\d{2}\" },\n  MR: { order: \"AC\" },\n  MS: { order: \"AC\" },\n  MT: { order: \"ACZ\", pattern: \"[A-Z]{3} ?\\\\d{2,4}\", upperPostal: true },\n  MU: { order: \"AZC\", pattern: \"\\\\d{3}(?:\\\\d{2}|[A-Z]{2}\\\\d{3})\", upperPostal: true },\n  MV: { order: \"ACZ\", pattern: \"\\\\d{5}\" },\n  MW: { order: \"AC\" },\n  MX: { order: \"ADZCS\", required: \"ACSZ\", state: \"state\", sub: \"neighborhood\", pattern: \"\\\\d{5}\", upperPostal: true },\n  MY: { order: \"ADZCS\", required: \"ACZ\", state: \"state\", sub: \"village_township\", pattern: \"\\\\d{5}\" },\n  MZ: { order: \"AZCS\", pattern: \"\\\\d{4}\" },\n  NA: { order: \"ACZ\", pattern: \"\\\\d{5}\" },\n  NC: { order: \"AZC\", required: \"ACZ\", pattern: \"988\\\\d{2}\" },\n  NE: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  NF: { order: \"ACSZ\", pattern: \"2899\" },\n  NG: { order: \"ADCZS\", state: \"state\", pattern: \"[A-Z]{2}[ -]?(?:0[1-9]|[1-9]\\\\d)[ -]?[A-Z\\\\d]{3}[ -]?[A-Z]{2}[ -]?(?:0[1-9]|[1-9]\\\\d)|\\\\d{6}\", upperPostal: true },\n  NI: { order: \"AZCS\", state: \"department\", pattern: \"\\\\d{5}\" },\n  NL: { order: \"AZC\", required: \"ACZ\", pattern: \"[1-9]\\\\d{3} ?(?:[A-RT-Z][A-Z]|S[BCE-RT-Z])\" },\n  NO: { order: \"AZC\", required: \"ACZ\", locality: \"post_town\", pattern: \"\\\\d{4}\" },\n  NP: { order: \"ACZ\", pattern: \"\\\\d{5}\" },\n  NR: { order: \"AS\", required: \"AS\", state: \"district\" },\n  NU: { order: \"AC\" },\n  NZ: { order: \"ADCZ\", required: \"ACDZ\", pattern: \"\\\\d{4}\" },\n  OM: { order: \"AZC\", pattern: \"(?:PC )?\\\\d{3}\" },\n  PA: { order: \"ACS\" },\n  PE: { order: \"ACZS\", locality: \"district\", pattern: \"(?:LIMA \\\\d{1,2}|CALLAO 0?\\\\d)|[0-2]\\\\d{4}\" },\n  PF: { order: \"AZCS\", required: \"ACSZ\", state: \"island\", pattern: \"987\\\\d{2}\" },\n  PG: { order: \"ACZS\", required: \"ACS\", pattern: \"\\\\d{3}\" },\n  PH: { order: \"ADCZS\", pattern: \"\\\\d{4}\" },\n  PK: { order: \"ADCZ\", pattern: \"\\\\d{5}\" },\n  PL: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{2}-\\\\d{3}\" },\n  PM: { order: \"AZC\", required: \"ACZ\", pattern: \"9[78]5\\\\d{2}\" },\n  PN: { order: \"ACZ\", required: \"ACZ\", pattern: \"PCRN 1ZZ\", upperPostal: true },\n  PR: { order: \"ACZ\", required: \"ACZ\", postal: \"zip\", pattern: \"(00[679]\\\\d{2})(?:[ \\\\-](\\\\d{4}))?\" },\n  PS: { order: \"AC\" },\n  PT: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{4}-\\\\d{3}\" },\n  PW: { order: \"ACSZ\", required: \"ACSZ\", state: \"state\", postal: \"zip\", pattern: \"(969(?:39|40))(?:[ \\\\-](\\\\d{4}))?\" },\n  PY: { order: \"AZC\", pattern: \"\\\\d{6}\" },\n  QA: { order: \"AC\" },\n  RE: { order: \"AZC\", required: \"ACZ\", pattern: \"9[78]4\\\\d{2}\" },\n  RO: { order: \"AZSC\", required: \"ACZ\", pattern: \"\\\\d{6}\" },\n  RS: { order: \"AZC\", pattern: \"\\\\d{5,6}\" },\n  RU: { order: \"ACSZ\", required: \"ACSZ\", state: \"oblast\", pattern: \"\\\\d{6}\" },\n  RW: { order: \"AC\" },\n  SA: { order: \"ACZ\", pattern: \"\\\\d{5}\" },\n  SB: { order: \"AC\" },\n  SC: { order: \"ACS\", state: \"island\" },\n  SD: { order: \"ACZ\", locality: \"district\", pattern: \"\\\\d{5}\" },\n  SE: { order: \"AZC\", required: \"ACZ\", locality: \"post_town\", pattern: \"\\\\d{3} ?\\\\d{2}\" },\n  SG: { order: \"AZ\", required: \"AZ\", pattern: \"\\\\d{6}\" },\n  SH: { order: \"ACZ\", required: \"ACZ\", pattern: \"(?:ASCN|STHL) 1ZZ\", upperPostal: true },\n  SI: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  SJ: { order: \"AZC\", required: \"ACZ\", locality: \"post_town\", pattern: \"\\\\d{4}\" },\n  SK: { order: \"AZC\", required: \"ACZ\", pattern: \"\\\\d{3} ?\\\\d{2}\" },\n  SL: { order: \"AC\" },\n  SM: { order: \"AZC\", required: \"AZ\", pattern: \"4789\\\\d\" },\n  SN: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  SO: { order: \"ACSZ\", required: \"ACS\", pattern: \"[A-Z]{2} ?\\\\d{5}\" },\n  SR: { order: \"ACS\" },\n  SS: { order: \"AC\" },\n  ST: { order: \"AC\" },\n  SV: { order: \"AZCS\", required: \"ACS\", pattern: \"[1-3][1-7][0-2]\\\\d\", upperPostal: true },\n  SX: { order: \"AC\" },\n  SY: { order: \"AC\", locality: \"district\" },\n  SZ: { order: \"ACZ\", pattern: \"[HLMS]\\\\d{3}\", upperPostal: true },\n  TA: { order: \"ACZ\", pattern: \"TDCU 1ZZ\" },\n  TC: { order: \"ACZ\", required: \"ACZ\", pattern: \"TKCA 1ZZ\", upperPostal: true },\n  TD: { order: \"AC\" },\n  TF: { order: \"AC\" },\n  TG: { order: \"AC\" },\n  TH: { order: \"ADCSZ\", pattern: \"\\\\d{5}\" },\n  TJ: { order: \"AZC\", pattern: \"\\\\d{6}\" },\n  TK: { order: \"AC\" },\n  TL: { order: \"AC\" },\n  TM: { order: \"AZC\", pattern: \"\\\\d{6}\" },\n  TN: { order: \"AZC\", pattern: \"\\\\d{4}\" },\n  TO: { order: \"AC\" },\n  TR: { order: \"AZCS\", required: \"ACZ\", locality: \"district\", pattern: \"\\\\d{5}\" },\n  TT: { order: \"ACZ\", pattern: \"\\\\d{6}\" },\n  TV: { order: \"ACS\", state: \"island\" },\n  TW: { order: \"ZSCA\", required: \"ACSZ\", state: \"county\", locality: \"district\", pattern: \"\\\\d{3}(?:\\\\d{2,3})?\" },\n  TZ: { order: \"AZC\", pattern: \"\\\\d{4,5}\" },\n  UA: { order: \"ACSZ\", required: \"ACZ\", state: \"oblast\", pattern: \"\\\\d{5}\" },\n  UG: { order: \"AC\" },\n  UM: { order: \"ACSZ\", required: \"ACS\", state: \"state\", postal: \"zip\", pattern: \"96898\" },\n  US: { order: \"ACSZ\", required: \"ACSZ\", state: \"state\", postal: \"zip\", pattern: \"(\\\\d{5})(?:[ \\\\-](\\\\d{4}))?\" },\n  UY: { order: \"AZCS\", pattern: \"\\\\d{5}\" },\n  UZ: { order: \"AZCS\", pattern: \"\\\\d{6}\" },\n  VA: { order: \"AZC\", pattern: \"00120\" },\n  VC: { order: \"ACZ\", pattern: \"VC\\\\d{4}\" },\n  VE: { order: \"ACZS\", required: \"ACS\", state: \"state\", pattern: \"\\\\d{4}\" },\n  VG: { order: \"ACZ\", required: \"A\", pattern: \"VG\\\\d{4}\" },\n  VI: { order: \"ACSZ\", required: \"ACSZ\", state: \"state\", postal: \"zip\", pattern: \"(008(?:(?:[0-4]\\\\d)|(?:5[01])))(?:[ \\\\-](\\\\d{4}))?\" },\n  VN: { order: \"ACSZ\", required: \"AS\", pattern: \"\\\\d{5}\\\\d?\" },\n  VU: { order: \"AC\" },\n  WF: { order: \"AZC\", required: \"ACZ\", pattern: \"986\\\\d{2}\" },\n  WS: { order: \"AC\" },\n  XK: { order: \"AZC\", pattern: \"[1-7]\\\\d{4}\" },\n  YE: { order: \"AC\" },\n  YT: { order: \"AZC\", required: \"ACZ\", pattern: \"976\\\\d{2}\" },\n  ZA: { order: \"ADCZ\", required: \"ACZ\", pattern: \"\\\\d{4}\" },\n  ZM: { order: \"AZC\", pattern: \"\\\\d{5}\" },\n  ZW: { order: \"AC\" },\n}\n\n/**\n * The English word for each field name upstream uses, plus the fields that are the same everywhere.\n *\n * Keyed by name *type* rather than by country so that one entry covers every country that calls the\n * field that, and so a caller translating the form overrides a dozen countries at once by passing\n * `labels={{ prefecture: \"都道府県\" }}`. `district` and `suburb` each appear upstream as both an\n * administrative-area name and a locality name; one entry serves both because the word is the same.\n */\nexport const FIELD_LABELS: Record<string, string> = {\n  // Administrative area, as the twelve countries' worth of variants upstream distinguishes.\n  province: \"Province\",\n  state: \"State\",\n  county: \"County\",\n  parish: \"Parish\",\n  island: \"Island\",\n  department: \"Department\",\n  emirate: \"Emirate\",\n  prefecture: \"Prefecture\",\n  do_si: \"Do / Si\",\n  district: \"District\",\n  area: \"Area\",\n  oblast: \"Oblast\",\n  // Locality.\n  city: \"City\",\n  post_town: \"Post town\",\n  suburb: \"Suburb\",\n  // Postal code.\n  postal: \"Postal code\",\n  zip: \"ZIP code\",\n  eircode: \"Eircode\",\n  pin: \"PIN code\",\n  // Dependent locality, the line between the street and the town.\n  neighborhood: \"Neighborhood\",\n  townland: \"Townland\",\n  village_township: \"Village / township\",\n  // The fields whose name does not vary by country.\n  country: \"Country\",\n  addressLine1: \"Address\",\n  addressLine2: \"Address line 2\",\n  addressLine3: \"Address line 3\",\n}\n\n/** The letters `order` and `required` are written in, as the fields they stand for. */\nconst LETTER_FIELDS: Record<string, AddressField> = {\n  D: \"dependentLocality\",\n  C: \"locality\",\n  S: \"administrativeArea\",\n  Z: \"postalCode\",\n}\n\nconst ADDRESS_LINES: AddressField[] = [\"addressLine1\", \"addressLine2\", \"addressLine3\"]\n\nexport type ResolvedAddressRule = {\n  country: string\n  /** Address fields in this country's order, as letters from `ADCSZ`. */\n  order: string\n  /** The subset of `order` that may not be left empty. */\n  required: string\n  labelTypes: { state: string; locality: string; postal: string; sub: string }\n  /** The postal code's shape, unanchored, exactly as upstream writes it. */\n  pattern?: string\n  /** Whether this country writes its postal code in capitals. */\n  upperPostal: boolean\n}\n\n/**\n * The rules for a country code, falling back to the default for one that is not in the table.\n *\n * Unknown codes resolve rather than throw, because a country list is a moving target and a form\n * that renders nothing is worse than one that asks for a street and a city. Case is normalised:\n * `autocomplete=\"country\"` can hand back a lower-case code.\n */\nexport function rulesFor(country: string): ResolvedAddressRule {\n  const code = (country ?? \"\").trim().toUpperCase()\n  const rule = COUNTRY_RULES[code] ?? { order: DEFAULT_ORDER }\n  return {\n    country: code,\n    order: rule.order,\n    required: rule.required ?? DEFAULT_REQUIRED,\n    labelTypes: {\n      state: rule.state ?? DEFAULT_LABEL_TYPES.state,\n      locality: rule.locality ?? DEFAULT_LABEL_TYPES.locality,\n      postal: rule.postal ?? DEFAULT_LABEL_TYPES.postal,\n      sub: rule.sub ?? DEFAULT_LABEL_TYPES.sub,\n    },\n    pattern: rule.pattern,\n    upperPostal: rule.upperPostal === true,\n  }\n}\n\nexport type AddressFieldSpec = {\n  field: AddressField\n  label: string\n  required: boolean\n  /** The HTML autofill token, already carrying any section prefix. */\n  autoComplete: string\n  /** `numeric` only where the postal code cannot contain a letter. */\n  inputMode?: \"numeric\"\n  /** The postal code's shape, unanchored. Only ever set on `postalCode`. */\n  pattern?: string\n  /** Whether this field's value is conventionally written in capitals. */\n  upper: boolean\n}\n\nexport type AddressFieldsOptions = {\n  /** How many street-address lines to render, 1 to 3. Defaults to 2. */\n  addressLines?: 1 | 2 | 3\n  /** Overrides for `FIELD_LABELS`, by name type or by field name. */\n  labels?: Partial<Record<string, string>>\n  /**\n   * An autofill section, prefixed to every token: `\"shipping\"`, `\"billing\"`, or `\"section-<name>\"`.\n   *\n   * Without it, a page with a shipping *and* a billing address gives the browser two fields both\n   * claiming to be `postal-code`, and it fills one of them — this is the whole reason the HTML\n   * autofill grammar has a section prefix.\n   */\n  autoCompleteSection?: string\n}\n\n/**\n * Whether a postal code pattern can match something with a letter in it.\n *\n * Used only to pick the mobile keyboard, so a wrong answer costs a keyboard and not a value. The\n * test is deliberately crude: strip the escapes that *contain* letters without meaning one (`\\d`,\n * `\\s`) and see whether a letter survives. Japan's `\\d{3}-?\\d{4}` has none, the UK's has a hundred.\n */\nfunction isDigitsOnly(pattern: string): boolean {\n  return !/[A-Za-z]/.test(pattern.replace(/\\\\[dswDSWbB]/g, \"\"))\n}\n\n/**\n * The fields to render for a country, in order, with their labels, required flags and autofill\n * tokens.\n *\n * Exported because the layout is sometimes the caller's: a checkout that wants the postal code and\n * the city on one row, or a read-only summary that wants the same labels the form used, can read\n * the specs and lay them out itself rather than reimplementing the table.\n */\nexport function fieldsFor(country: string, options: AddressFieldsOptions = {}): AddressFieldSpec[] {\n  const { addressLines = 2, labels, autoCompleteSection } = options\n  const rule = rulesFor(country)\n  const label = (key: string) => labels?.[key] ?? FIELD_LABELS[key] ?? key\n  const token = (name: string) =>\n    autoCompleteSection ? `${autoCompleteSection.trim()} ${name}` : name\n  const specs: AddressFieldSpec[] = []\n\n  for (const letter of rule.order) {\n    if (letter === \"A\") {\n      const count = Math.min(Math.max(addressLines, 1), 3)\n      for (let i = 0; i < count; i += 1) {\n        specs.push({\n          field: ADDRESS_LINES[i],\n          label: label(ADDRESS_LINES[i]),\n          // Only the first line is ever required: the second is \"Apartment 4B\", and a country that\n          // requires an address requires a street, not two lines of one.\n          required: i === 0 && rule.required.includes(\"A\"),\n          // A single line is the whole street address; several are its numbered parts. Getting this\n          // wrong is the difference between the browser filling one field and filling none.\n          autoComplete: token(count === 1 ? \"street-address\" : `address-line${i + 1}`),\n          upper: false,\n        })\n      }\n      continue\n    }\n    const field = LETTER_FIELDS[letter]\n    if (!field) continue\n    if (field === \"postalCode\") {\n      specs.push({\n        field,\n        label: label(rule.labelTypes.postal),\n        required: rule.required.includes(\"Z\"),\n        autoComplete: token(\"postal-code\"),\n        inputMode: rule.pattern && isDigitsOnly(rule.pattern) ? \"numeric\" : undefined,\n        pattern: rule.pattern,\n        upper: rule.upperPostal,\n      })\n      continue\n    }\n    specs.push({\n      field,\n      label: label(\n        field === \"locality\"\n          ? rule.labelTypes.locality\n          : field === \"administrativeArea\"\n            ? rule.labelTypes.state\n            : rule.labelTypes.sub\n      ),\n      required: rule.required.includes(letter),\n      // The three levels below the country, outermost first. `address-level1` is the state even in\n      // the countries that do not call it one, and `address-level3` is the line above the town.\n      autoComplete: token(\n        field === \"locality\"\n          ? \"address-level2\"\n          : field === \"administrativeArea\"\n            ? \"address-level1\"\n            : \"address-level3\"\n      ),\n      upper: false,\n    })\n  }\n  return specs\n}\n\n/**\n * The anchored regular expression a country's postal code must match, or null where it has none.\n *\n * The wrapping `(?:…)` is not cosmetic. Several patterns upstream are a top-level alternation — the\n * UK's is `GIR ?0AA|(?:AB|AL|…)…|BFPO ?\\d{1,4}` — so `^` and `$` written straight onto it would\n * anchor the first and last branch only, and `\"nonsense GIR 0AA nonsense\"` would pass. The group is\n * what makes the anchors apply to the whole thing.\n */\nexport function postalCodePattern(country: string): RegExp | null {\n  const { pattern } = rulesFor(country)\n  if (!pattern) return null\n  try {\n    return new RegExp(`^(?:${pattern})$`)\n  } catch {\n    return null\n  }\n}\n\n/**\n * A postal code tidied the way the country writes it: trimmed, inner runs of space collapsed, and\n * capitalised only where upstream says that country capitalises it.\n *\n * Ireland is the case that explains the caveat: an Eircode is alphanumeric and is printed in\n * capitals, but upstream does not mark it `upper`, so this leaves `d02 af30` alone. Validation\n * upper-cases before matching regardless, so the value is accepted either way — what is not done\n * is overriding upstream on how it is written.\n */\nexport function normalizePostalCode(country: string, raw: string): string {\n  const collapsed = raw.trim().replace(/\\s+/g, \" \")\n  return rulesFor(country).upperPostal ? collapsed.toUpperCase() : collapsed\n}\n\n/**\n * Whether a postal code fits its country's shape. Empty is valid here — emptiness is the required\n * check's business, and a field that is both optional and malformed-when-empty cannot be left\n * alone.\n */\nexport function isValidPostalCode(country: string, raw: string): boolean {\n  const value = raw.trim().replace(/\\s+/g, \" \")\n  if (value === \"\") return true\n  const pattern = postalCodePattern(country)\n  if (!pattern) return true\n  // Matched in capitals because the patterns are written in them and postal codes are not\n  // case-sensitive anywhere; `sw1a 1aa` is a London postcode however it was typed.\n  return pattern.test(value.toUpperCase())\n}\n\nexport type AddressMessages = {\n  required?: (label: string) => string\n  invalid?: (label: string) => string\n}\n\nconst DEFAULT_MESSAGES: Required<AddressMessages> = {\n  required: (label) => `${label} is required`,\n  invalid: (label) => `Enter a valid ${label}`,\n}\n\n/** A blank address for a country, ready to put in state. */\nexport function emptyAddress(country = \"\"): AddressValue {\n  return {\n    country,\n    addressLine1: \"\",\n    addressLine2: \"\",\n    addressLine3: \"\",\n    dependentLocality: \"\",\n    locality: \"\",\n    administrativeArea: \"\",\n    postalCode: \"\",\n  }\n}\n\n/**\n * The problems with an address, by field, empty when there are none.\n *\n * Only the fields the country actually uses are checked: a stale `administrativeArea` left over\n * from a different country is not an error here, because changing the country clears it. Exported\n * so a submit handler runs exactly what the fields showed on blur rather than a second opinion.\n */\nexport function validateAddress(\n  value: AddressValue,\n  options: AddressFieldsOptions & { messages?: AddressMessages } = {}\n): Partial<Record<AddressField, string>> {\n  const messages = { ...DEFAULT_MESSAGES, ...options.messages }\n  const errors: Partial<Record<AddressField, string>> = {}\n  for (const spec of fieldsFor(value.country, options)) {\n    const raw = value[spec.field] ?? \"\"\n    if (spec.required && raw.trim() === \"\") {\n      errors[spec.field] = messages.required(spec.label)\n      continue\n    }\n    if (spec.field === \"postalCode\" && !isValidPostalCode(value.country, raw)) {\n      errors[spec.field] = messages.invalid(spec.label)\n    }\n  }\n  return errors\n}\n\nconst ADDRESS_FIELDS: AddressField[] = [\n  ...ADDRESS_LINES,\n  \"dependentLocality\",\n  \"locality\",\n  \"administrativeArea\",\n  \"postalCode\",\n]\n\n/** Whether two addresses agree on every field, so a controlled re-render is not a change. */\nfunction sameAddress(a: AddressValue, b: AddressValue): boolean {\n  if (a.country !== b.country) return false\n  return ADDRESS_FIELDS.every((field) => (a[field] ?? \"\") === (b[field] ?? \"\"))\n}\n\n/** Fills in whatever a caller left out, so the internal value always has every field. */\nfunction completeAddress(partial: Partial<AddressValue> | undefined): AddressValue {\n  return { ...emptyAddress(), ...partial } as AddressValue\n}\n\nexport interface AddressInputProps {\n  /** The address, when the parent owns it. Every field should be present; missing ones read empty. */\n  value?: AddressValue\n  defaultValue?: Partial<AddressValue>\n  onChange?: (value: AddressValue) => void\n  /** How many street-address lines to render, 1 to 3. Defaults to 2. */\n  addressLines?: 1 | 2 | 3\n  /** The countries to offer. Defaults to every country `country-select` knows. */\n  countries?: readonly string[]\n  /** Language for the country names. Left out, the runtime's own, resolved after mount. */\n  locale?: string\n  /** Overrides for `FIELD_LABELS`, by name type (`prefecture`) or field name (`addressLine1`). */\n  labels?: Partial<Record<string, string>>\n  messages?: AddressMessages\n  /** An autofill section prefix: `\"shipping\"`, `\"billing\"`, `\"section-<name>\"`. */\n  autoCompleteSection?: string\n  /** Turns the administrative area into a select — pass the subdivisions you have. */\n  administrativeAreaOptions?: readonly { value: string; label: string }[]\n  /** Show every error at once, not only for fields that have been visited. For submit. */\n  showErrors?: boolean\n  /** An accessible name for the group of fields. Defaults to \"Address\". */\n  legend?: string\n  disabled?: boolean\n  /** Prefix for each input's `name`, so the address posts with a plain form. */\n  namePrefix?: string\n  id?: string\n  className?: string\n}\n\n/**\n * Renders the country's own address fields, in its own order, with its own labels.\n *\n * The country comes first regardless of where that country writes it, because it decides what the\n * rest of the form is: asking for it last means re-labelling and re-ordering fields the reader has\n * already filled in. It is a native `<select>` rather than this registry's `country-select`\n * deliberately — a custom combobox cannot be filled by the browser, and `autocomplete=\"country\"` on\n * the field that determines every other field is worth more here than a searchable list. The\n * country *names* still come from `country-select`, so the spelling matches wherever both appear.\n */\nexport const AddressInput = React.forwardRef<HTMLDivElement, AddressInputProps>(\n  function AddressInput(\n    {\n      value,\n      defaultValue,\n      onChange,\n      addressLines = 2,\n      countries,\n      locale,\n      labels,\n      messages,\n      autoCompleteSection,\n      administrativeAreaOptions,\n      showErrors = false,\n      legend,\n      disabled = false,\n      namePrefix,\n      id,\n      className,\n    },\n    forwardedRef\n  ) {\n    const isControlled = value !== undefined\n    const [fields, setFields] = React.useState<AddressValue>(() =>\n      completeAddress(isControlled ? value : defaultValue)\n    )\n    const [touched, setTouched] = React.useState<Partial<Record<AddressField, boolean>>>({})\n\n    const fieldsRef = React.useRef(fields)\n    fieldsRef.current = fields\n\n    // Re-seed from the prop only when it disagrees with what is on screen. A parent that rebuilds\n    // the object on every render still passes an equal address, and echoing that back would reset\n    // the field being typed in; comparing by field rather than by identity is what makes a\n    // controlled address typable at all.\n    React.useEffect(() => {\n      // `value === undefined` is exactly `!isControlled`, so this is the whole guard — naming both\n      // read as two checks and was one, which is how a mutation of either survived the suite.\n      if (value === undefined) return\n      const next = completeAddress(value)\n      if (!sameAddress(next, fieldsRef.current)) setFields(next)\n    }, [isControlled, value])\n\n    const [mounted, setMounted] = React.useState(false)\n    React.useEffect(() => {\n      setMounted(true)\n    }, [])\n    // Country names are resolved after mount unless the caller pinned the language. The server's\n    // locale is the server's, so `Intl.DisplayNames(undefined)` renders a different word on each\n    // side of hydration; until then the options show their codes — present, correct, submittable.\n    const namesReady = mounted || locale !== undefined\n\n    const reactId = React.useId()\n    const base = id ?? reactId\n    const fieldId = (field: string) => `${base}-${field}`\n    const errorId = (field: string) => `${base}-${field}-error`\n    const legendId = `${base}-legend`\n\n    const specs = React.useMemo(\n      () => fieldsFor(fields.country, { addressLines, labels, autoCompleteSection }),\n      [fields.country, addressLines, labels, autoCompleteSection]\n    )\n\n    const errors = React.useMemo(\n      () => validateAddress(fields, { addressLines, labels, autoCompleteSection, messages }),\n      [fields, addressLines, labels, autoCompleteSection, messages]\n    )\n\n    const countryLabel = labels?.country ?? FIELD_LABELS.country\n    const options = React.useMemo(() => {\n      const list = countries ?? COUNTRY_CODES\n      if (!namesReady) return list.map((code) => ({ code, name: code }))\n      const named = list.map((code) => ({ code, name: getCountryName(code, locale) }))\n      // Sorted through a collator rather than by code point, which is the difference between a\n      // usable list and a broken one: a plain sort drops every country whose name starts with an\n      // accent — Åland Islands, Österreich — below Zimbabwe, where nobody scrolls.\n      //\n      // Constructed defensively because a malformed `locale` prop makes the constructor throw, and\n      // an unordered list is a far smaller failure than a form that will not render at all.\n      try {\n        const collator = new Intl.Collator(locale)\n        return named.sort((a, b) => collator.compare(a.name, b.name))\n      } catch {\n        return named\n      }\n    }, [countries, namesReady, locale])\n\n    // One commit path, and it always writes the local state — the value carries every field, so a\n    // half-filled address round-trips through a controlled parent without losing anything.\n    function commit(next: AddressValue) {\n      setFields(next)\n      onChange?.(next)\n    }\n\n    function setField(field: AddressField, next: string) {\n      commit({ ...fields, [field]: next })\n    }\n\n    /**\n     * Changing the country clears the fields the new one does not have.\n     *\n     * The alternative — keeping them so switching back restores them — means the value carries a\n     * US state while the address is in Hong Kong, and that is what eventually gets submitted. The\n     * fields that survive are the ones both countries use, which is the common case of correcting\n     * the country after the browser guessed wrong.\n     */\n    function changeCountry(nextCountry: string) {\n      const keep = new Set(\n        fieldsFor(nextCountry, { addressLines, labels, autoCompleteSection }).map((s) => s.field)\n      )\n      const next = emptyAddress(nextCountry)\n      for (const field of ADDRESS_FIELDS) {\n        if (keep.has(field)) next[field] = fields[field]\n      }\n      setTouched({})\n      commit(next)\n    }\n\n    function blur(spec: AddressFieldSpec) {\n      setTouched((t) => ({ ...t, [spec.field]: true }))\n      if (spec.field !== \"postalCode\") return\n      const tidied = normalizePostalCode(fields.country, fields.postalCode)\n      if (tidied !== fields.postalCode) commit({ ...fields, postalCode: tidied })\n    }\n\n    return (\n      <div\n        ref={forwardedRef}\n        role=\"group\"\n        aria-labelledby={legend ? legendId : undefined}\n        aria-label={legend ? undefined : \"Address\"}\n        className={cn(\"flex flex-col gap-4\", className)}\n      >\n        {legend ? (\n          <span id={legendId} className=\"text-sm font-medium\">\n            {legend}\n          </span>\n        ) : null}\n\n        <div className=\"flex flex-col gap-1.5\">\n          <label htmlFor={fieldId(\"country\")} className=\"text-sm font-medium\">\n            {countryLabel}\n          </label>\n          <select\n            id={fieldId(\"country\")}\n            name={namePrefix ? `${namePrefix}.country` : undefined}\n            value={fields.country}\n            onChange={(event) => changeCountry(event.target.value)}\n            disabled={disabled}\n            autoComplete={\n              autoCompleteSection ? `${autoCompleteSection.trim()} country` : \"country\"\n            }\n            aria-required={true}\n            className={cn(\n              \"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors\",\n              \"focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\",\n              \"disabled:cursor-not-allowed disabled:opacity-50\"\n            )}\n          >\n            <option value=\"\">{`Select a ${countryLabel.toLowerCase()}`}</option>\n            {options.map((option) => (\n              <option key={option.code} value={option.code}>\n                {option.name}\n              </option>\n            ))}\n          </select>\n        </div>\n\n        {specs.map((spec) => {\n          const message = errors[spec.field]\n          const show = Boolean(message) && (showErrors || touched[spec.field] === true)\n          const isArea = spec.field === \"administrativeArea\"\n          const shared = {\n            id: fieldId(spec.field),\n            name: namePrefix ? `${namePrefix}.${spec.field}` : undefined,\n            value: fields[spec.field] ?? \"\",\n            disabled,\n            autoComplete: spec.autoComplete,\n            \"aria-required\": spec.required,\n            \"aria-invalid\": show ? true : undefined,\n            \"aria-describedby\": show ? errorId(spec.field) : undefined,\n            onBlur: () => blur(spec),\n            className: cn(\n              \"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors\",\n              \"placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\",\n              \"disabled:cursor-not-allowed disabled:opacity-50\",\n              show && \"border-destructive focus-visible:ring-destructive\"\n            ),\n          }\n          return (\n            <div key={spec.field} className=\"flex flex-col gap-1.5\">\n              <label htmlFor={fieldId(spec.field)} className=\"text-sm font-medium\">\n                {spec.label}\n                {spec.required ? null : (\n                  <span className=\"ml-1 font-normal text-muted-foreground\">(optional)</span>\n                )}\n              </label>\n              {isArea && administrativeAreaOptions ? (\n                <select\n                  {...shared}\n                  onChange={(event) => setField(spec.field, event.target.value)}\n                >\n                  <option value=\"\">{`Select a ${spec.label.toLowerCase()}`}</option>\n                  {administrativeAreaOptions.map((option) => (\n                    <option key={option.value} value={option.value}>\n                      {option.label}\n                    </option>\n                  ))}\n                </select>\n              ) : (\n                <input\n                  {...shared}\n                  type=\"text\"\n                  inputMode={spec.inputMode}\n                  autoCapitalize={spec.upper ? \"characters\" : undefined}\n                  spellCheck={false}\n                  onChange={(event) => setField(spec.field, event.target.value)}\n                />\n              )}\n              {show ? (\n                <p id={errorId(spec.field)} role=\"alert\" className=\"text-sm text-destructive\">\n                  {message}\n                </p>\n              ) : null}\n            </div>\n          )\n        })}\n      </div>\n    )\n  }\n)\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui",
  "docs": "Install any pulld component by name: add \"@pulld\": \"https://pulld.pages.dev/r/{name}.json\" to the registries block in components.json, then `npx shadcn add @pulld/<name>`. All 149 components: https://pulld.pages.dev/?utm_source=cli"
}
