{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "ip-input",
  "title": "IP Input",
  "description": "One box for an IP address or a CIDR block that normalises what it is given to the single spelling the RFCs allow, says what a prefix is worth in addresses, and refuses the two IPv4 forms whose readings disagree instead of picking one. Reach for it wherever a person types an address rather than a program emitting one: a firewall rule or allowlist entry, an SSH or VPN access list, subnet planning, a DNS A or AAAA record, the upstream for a proxy or load balancer, a monitoring or scan target, a BGP or route-table entry, a rate-limit or geo-block exception, a Kubernetes or security-group CIDR, and the search box where somebody pastes the source address out of a log. Common asks it answers: \"ip input react\", \"ip address input component\", \"shadcn ip input\", \"cidr input react\", \"subnet input component\", \"ipv4 input validation react\", \"ipv6 input react\", \"validate ip address javascript\", \"ip address regex javascript\", \"cidr validation javascript\", \"parse cidr javascript\", \"subnet mask calculator javascript\", \"how many hosts in a /24\", \"how many addresses in a /16\", \"prefix length to number of hosts\", \"/31 usable addresses\", \"ipv6 /64 how many addresses\", \"normalize ipv6 address javascript\", \"rfc 5952 canonical ipv6\", \"ipv6 compare two addresses javascript\", \"are these two ipv6 addresses the same\", \"ipv6 leading zeros equal\", \"ipv4 mapped ipv6 ::ffff\", \"::ffff:192.0.2.1 validation\", \"ip with leading zero octal\", \"010.0.0.1 is 8.0.0.1\", \"ssrf leading zero bypass\", \"127.1 is 127.0.0.1\", \"why does 127.1 work in browser\", \"net.isIPv4 rejects 127.1\", \"inet_aton short form javascript\", \"2130706433 ip address\", \"0x7f000001 ip\", \"cidr host bits set error\", \"192.168.1.5/24 is not a network\", \"ipv6 zone id fe80::1%eth0\", \"netmask from prefix length javascript\", \"0.0.0.0/0 means all addresses\", \"ip subnet form validation\", \"allowlist ip entry form\", \"firewall rule input component\", \"IP 入力 react\", \"IPアドレス 入力 コンポーネント\", \"CIDR 入力 バリデーション\", \"サブネット 台数 計算\", \"IPv6 正規化 javascript\", \"先頭ゼロ IP 8進数\", \"ホストビット CIDR エラー\". **A text box with `/^(\\\\d{1,3}\\\\.){3}\\\\d{1,3}$/` in front of it is wrong about four separate things, and every one of them has been a CVE class or an outage.** They are: which strings are addresses, whether two strings are the same address, how big a prefix is, and what an empty box means. **The two IPv4 spellings whose readings disagree are refused rather than resolved, and the field says who disagrees.** Measured, the WHATWG URL parser — which is to say every browser, and curl — reads `127.1`, `127.0.1`, `2130706433`, `0x7f.1`, `0x7f000001` and `0177.0.0.1` all as `127.0.0.1`, and `192.168.257` as `192.168.1.1`, while `net.isIPv4` in the very same Node process calls every one of them invalid. \"Is this a valid address\" has two answers inside one runtime, so a field that quietly takes either one is choosing which tool downstream gets surprised; each is reported with its expansion named, on a control that puts it in the box when the reader says so. **A leading zero is the dangerous one, because the two readings are different hosts rather than two spellings of one.** Measured: `new URL(\"http://010.0.0.1\").hostname` is `8.0.0.1`, not `10.0.0.1` — a leading zero makes the octet octal — and `0177.0.0.1` is `127.0.0.1` where a zero-stripper reads `177.0.0.1`. An allowlist that stores the text and a parser that resolves it octal then disagree about who is allowed in, which is exactly the shape of the leading-zero SSRF bypass. The field names both readings and refuses, because offering one would be picking. The 8 and the 9 are a separate case worth knowing: `09.0.0.1` and `08.0.0.1` are not URLs at all (measured), since 8 and 9 are not octal digits. **Identity is decided on the bytes, because the strings lie.** Each of these pairs is two valid spellings of one address, and `===` says they differ: `2001:db8::1` against `2001:0db8:0000:0000:0000:0000:0000:0001`, `::1` against `0:0:0:0:0:0:0:1`, `2001:DB8::1` against `2001:db8::1`, and `::ffff:192.0.2.1` against `::ffff:c000:0201`. A duplicate check written on the text of an allowlist misses all four, which is how one host gets added twice and removed once. Everything is canonicalised per RFC 5952 — lowercase, leading zeros dropped, the longest run of zero groups collapsed and the leftmost of two equal runs (§4.2.3), a single zero group never collapsed (§4.2.2) — and `sameAddress` compares bytes, with the zone counted because `fe80::1%eth0` and `fe80::1%eth1` are the same bytes on different links (RFC 4007). **The dotted form of a mapped address is kept, and this is the one place the component disagrees with the browser on purpose.** Measured, `new URL(\"http://[::ffff:192.0.2.1]\").hostname` is `[::ffff:c000:201]`: the WHATWG serialiser has no RFC 5952 §5 special case. Both are correct; only one is a string somebody reviewing a firewall rule can recognise. **A prefix written on a mapped address is flagged, and the error is always the same factor.** `::ffff:10.0.0.0/8` is a legal IPv6 block covering 2^120 addresses; the IPv4 `10.0.0.0/8` that was meant is `/104` here, covering 2^24. The ratio does not depend on the prefix — 2^(128−p) over 2^(32−p) is 2^96 for every p — so the mistake is always 79,228,162,514,264,337,593,543,950,336 times, about 7.9e28. **The netmask is assembled a byte at a time, because the one-line version is wrong about the most consequential prefix there is.** Measured, `(0xFFFFFFFF << 32) >>> 0` is `4294967295`, not 0: JavaScript takes a shift count modulo 32, so `prefix` 0 shifts by nothing and `0.0.0.0/0` comes out with a `/32` mask — a firewall UI reading \"the entire internet\" as \"one host\". Eight-bit shifts cannot reach 32, so built per byte the failure mode does not exist rather than being guarded against. **The usable count is not \"minus two\", and that formula produces impossible numbers at both ends of the one family it belongs to.** Measured: `2 ** (32 - 31) - 2` is 0 and `2 ** (32 - 32) - 2` is −1, so it claims a point-to-point link has no usable addresses and a single host has minus one. RFC 3021 makes a /31 a two-address link with both ends usable and a /32 one host. On IPv6 the subtraction is wrong at every prefix, because **there is no broadcast address in IPv6 at all** (RFC 4291 §2.7); what a subnet reserves is the one Subnet-Router anycast address (§2.6.1), and a /127 inter-router link does not reserve even that (RFC 6164). One formula for both families is wrong about one of them everywhere. **The counts are `bigint`, because a /64 is not a Number.** Measured, `2 ** 64` evaluates to 18446744073709552000 where the true value is 18446744073709551616, and `2 ** 64 - 1 === 2 ** 64` is `true` — the commonest IPv6 subnet and the whole of it minus one address are one figure in float64. `Intl.NumberFormat` formats a `bigint` exactly (2^128 comes out as all 39 digits), so nothing has to be narrowed to be shown. **Host bits set in a CIDR is reported with both repairs and neither applied.** `192.168.1.5/24` is a host inside a block, not the block; rounding it down to `192.168.1.0/24` turns a rule about one machine into a rule about 256, which is the distinction the reader was writing the rule to express, so the field offers the network and leaves the /32 alone. **An embedded IPv4 address only reads at the end.** A dotted quad is two groups wherever it sits, so a parser that only counts groups accepts `1.2.3.4::1` and invents an address out of it; measured, `net.isIPv6(\"1.2.3.4::1\")` is `false`, and so is this. **And an empty box is not an address.** Empty parses to nothing and unreadable text parses to a refusal, kept apart because `0.0.0.0` with a `/0` is every host on the internet and a blank allowlist row that posts it is the single most expensive thing this component could do. Accessibility and form behaviour: the field is one `role=\"group\"` with a label, the box is `type=\"text\"` because a number input would discard every character that makes an address, one polite `role=\"status\"` line carries the verdict through `aria-describedby` (two live regions race each other and neither gets read) alongside a second describedby target that is always rendered and sr-only when there is nothing to add, `aria-invalid` and the destructive border both follow the actual fault rather than a non-empty box, a warning leaves both alone because the value still stands, the rewrite controls are `type=\"button\"` so they cannot submit the form they sit in, an sr-only hint names whether a prefix is wanted, and a `name` posts the canonical text plus the family and the prefix through hidden inputs — and posts nothing at all for a value the field would not stand behind. `parseIpText`, `parseLegacyIpv4`, `formatAddress`, `formatCidr`, `sameAddress`, `maskBytes`, `networkBytes`, `lastAddressBytes`, `hostBitsSet`, `addressCount`, `usableCount`, `describePrefix`, `bytesToBigInt`, `bigIntToBytes`, `BITS` and `MAPPED_PREFIX_BITS` are exported as plain functions and values, so the route handler that receives the string reaches the same verdict the field showed instead of carrying a second copy of the rules. `families` and `accept` narrow it to one family or to addresses-only or blocks-only. Official shadcn/ui has nothing of the kind and the measurement is not close: fetching every entry in its registry today — 65 listed, 62 fetchable, `code-block`, `questionnaire` and `trace` 404 on both style tracks — and searching all 223,287 bytes, `ipv4`, `ipv6`, `CIDR`, `subnet`, `netmask`, `inet_aton`, `ip address`, `ipAddress`, `prefixLength` and `octet` are every one of them a zero hit; its `input` is a bare text box and `input-group` only puts ornaments either side of one. Within pulld, `masked-input` fixes the shape of a field whose parts all follow one rule where each half of this one has its own, `number-range-input` is one axis of from-and-to, `latlng-input` is the other two-rules-in-one-field case, and `network-status` reports the browser's own connection rather than taking an address. No dependencies beyond React and your `cn`.",
  "dependencies": [],
  "files": [
    {
      "path": "registry/ui/ip-input.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\n/**\n * Which family an address belongs to. The two are not one field with a wider range.\n *\n * They disagree about how many bits an address has, about how many of a subnet's addresses a host\n * may use, and about whether the text in the box is the address or merely one of its spellings.\n * Everything below that reads `family` is reading one of those three differences.\n */\nexport type Family = 4 | 6\n\n/** How many bits an address of each family has. This is the definition, not a measurement. */\nexport const BITS: Record<Family, number> = { 4: 32, 6: 128 }\n\n/**\n * Where the IPv4 part of an IPv4-mapped IPv6 address starts (RFC 4291 §2.5.5.2).\n *\n * **A prefix written on a mapped address is not the prefix anybody means, and the error is a\n * constant.** `::ffff:10.0.0.0/8` is a legal IPv6 block, but it counts from the front of all 128\n * bits, so it covers 2^120 addresses; the IPv4 `10.0.0.0/8` somebody meant is `/104` here, which\n * covers 2^24. The ratio does not depend on the prefix — `2^(128-p) / 2^(32-p)` is `2^96` for\n * every `p` — so the mistake is always the same factor: 79,228,162,514,264,337,593,543,950,336,\n * about 7.9e28. That is why a mapped address carrying a prefix under 96 gets told about it.\n */\nexport const MAPPED_PREFIX_BITS = 96\n\nexport interface IpAddress {\n  family: Family\n  /** 4 bytes or 16. **This is the address**; the text in the box is one of its spellings. */\n  bytes: readonly number[]\n  /** RFC 4007 scope zone, IPv6 only. Part of the destination, not of the bytes — see `sameAddress`. */\n  zone: string | null\n  /** `::ffff:a.b.c.d` — sixteen bytes that denote an IPv4 host (RFC 4291 §2.5.5.2). */\n  mapped: boolean\n}\n\n/** The address as one integer. `bigint` rather than `number` for the reason `addressCount` gives. */\nexport function bytesToBigInt(bytes: readonly number[]): bigint {\n  let n = 0n\n  for (const b of bytes) n = (n << 8n) | BigInt(b)\n  return n\n}\n\n/** The integer back as bytes of `family`. */\nexport function bigIntToBytes(value: bigint, family: Family): number[] {\n  const length = BITS[family] / 8\n  const out = new Array<number>(length)\n  let n = value\n  for (let i = length - 1; i >= 0; i--) {\n    out[i] = Number(n & 255n)\n    n >>= 8n\n  }\n  return out\n}\n\n/**\n * Whether two parsed addresses are the same destination.\n *\n * **Compared on the bytes, because the strings lie.** Measured, every one of these pairs is two\n * valid spellings of one address and `===` says they differ: `2001:db8::1` against\n * `2001:0db8:0000:0000:0000:0000:0000:0001`; `::1` against `0:0:0:0:0:0:0:1`; `2001:DB8::1`\n * against `2001:db8::1`; and `::ffff:192.0.2.1` against `::ffff:c000:0201`. A duplicate check\n * written on the text of an allowlist misses all four, which is how the same host gets added\n * twice and removed once.\n *\n * The zone is compared too, and it is not pedantry: `fe80::1%eth0` and `fe80::1%eth1` carry\n * identical bytes and are hosts on different links (RFC 4007). The bytes alone are not the\n * destination for a link-local address.\n */\nexport function sameAddress(a: IpAddress | null, b: IpAddress | null): boolean {\n  if (!a || !b) return false\n  if (a.family !== b.family || a.zone !== b.zone) return false\n  return a.bytes.length === b.bytes.length && a.bytes.every((byte, i) => byte === b.bytes[i])\n}\n\n/**\n * The netmask of `prefix` bits, byte by byte.\n *\n * **Built per byte because the one-line version is wrong about the most consequential prefix\n * there is.** The mask everybody writes is `(0xFFFFFFFF << (32 - prefix)) >>> 0`, and measured,\n * at `prefix` 0 that is `4294967295` — not zero. JavaScript takes a shift count modulo 32, so\n * shifting by 32 shifts by nothing, and `0.0.0.0/0` comes out with a `/32` mask: a firewall UI\n * reads \"the entire internet\" as \"one host\". Eight-bit shifts cannot reach 32, so assembling the\n * mask a byte at a time does not have the failure mode at all, rather than guarding against it.\n */\nexport function maskBytes(family: Family, prefix: number): number[] {\n  const length = BITS[family] / 8\n  return Array.from({ length }, (_, i) => {\n    const bits = Math.min(8, Math.max(0, prefix - i * 8))\n    return (0xff << (8 - bits)) & 0xff\n  })\n}\n\n/** The first address of the block `bytes/prefix` falls in. */\nexport function networkBytes(bytes: readonly number[], family: Family, prefix: number): number[] {\n  const mask = maskBytes(family, prefix)\n  return bytes.map((b, i) => b & mask[i])\n}\n\n/** The last address of that block — the IPv4 broadcast address, and in IPv6 just the last one. */\nexport function lastAddressBytes(\n  bytes: readonly number[],\n  family: Family,\n  prefix: number\n): number[] {\n  const mask = maskBytes(family, prefix)\n  return bytes.map((b, i) => (b & mask[i]) | (~mask[i] & 0xff))\n}\n\n/**\n * Whether the address has bits set below its own prefix — `192.168.1.5/24`, which is not a network.\n *\n * Reported rather than corrected, because the two repairs are a host and a subnet. Rounding it\n * down to `192.168.1.0/24` turns a rule about one machine into a rule about 256 of them, and in an\n * allowlist that is the difference the reader was writing the rule to express.\n */\nexport function hostBitsSet(bytes: readonly number[], family: Family, prefix: number): boolean {\n  const network = networkBytes(bytes, family, prefix)\n  return !bytes.every((b, i) => b === network[i])\n}\n\n/**\n * How many addresses a prefix covers.\n *\n * **`bigint`, because the IPv6 answers are not Numbers.** Measured: `2 ** 64` evaluates to\n * 18446744073709552000, where the true value is 18446744073709551616 — and `2 ** 64 - 1 === 2 ** 64`\n * is `true`, so a /64 and the whole of it minus one address are the same figure in float64. The\n * commonest subnet in IPv6 cannot be counted in a `number`. `Intl.NumberFormat` does format a\n * `bigint` exactly (measured: 2^128 comes out as all 39 digits), so there is nowhere this has to\n * be narrowed.\n */\nexport function addressCount(family: Family, prefix: number): bigint {\n  return 1n << BigInt(BITS[family] - prefix)\n}\n\n/**\n * How many of those addresses a host can actually be given.\n *\n * **The familiar \"minus two\" is an IPv4 rule, and it produces impossible numbers at both ends of\n * even that axis.** Measured: `2 ** (32 - 31) - 2` is 0 and `2 ** (32 - 32) - 2` is -1, so the\n * formula claims a point-to-point link has no usable addresses and a single host has minus one.\n * RFC 3021 makes a /31 a two-address link with both ends usable, and a /32 is one host.\n *\n * On IPv6 the subtraction is wrong at every prefix, not just at the ends: **there is no broadcast\n * address in IPv6 at all** (RFC 4291 §2.7 — broadcast is replaced by multicast). What a v6 subnet\n * does reserve is one address, the Subnet-Router anycast with an all-zero interface identifier\n * (RFC 4291 §2.6.1), and a /127 inter-router link does not reserve even that (RFC 6164). One\n * formula used for both families is therefore wrong about one of them everywhere, which is the\n * same shape of mistake as quoting one metres-per-degree figure for latitude and longitude.\n */\nexport function usableCount(family: Family, prefix: number): bigint {\n  const total = addressCount(family, prefix)\n  if (family === 4) {\n    if (prefix >= 32) return 1n\n    if (prefix === 31) return 2n\n    return total - 2n\n  }\n  if (prefix >= 127) return total\n  return total - 1n\n}\n\n/** The dotted-quad form of four bytes. */\nfunction formatIpv4(bytes: readonly number[]): string {\n  return bytes.join(\".\")\n}\n\n/**\n * The address written the one way RFC 5952 allows.\n *\n * The rules that are easy to miss: hex is lowercase, each group loses its leading zeros, `::`\n * replaces the **longest** run of two or more zero groups and the **leftmost** such run when two\n * are the same length (§4.2.3), and a run of exactly one zero group is never shortened to `::`\n * (§4.2.2) — `2001:db8::1:1:1:1:1` is a legal spelling of `2001:db8:0:1:1:1:1:1` but not its\n * canonical one.\n *\n * **A mapped address is written with its dotted quad, which is the one place this disagrees with\n * the browser.** Measured, `new URL(\"http://[::ffff:192.0.2.1]\").hostname` is `[::ffff:c000:201]`\n * — the WHATWG serialiser has no special case for §5 and prints the last four bytes as hex. Both\n * are correct spellings; only one of them is a form somebody reviewing a firewall rule can read,\n * so this returns `::ffff:192.0.2.1` and the component says what the address is in both families.\n */\nexport function formatAddress(address: IpAddress): string {\n  if (address.family === 4) return formatIpv4(address.bytes)\n  const suffix = address.zone ? `%${address.zone}` : \"\"\n  if (address.mapped) {\n    return `::ffff:${formatIpv4(address.bytes.slice(12))}${suffix}`\n  }\n  const groups: number[] = []\n  for (let i = 0; i < 16; i += 2) groups.push((address.bytes[i] << 8) | address.bytes[i + 1])\n\n  let bestStart = -1\n  let bestLength = 0\n  let start = -1\n  for (let i = 0; i <= groups.length; i++) {\n    if (i < groups.length && groups[i] === 0) {\n      if (start < 0) start = i\n      continue\n    }\n    if (start >= 0) {\n      const length = i - start\n      // `>` and not `>=`: on a tie the leftmost run wins, which is §4.2.3.\n      if (length >= 2 && length > bestLength) {\n        bestStart = start\n        bestLength = length\n      }\n      start = -1\n    }\n  }\n\n  const hex = groups.map((g) => g.toString(16))\n  if (bestStart < 0) return `${hex.join(\":\")}${suffix}`\n  const head = hex.slice(0, bestStart).join(\":\")\n  const tail = hex.slice(bestStart + bestLength).join(\":\")\n  return `${head}::${tail}${suffix}`\n}\n\n/** The canonical text for an address with an optional prefix. */\nexport function formatCidr(address: IpAddress, prefix: number | null): string {\n  return prefix === null ? formatAddress(address) : `${formatAddress(address)}/${prefix}`\n}\n\nexport type IssueCode =\n  | \"not-an-address\"\n  | \"leading-zero\"\n  | \"legacy-form\"\n  | \"bad-prefix\"\n  | \"prefix-range\"\n  | \"host-bits\"\n  | \"mapped-prefix\"\n  | \"family-not-accepted\"\n  | \"prefix-required\"\n  | \"prefix-not-accepted\"\n\nexport interface IpIssue {\n  code: IssueCode\n  /** `error` means nothing is posted. `warning` means the value stands and is flagged. */\n  level: \"error\" | \"warning\"\n  message: string\n}\n\nexport interface IpParse {\n  /** The address, or `null` for an empty box or text that is not one. */\n  address: IpAddress | null\n  /** The prefix length the text carried, or `null` when it carried none. */\n  prefix: number | null\n  /** The canonical text, or `\"\"` when there is nothing to stand behind. */\n  canonical: string\n  issue: IpIssue | null\n  /** Things true about a readable value: what it is, how big, what it denotes. */\n  notes: string[]\n  /** Unambiguous text a control can put in the box, when the field will not do it unasked. */\n  suggestion: string | null\n}\n\nconst EMPTY: IpParse = {\n  address: null,\n  prefix: null,\n  canonical: \"\",\n  issue: null,\n  notes: [],\n  suggestion: null,\n}\n\nconst fail = (code: IssueCode, message: string, suggestion: string | null = null): IpParse => ({\n  ...EMPTY,\n  issue: { code, level: \"error\", message },\n  suggestion,\n})\n\n/**\n * Reads one part of a dotted address the way the WHATWG URL parser does, which is the way every\n * browser and curl do: `0x` is hex, a leading `0` is octal, anything else is decimal.\n *\n * Returns `null` for a part that is not a number in its own radix — measured, that is why\n * `http://09.0.0.1` is not a URL at all: `09` strips to `9`, which is not an octal digit.\n */\nfunction legacyPart(text: string): number | null {\n  if (/^0[xX][0-9a-fA-F]+$/.test(text)) return Number.parseInt(text.slice(2), 16)\n  if (/^0[0-7]+$/.test(text)) return Number.parseInt(text.slice(1), 8)\n  if (/^\\d+$/.test(text) && !(text.length > 1 && text[0] === \"0\")) return Number(text)\n  return null\n}\n\n/**\n * The IPv4 address the legacy forms denote, or `null` when they denote none.\n *\n * One to four parts, the last of which absorbs however many bytes the earlier parts left. Verified\n * against the browser on every case it is used for below: `127.1` and `2130706433` and `0x7f.1`\n * and `0177.0.0.1` all come out `127.0.0.1`, `192.168.257` comes out `192.168.1.1`,\n * `10.16777215` comes out `10.255.255.255`, and `192.168.65536`, `10.16777216`, `1.2.3.256`,\n * `1.1.1.1.1` and `99999999999` are refused by both.\n */\nexport function parseLegacyIpv4(text: string): number[] | null {\n  // One bound, not two: `\"\".split(\".\")` is `[\"\"]`, so `split` never returns fewer than one part and\n  // a `length < 1` guard is a condition that cannot be false. Mutation testing found it by deleting\n  // it without any test noticing, which is what an unreachable guard looks like from outside.\n  const parts = text.split(\".\")\n  if (parts.length > 4) return null\n  const values: number[] = []\n  for (const part of parts) {\n    const value = legacyPart(part)\n    if (value === null) return null\n    values.push(value)\n  }\n  for (let i = 0; i < values.length - 1; i++) if (values[i] > 255) return null\n  const lastMax = 256 ** (4 - (values.length - 1)) - 1\n  const last = values[values.length - 1]\n  if (last > lastMax) return null\n  let n = last\n  for (let i = 0; i < values.length - 1; i++) n += values[i] * 256 ** (3 - i)\n  return [(n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255]\n}\n\n/** Four plain decimal parts, each 0-255, with no leading zeros. The only unambiguous IPv4 text. */\nfunction parseStrictIpv4(text: string): number[] | null {\n  const parts = text.split(\".\")\n  if (parts.length !== 4) return null\n  const bytes: number[] = []\n  for (const part of parts) {\n    if (!/^\\d{1,3}$/.test(part)) return null\n    if (part.length > 1 && part[0] === \"0\") return null\n    const value = Number(part)\n    if (value > 255) return null\n    bytes.push(value)\n  }\n  return bytes\n}\n\nfunction readIpv4(text: string): IpParse {\n  const strict = parseStrictIpv4(text)\n  if (strict) {\n    return {\n      ...EMPTY,\n      address: { family: 4, bytes: strict, zone: null, mapped: false },\n      canonical: formatIpv4(strict),\n    }\n  }\n\n  const parts = text.split(\".\")\n  // The leading zero is checked before the legacy expansion, because it is the one form where the\n  // two readings are different hosts rather than two spellings of one.\n  if (parts.length === 4 && parts.every((p) => /^\\d+$/.test(p))) {\n    const padded = parts.find((p) => p.length > 1 && p[0] === \"0\")\n    if (padded) {\n      const octal = parseLegacyIpv4(text)\n      const decimal = parseStrictIpv4(parts.map((p) => String(Number(p))).join(\".\"))\n      if (octal && decimal) {\n        return fail(\n          \"leading-zero\",\n          `\"${padded}\" reads as octal: every browser resolves this to ${formatIpv4(octal)}, while a` +\n            ` tool that strips the zero resolves it to ${formatIpv4(decimal)}. Those are different` +\n            ` hosts — write the one you mean without the leading zero.`,\n          formatIpv4(decimal)\n        )\n      }\n      return fail(\n        \"leading-zero\",\n        `\"${padded}\" has a leading zero, which makes it octal — and 8 and 9 are not octal digits,` +\n          ` so browsers refuse this address outright rather than reading it either way.`,\n        decimal ? formatIpv4(decimal) : null\n      )\n    }\n  }\n\n  const legacy = parseLegacyIpv4(text)\n  if (legacy) {\n    return fail(\n      \"legacy-form\",\n      `Browsers and curl read \"${text}\" as ${formatIpv4(legacy)}, and this runtime's own` +\n        ` net.isIPv4 calls it invalid. Two answers in one process is not something a rule can be` +\n        ` stored on, so write it out.`,\n      formatIpv4(legacy)\n    )\n  }\n  return fail(\"not-an-address\", `\"${text}\" is not an IP address.`)\n}\n\nfunction readIpv6(text: string): IpParse {\n  let body = text\n  let zone: string | null = null\n  const percent = body.indexOf(\"%\")\n  if (percent >= 0) {\n    zone = body.slice(percent + 1)\n    body = body.slice(0, percent)\n    // A zone with no name is the one spelling `net.isIPv6` refuses while accepting `%0` (measured).\n    if (zone === \"\") return fail(\"not-an-address\", \"A % needs the name of the link after it.\")\n  }\n\n  const halves = body.split(\"::\")\n  if (halves.length > 2) {\n    return fail(\"not-an-address\", \"A :: may only appear once — it is the run of zeros, so two of them have no reading.\")\n  }\n  const compressed = halves.length === 2\n\n  // **An embedded IPv4 address belongs at the end, and the check is on the half rather than on a\n  // flag the reader of each piece sets.** A dotted quad is two groups wherever it sits, so a parser\n  // that only counts groups accepts `1.2.3.4::1` and invents `102:304::1` out of it — measured,\n  // `net.isIPv6(\"1.2.3.4::1\")` is `false`. Asking whether the left half contains a dot answers it,\n  // because a dot anywhere else in that half fails the piece it is in anyway; the flag that used to\n  // carry this was a field whose value on the right-hand half was never read, which is what\n  // mutation testing found by setting it to `true` with nothing noticing.\n  if (compressed && halves[0].includes(\".\")) {\n    return fail(\"not-an-address\", \"An embedded IPv4 address belongs at the end of the address.\")\n  }\n\n  const readSide = (side: string): number[] | null => {\n    if (side === \"\") return []\n    const pieces = side.split(\":\")\n    const groups: number[] = []\n    for (let i = 0; i < pieces.length; i++) {\n      const piece = pieces[i]\n      if (i === pieces.length - 1 && piece.includes(\".\")) {\n        const quad = parseStrictIpv4(piece)\n        if (!quad) return null\n        groups.push((quad[0] << 8) | quad[1], (quad[2] << 8) | quad[3])\n        continue\n      }\n      if (!/^[0-9a-fA-F]{1,4}$/.test(piece)) return null\n      groups.push(Number.parseInt(piece, 16))\n    }\n    return groups\n  }\n\n  const head = readSide(halves[0])\n  const tail = compressed ? readSide(halves[1]) : []\n  if (!head || !tail) return fail(\"not-an-address\", `\"${text}\" is not an IPv6 address.`)\n\n  const total = head.length + tail.length\n  if (compressed) {\n    if (total > 7) {\n      return fail(\n        \"not-an-address\",\n        \"The :: has to stand for at least one group of zeros, and there is no room left for it.\"\n      )\n    }\n  } else if (total !== 8) {\n    return fail(\"not-an-address\", `An IPv6 address has 8 groups; this has ${total}.`)\n  }\n\n  const groups = compressed\n    ? [...head, ...Array.from({ length: 8 - total }, () => 0), ...tail]\n    : head\n  const bytes: number[] = []\n  for (const g of groups) bytes.push((g >> 8) & 255, g & 255)\n\n  const mapped =\n    bytes.slice(0, 10).every((b) => b === 0) && bytes[10] === 0xff && bytes[11] === 0xff\n  const address: IpAddress = { family: 6, bytes, zone, mapped }\n  return { ...EMPTY, address, canonical: formatAddress(address) }\n}\n\nexport interface ParseOptions {\n  /** Which families the field will stand behind. */\n  families?: readonly Family[]\n  /** `\"address\"` refuses a prefix, `\"cidr\"` requires one, `\"either\"` takes both. */\n  accept?: \"address\" | \"cidr\" | \"either\"\n}\n\n/**\n * Reads the box as an address or a block, and says what it had to assume.\n *\n * **Empty and unreadable are kept apart**, for the reason every input in this registry keeps them\n * apart: an empty allowlist entry is not `0.0.0.0`, and `0.0.0.0/0` is every host on the internet.\n *\n * What it will not do is pick between two readings on the reader's behalf. The legacy IPv4 forms\n * are the clearest case: measured, the WHATWG URL parser — which is to say every browser, and\n * curl — resolves `127.1`, `2130706433`, `0x7f.1` and `0177.0.0.1` all to `127.0.0.1` and\n * `192.168.257` to `192.168.1.1`, while `net.isIPv4` in the very same Node process calls every one\n * of them invalid. \"Is this a valid address\" has two answers inside one runtime, so a field that\n * silently takes either one is deciding which tool downstream is going to be surprised. Each is\n * reported with the expansion named, for a control to apply.\n */\nexport function parseIpText(text: string, options: ParseOptions = {}): IpParse {\n  const { families = [4, 6] as const, accept = \"either\" } = options\n  const trimmed = text.trim()\n  if (trimmed === \"\") return EMPTY\n\n  const slash = trimmed.lastIndexOf(\"/\")\n  const body = slash >= 0 ? trimmed.slice(0, slash) : trimmed\n  const prefixText = slash >= 0 ? trimmed.slice(slash + 1) : null\n  if (body === \"\") return fail(\"not-an-address\", \"There is a prefix here but no address.\")\n\n  const read = body.includes(\":\") ? readIpv6(body) : readIpv4(body)\n  if (!read.address) return read\n  const address = read.address\n\n  if (!families.includes(address.family)) {\n    return fail(\n      \"family-not-accepted\",\n      `This field takes IPv${families.join(\" and IPv\")} addresses, and that is an IPv${address.family} address.`\n    )\n  }\n\n  let prefix: number | null = null\n  if (prefixText !== null) {\n    if (accept === \"address\") {\n      return fail(\"prefix-not-accepted\", \"This field takes a single address, without a /prefix.\")\n    }\n    if (!/^\\d{1,3}$/.test(prefixText)) {\n      return fail(\"bad-prefix\", `\"/${prefixText}\" is not a prefix length.`)\n    }\n    prefix = Number(prefixText)\n    const limit = BITS[address.family]\n    if (prefix > limit) {\n      return fail(\n        \"prefix-range\",\n        `An IPv${address.family} prefix runs from /0 to /${limit}${\n          address.family === 4 ? \", not /128 — that is the IPv6 limit\" : \"\"\n        }.`\n      )\n    }\n  } else if (accept === \"cidr\") {\n    return fail(\n      \"prefix-required\",\n      `This field takes a block, so it needs a /prefix — /${BITS[address.family]} for the single host.`\n    )\n  }\n\n  const notes: string[] = []\n  if (address.mapped) {\n    notes.push(\n      `An IPv4-mapped address: sixteen bytes that denote the IPv4 host ${formatIpv4(\n        address.bytes.slice(12)\n      )}.`\n    )\n  }\n  if (address.zone) {\n    notes.push(\n      `Scoped to the link \"${address.zone}\", which is part of the destination — the same bytes on` +\n        ` another link are another host — and is why this address cannot be a URL host.`\n    )\n  }\n\n  if (prefix !== null) notes.push(describePrefix(address.family, prefix))\n\n  if (prefix !== null && address.mapped && prefix < MAPPED_PREFIX_BITS) {\n    const intended = MAPPED_PREFIX_BITS + prefix\n    return {\n      address,\n      prefix,\n      canonical: formatCidr(address, prefix),\n      notes,\n      suggestion: formatCidr(address, intended),\n      issue: {\n        code: \"mapped-prefix\",\n        level: \"warning\",\n        message:\n          `/${prefix} counts from the front of all 128 bits, so this block is ${count(\n            addressCount(6, prefix)\n          )} addresses. The IPv4 /${prefix} you are likely to mean is /${intended} here — the` +\n          ` difference is 2^96, about 7.9e28 times.`,\n      },\n    }\n  }\n\n  if (prefix !== null && hostBitsSet(address.bytes, address.family, prefix)) {\n    const network: IpAddress = {\n      ...address,\n      bytes: networkBytes(address.bytes, address.family, prefix),\n    }\n    return {\n      address,\n      prefix,\n      canonical: formatCidr(address, prefix),\n      notes,\n      suggestion: formatCidr(network, prefix),\n      issue: {\n        code: \"host-bits\",\n        level: \"warning\",\n        message:\n          `${formatAddress(address)}/${prefix} is a host inside a block, not the block:` +\n          ` ${formatCidr(network, prefix)} is the block. Rounding it down would widen the rule` +\n          ` from 1 address to ${count(addressCount(address.family, prefix))}, so neither is` +\n          ` applied for you.`,\n      },\n    }\n  }\n\n  return {\n    address,\n    prefix,\n    canonical: formatCidr(address, prefix),\n    notes,\n    suggestion: null,\n    issue: null,\n  }\n}\n\n/** A count with its thousands separators. `bigint` all the way, for the reason `addressCount` gives. */\nfunction count(value: bigint): string {\n  return value.toLocaleString(\"en-US\")\n}\n\n/**\n * What a prefix is worth, in addresses.\n *\n * **The sentence exists because the prefix is the one number in a firewall rule that is read\n * linearly and is not linear.** A /24 is 256 addresses and a /16 is 65,536 — one digit, 256 times\n * as many hosts — and a /0 is every address there is. Printing the figure is the whole of the fix.\n */\nexport function describePrefix(family: Family, prefix: number): string {\n  const total = addressCount(family, prefix)\n  const usable = usableCount(family, prefix)\n  const single = prefix === BITS[family]\n  if (single) return `/${prefix} is the single address.`\n  const detail =\n    family === 4\n      ? prefix === 31\n        ? \"both usable on a point-to-point link (RFC 3021)\"\n        : `${count(usable)} usable, after the network and broadcast addresses`\n      : prefix >= 127\n        ? \"both usable on an inter-router link (RFC 6164)\"\n        : `${count(usable)} usable, after the Subnet-Router anycast address — IPv6 has no broadcast address to lose`\n  return `/${prefix} covers ${count(total)} addresses: ${detail}.`\n}\n\nexport interface IpValue {\n  canonical: string\n  family: Family\n  prefix: number | null\n  bytes: readonly number[]\n  zone: string | null\n}\n\nexport interface IpInputProps\n  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, \"value\" | \"defaultValue\" | \"onChange\"> {\n  value?: string\n  defaultValue?: string\n  /** Called with a value the field stands behind, or `null` while it does not. */\n  onValueChange?: (value: IpValue | null) => void\n  families?: readonly Family[]\n  accept?: \"address\" | \"cidr\" | \"either\"\n  label?: string\n  /** Posts the canonical text, the family and the prefix — and posts nothing when invalid. */\n  name?: string\n}\n\n/**\n * One box for an IP address or a CIDR block, which is a stricter field than it looks.\n *\n * What it is for: a firewall or allowlist entry, a VPN or subnet plan, a DNS A/AAAA record, an\n * upstream for a proxy or load balancer, a monitoring target, and the search box where somebody\n * pastes the source address out of a log.\n *\n * What it does that a text box with a regular expression does not: it normalises to the one\n * spelling RFC 5952 allows, so a duplicate check lands; it refuses the two IPv4 forms whose\n * readings disagree instead of picking one; it says what a prefix is worth in addresses; and it\n * tells the difference between an empty box and an unreadable one.\n *\n * Within pulld, `masked-input` fixes the shape of a field whose parts all follow one rule, where\n * each half of this one has its own; `number-range-input` is one axis of from-and-to; and\n * `network-status` reports the browser's own connection rather than taking an address.\n */\nexport function IpInput({\n  value,\n  defaultValue = \"\",\n  onValueChange,\n  families = [4, 6],\n  accept = \"either\",\n  label = \"IP address\",\n  name,\n  className,\n  disabled,\n  placeholder,\n  ...rest\n}: IpInputProps) {\n  const isControlled = value !== undefined\n  const reactId = React.useId()\n  const [text, setText] = React.useState(isControlled ? (value as string) : defaultValue)\n\n  // An outside value is written into the box only when it is a different string from the one on\n  // screen, so a parent echoing the same text back cannot interrupt typing.\n  const lastPushed = React.useRef<string>(isControlled ? (value as string) : defaultValue)\n  React.useEffect(() => {\n    if (!isControlled) return\n    if (value === lastPushed.current) return\n    lastPushed.current = value as string\n    setText(value as string)\n  }, [isControlled, value])\n\n  const parsed = parseIpText(text, { families, accept })\n  // `address !== null` is the whole condition, and the `issue?.level !== \"error\"` that was beside it\n  // was the same rule written twice: every error-level return in `parseIpText` goes through `fail`,\n  // which carries no address, and a warning-level one always carries one. Mutation testing turned\n  // the `&&` into an `||` in both places here with no test noticing — which is the signature of a\n  // second clause that can never change the answer.\n  const found = parsed.address\n  const result: IpValue | null = found\n    ? {\n        canonical: parsed.canonical,\n        family: found.family,\n        prefix: parsed.prefix,\n        bytes: found.bytes,\n        zone: found.zone,\n      }\n    : null\n\n  // The parent hears about a value, not about a keystroke: the canonical text is the identity, so\n  // retyping the same address in another spelling is not a change.\n  const lastEmitted = React.useRef<string>(\"\\u0000\")\n  React.useEffect(() => {\n    const key = result ? result.canonical : \"null\"\n    if (key === lastEmitted.current) return\n    lastEmitted.current = key\n    onValueChange?.(result)\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [result?.canonical])\n\n  const bad = parsed.issue?.level === \"error\"\n  const statusId = `${reactId}-status`\n  const noteId = `${reactId}-note`\n  const normalised = result && result.canonical !== text.trim() ? result.canonical : null\n\n  const apply = (next: string) => {\n    lastPushed.current = next\n    setText(next)\n  }\n\n  return (\n    <div role=\"group\" aria-label={label} className={cn(\"flex w-full flex-col gap-2\", className)}>\n      <div className=\"flex flex-wrap items-end gap-2\">\n        <div className=\"flex min-w-[12rem] flex-1 flex-col gap-1\">\n          <label htmlFor={reactId} className=\"text-xs font-medium text-muted-foreground\">\n            {label}\n            <span className=\"sr-only\">\n              {accept === \"address\"\n                ? \", a single address\"\n                : accept === \"cidr\"\n                  ? \", a block written as an address and a slash and a prefix length\"\n                  : \", an address, or a block written with a slash and a prefix length\"}\n            </span>\n          </label>\n          <input\n            id={reactId}\n            // `type=\"text\"`: there is no input type that holds an address, and `type=\"number\"`\n            // would discard every character that makes one.\n            type=\"text\"\n            inputMode=\"text\"\n            autoComplete=\"off\"\n            spellCheck={false}\n            disabled={disabled}\n            value={text}\n            aria-invalid={bad || undefined}\n            aria-describedby={`${statusId} ${noteId}`}\n            placeholder={placeholder ?? (accept === \"cidr\" ? \"10.0.0.0/8\" : \"192.0.2.10\")}\n            onChange={(e) => setText(e.target.value)}\n            className={cn(\n              \"h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 font-mono 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              bad && \"border-destructive focus-visible:ring-destructive\"\n            )}\n            {...rest}\n          />\n        </div>\n        {parsed.suggestion ? (\n          <button\n            type=\"button\"\n            onClick={() => apply(parsed.suggestion as string)}\n            disabled={disabled}\n            className={cn(\n              \"h-9 shrink-0 rounded-md border border-input px-3 font-mono text-xs transition-colors\",\n              \"hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\",\n              \"disabled:cursor-not-allowed disabled:opacity-50\"\n            )}\n          >\n            {parsed.suggestion}\n            <span className=\"sr-only\"> — put this in the box instead</span>\n          </button>\n        ) : null}\n        {normalised ? (\n          <button\n            type=\"button\"\n            onClick={() => apply(normalised)}\n            disabled={disabled}\n            className={cn(\n              \"h-9 shrink-0 rounded-md border border-input px-3 font-mono text-xs transition-colors\",\n              \"hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring\",\n              \"disabled:cursor-not-allowed disabled:opacity-50\"\n            )}\n          >\n            {normalised}\n            <span className=\"sr-only\"> — the canonical spelling, RFC 5952</span>\n          </button>\n        ) : null}\n      </div>\n\n      {/* One polite status line for the group: two live regions race each other and a screen\n          reader ends up announcing neither. */}\n      <p\n        id={statusId}\n        role=\"status\"\n        aria-live=\"polite\"\n        className={cn(\"text-xs\", bad ? \"text-destructive\" : \"text-muted-foreground\")}\n      >\n        {parsed.issue\n          ? parsed.issue.message\n          : result\n            ? `IPv${result.family} — ${result.canonical}`\n            : accept === \"cidr\"\n              ? \"An IPv4 or IPv6 block, such as 10.0.0.0/8 or 2001:db8::/32.\"\n              : \"An IPv4 or IPv6 address, with an optional /prefix.\"}\n      </p>\n      {parsed.notes.length > 0 ? (\n        <p id={noteId} className=\"text-xs text-muted-foreground\">\n          {parsed.notes.join(\" \")}\n        </p>\n      ) : (\n        <p id={noteId} className=\"sr-only\" />\n      )}\n\n      {name ? (\n        <>\n          <input type=\"hidden\" name={name} value={result ? result.canonical : \"\"} disabled={!result} />\n          <input\n            type=\"hidden\"\n            name={`${name}.family`}\n            value={result ? String(result.family) : \"\"}\n            disabled={!result}\n          />\n          <input\n            type=\"hidden\"\n            name={`${name}.prefix`}\n            value={result && result.prefix !== null ? String(result.prefix) : \"\"}\n            disabled={!result || result.prefix === null}\n          />\n        </>\n      ) : null}\n    </div>\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"
}
