{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "regex-input",
  "title": "Regex Input",
  "description": "Validate regular expressions live with flags toggles, error feedback, and match previews.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "utils",
    "badge",
    "@drift-ui/use-controllable-state",
    "@drift-ui/shape"
  ],
  "files": [
    {
      "path": "registry/default/ui/regex-input.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AlertCircleIcon } from \"lucide-react\"\n\nimport { useControllableState } from \"@/registry/default/hooks/use-controllable-state\"\nimport {\n  DEFAULT_AVAILABLE_FLAGS,\n  findRegexMatchesAsync,\n  highlightSampleText,\n  normalizeFlags,\n  REGEX_FLAGS,\n  toggleFlag,\n  validateRegex,\n  type RegexFlagInfo,\n  type RegexMatchResult,\n} from \"@/registry/default/lib/regex-input-utils\"\nimport { cn } from \"@/registry/default/lib/utils\"\nimport { Badge } from \"@/registry/default/ui/badge\"\n\nexport interface RegexInputProps extends Omit<\n  React.ComponentProps<\"div\">,\n  \"defaultValue\" | \"onChange\"\n> {\n  /** The regex pattern string (without slash delimiters) */\n  value?: string\n  /** Uncontrolled default pattern */\n  defaultValue?: string\n  /** Callback when pattern changes */\n  onValueChange?: (pattern: string) => void\n\n  /** Active regex flags (e.g. \"i\", \"ims\") */\n  flags?: string\n  /** Uncontrolled default flags */\n  defaultFlags?: string\n  /** Callback when flags change */\n  onFlagsChange?: (flags: string) => void\n\n  /** Available flag toggle buttons to display. Defaults to [\"i\", \"m\", \"s\"] */\n  availableFlags?: readonly string[]\n\n  /** Sample text to test pattern against */\n  sample?: string\n\n  /** Placeholder text for pattern input */\n  placeholder?: string\n\n  /** Disabled state */\n  disabled?: boolean\n  /** Read-only state */\n  readOnly?: boolean\n\n  /** Form field name for hidden input */\n  name?: string\n\n  /** Whether to show regex delimiters `/` ... `/`. Defaults to true */\n  showDelimiters?: boolean\n\n  /** Whether to show flag toggle buttons. Defaults to true */\n  showFlags?: boolean\n\n  /** Whether to display constructor error message on invalid regex. Defaults to true */\n  showError?: boolean\n\n  /** Whether to show sample text highlight and match preview when sample is provided. Defaults to true */\n  showSamplePreview?: boolean\n\n  /** Maximum matches to process. Defaults to 100 */\n  maxMatches?: number\n\n  /** Maximum sample text length. Defaults to 20000 */\n  maxSampleLength?: number\n\n  /** Additional props forwarded to the underlying text input */\n  inputProps?: Omit<\n    React.ComponentProps<\"input\">,\n    \"value\" | \"defaultValue\" | \"onChange\" | \"disabled\" | \"readOnly\"\n  >\n\n  /** Ref to the underlying text input */\n  inputRef?: React.Ref<HTMLInputElement>\n}\n\nfunction RegexInput({\n  value: valueProp,\n  defaultValue = \"\",\n  onValueChange,\n  flags: flagsProp,\n  defaultFlags = \"\",\n  onFlagsChange,\n  availableFlags = DEFAULT_AVAILABLE_FLAGS,\n  sample,\n  placeholder = \"pattern\",\n  disabled = false,\n  readOnly = false,\n  name,\n  showDelimiters = true,\n  showFlags = true,\n  showError = true,\n  showSamplePreview = true,\n  maxMatches = 100,\n  maxSampleLength = 20000,\n  inputRef,\n  inputProps,\n  className,\n  \"aria-describedby\": ariaDescribedBy,\n  \"aria-label\": ariaLabel,\n  \"aria-labelledby\": ariaLabelledBy,\n  ...props\n}: RegexInputProps) {\n  const { value: pattern, setValue: setPattern } = useControllableState({\n    value: valueProp,\n    defaultValue,\n    onChange: onValueChange,\n  })\n\n  const { value: currentFlags, setValue: setCurrentFlags } =\n    useControllableState({\n      value: flagsProp !== undefined ? normalizeFlags(flagsProp) : undefined,\n      defaultValue: normalizeFlags(defaultFlags),\n      onChange: onFlagsChange,\n    })\n\n  const generatedId = React.useId()\n  const inputId = `regex-pattern-${generatedId}`\n  const errorId = `regex-error-${generatedId}`\n  const sampleId = `regex-sample-${generatedId}`\n  const statusId = `regex-status-${generatedId}`\n\n  const internalInputRef = React.useRef<HTMLInputElement | null>(null)\n  React.useImperativeHandle(\n    inputRef,\n    () => internalInputRef.current as HTMLInputElement,\n    []\n  )\n  React.useImperativeHandle(\n    inputProps?.ref,\n    () => internalInputRef.current as HTMLInputElement,\n    []\n  )\n\n  // Validate pattern\n  const validation = React.useMemo(\n    () => validateRegex(pattern, currentFlags),\n    [pattern, currentFlags]\n  )\n  const isValid = validation.isValid\n  const error = validation.error\n\n  // Evaluate matches off-render (in an interruptible Worker when supported)\n  const [matchState, setMatchState] = React.useState<{\n    key: string\n    result: RegexMatchResult\n  } | null>(null)\n\n  const matchKey =\n    sample && isValid && pattern\n      ? JSON.stringify([\n          pattern,\n          currentFlags,\n          sample,\n          maxMatches,\n          maxSampleLength,\n        ])\n      : null\n\n  React.useEffect(() => {\n    if (!matchKey || !sample) return\n\n    const controller = new AbortController()\n    findRegexMatchesAsync(pattern, currentFlags, sample, {\n      maxMatches,\n      maxSampleLength,\n      signal: controller.signal,\n    }).then((result) => {\n      if (!controller.signal.aborted) {\n        setMatchState({ key: matchKey, result })\n      }\n    })\n\n    return () => {\n      controller.abort()\n    }\n  }, [matchKey, pattern, currentFlags, sample, maxMatches, maxSampleLength])\n\n  const matchResult =\n    matchKey && matchState?.key === matchKey ? matchState.result : null\n\n  const matches = React.useMemo(() => matchResult?.matches ?? [], [matchResult])\n  const matchCount = matchResult?.matchCount ?? 0\n\n  // Segment sample text for highlighting\n  const segments = React.useMemo(\n    () => highlightSampleText(sample ?? \"\", matches),\n    [sample, matches]\n  )\n\n  const { className: inputPropsClassName, ...restInputProps } = inputProps ?? {}\n\n  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    setPattern(e.target.value)\n  }\n\n  const handleToggleFlag = (flag: string) => {\n    const nextFlags = toggleFlag(currentFlags, flag)\n    setCurrentFlags(nextFlags)\n  }\n\n  return (\n    <div\n      data-slot=\"regex-input\"\n      className={cn(\"flex w-full flex-col gap-2 text-sm\", className)}\n      {...props}\n    >\n      <div\n        data-slot=\"regex-input-control\"\n        data-invalid={!isValid || undefined}\n        className={cn(\n          \"flex h-control w-full items-center gap-1.5 rounded-control border bg-background px-3 shadow-control transition-all\",\n          \"focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50\",\n          !isValid &&\n            \"border-destructive focus-within:border-destructive focus-within:ring-destructive/20 dark:focus-within:ring-destructive/40\",\n          disabled && \"pointer-events-none opacity-50\"\n        )}\n      >\n        {showDelimiters && (\n          <span\n            aria-hidden=\"true\"\n            className=\"font-mono font-medium text-muted-foreground select-none\"\n          >\n            /\n          </span>\n        )}\n\n        <input\n          {...restInputProps}\n          ref={internalInputRef}\n          id={inputProps?.id ?? inputId}\n          type=\"text\"\n          value={pattern}\n          onChange={handleInputChange}\n          placeholder={placeholder}\n          disabled={disabled}\n          readOnly={readOnly}\n          aria-invalid={!isValid}\n          aria-label={\n            inputProps?.[\"aria-label\"] ??\n            ariaLabel ??\n            (ariaLabelledBy || inputProps?.[\"aria-labelledby\"]\n              ? undefined\n              : \"Regular expression pattern\")\n          }\n          aria-labelledby={inputProps?.[\"aria-labelledby\"] ?? ariaLabelledBy}\n          aria-describedby={\n            cn(\n              !isValid && showError && errorId,\n              sample && statusId,\n              ariaDescribedBy,\n              inputProps?.[\"aria-describedby\"]\n            ) || undefined\n          }\n          className={cn(\n            \"flex-1 bg-transparent font-mono text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\",\n            inputPropsClassName\n          )}\n        />\n\n        {showDelimiters && (\n          <span\n            aria-hidden=\"true\"\n            className=\"font-mono font-medium text-muted-foreground select-none\"\n          >\n            /\n          </span>\n        )}\n\n        {showFlags && availableFlags.length > 0 && (\n          <div\n            role=\"group\"\n            aria-label=\"Regex flags\"\n            className=\"flex items-center gap-0.5 border-l border-border pl-1.5\"\n          >\n            {availableFlags.map((flag) => {\n              const info: RegexFlagInfo | undefined = REGEX_FLAGS[flag]\n              const isActive = currentFlags.includes(flag)\n              const label = info ? `${info.label} (${flag})` : `Flag ${flag}`\n              const title = info\n                ? `${info.label} (${flag}): ${info.description}`\n                : `Flag ${flag}`\n\n              return (\n                <button\n                  key={flag}\n                  type=\"button\"\n                  aria-pressed={isActive}\n                  aria-label={label}\n                  title={title}\n                  disabled={disabled || readOnly}\n                  onClick={() => handleToggleFlag(flag)}\n                  className={cn(\n                    \"inline-flex size-6 cursor-pointer items-center justify-center rounded-sm font-mono text-xs font-semibold transition-colors select-none\",\n                    isActive\n                      ? \"bg-accent font-bold text-accent-foreground shadow-xs\"\n                      : \"text-muted-foreground hover:bg-muted hover:text-foreground\",\n                    \"focus-visible:ring-1 focus-visible:ring-ring focus-visible:outline-none\",\n                    \"disabled:cursor-not-allowed disabled:opacity-50\"\n                  )}\n                >\n                  {flag}\n                </button>\n              )\n            })}\n          </div>\n        )}\n\n        {sample && !showSamplePreview && isValid && pattern && (\n          <Badge\n            variant=\"secondary\"\n            className=\"h-5 shrink-0 px-1.5 text-[10px] font-normal\"\n          >\n            {matchCount} {matchCount === 1 ? \"match\" : \"matches\"}\n            {matchResult?.truncated && \"+\"}\n          </Badge>\n        )}\n      </div>\n\n      {!isValid && showError && error && (\n        <div\n          id={errorId}\n          role=\"alert\"\n          aria-live=\"assertive\"\n          className=\"flex items-center gap-1.5 text-xs font-medium text-destructive\"\n        >\n          <AlertCircleIcon className=\"size-3.5 shrink-0\" />\n          <span>{error}</span>\n        </div>\n      )}\n\n      {sample && (\n        <div id={statusId} className=\"sr-only\" aria-live=\"polite\">\n          {isValid && pattern\n            ? `${matchCount} ${matchCount === 1 ? \"match\" : \"matches\"} found in sample text`\n            : !isValid\n              ? \"Invalid regex pattern\"\n              : \"\"}\n        </div>\n      )}\n\n      {sample && showSamplePreview && (\n        <div\n          id={sampleId}\n          data-slot=\"regex-sample-preview\"\n          className=\"flex flex-col gap-2 rounded-control border border-border bg-muted/30 p-3 text-xs\"\n        >\n          <div className=\"flex items-center justify-between\">\n            <span className=\"font-semibold text-muted-foreground\">\n              Test Sample\n            </span>\n            <span className=\"text-[11px] text-muted-foreground\">\n              {pattern ? (\n                isValid ? (\n                  <>\n                    <span className=\"font-medium text-foreground\">\n                      {matchCount}\n                    </span>{\" \"}\n                    {matchCount === 1 ? \"match\" : \"matches\"}\n                    {matchResult?.truncated ? \" (limit reached)\" : \"\"}\n                  </>\n                ) : (\n                  <span className=\"font-medium text-destructive\">\n                    Invalid pattern\n                  </span>\n                )\n              ) : (\n                \"Enter a pattern to test\"\n              )}\n            </span>\n          </div>\n\n          <pre className=\"max-h-48 overflow-auto rounded-sm border border-border/60 bg-background/80 p-2.5 font-mono text-xs break-all whitespace-pre-wrap select-text\">\n            {segments.map((seg, i) =>\n              seg.isMatch ? (\n                <mark\n                  key={i}\n                  data-match-index={seg.matchIndex}\n                  className=\"rounded-xs border-b border-primary/50 bg-primary/20 px-0.5 font-medium text-foreground\"\n                >\n                  {seg.text}\n                </mark>\n              ) : (\n                <span key={i}>{seg.text}</span>\n              )\n            )}\n          </pre>\n\n          {matches.some((m) => m.groups.length > 0) && (\n            <div className=\"mt-1 space-y-1.5 border-t border-border/50 pt-2\">\n              <span className=\"text-[11px] font-semibold text-muted-foreground\">\n                Capture Groups\n              </span>\n              <div className=\"max-h-36 space-y-1 overflow-auto font-mono text-[11px]\">\n                {matches.slice(0, 10).map((m, mIdx) => (\n                  <div\n                    key={mIdx}\n                    className=\"rounded-sm border border-border/40 bg-background/60 p-1.5\"\n                  >\n                    <span className=\"text-muted-foreground\">\n                      Match {mIdx + 1}:{\" \"}\n                    </span>\n                    <span className=\"font-medium\">&quot;{m.match}&quot;</span>\n                    <div className=\"mt-0.5 ml-3 flex flex-wrap gap-x-3 gap-y-0.5\">\n                      {m.groups.map((g, gIdx) => (\n                        <div key={gIdx} className=\"text-muted-foreground\">\n                          <span className=\"font-medium text-primary\">\n                            {g.name ? `$${g.name}` : `Group ${g.number}`}\n                          </span>\n                          :{\" \"}\n                          <span className=\"text-foreground\">\n                            &quot;{g.value}&quot;\n                          </span>\n                        </div>\n                      ))}\n                    </div>\n                  </div>\n                ))}\n                {matches.length > 10 && (\n                  <p className=\"text-[10px] text-muted-foreground italic\">\n                    + {matches.length - 10} more matches\n                  </p>\n                )}\n              </div>\n            </div>\n          )}\n        </div>\n      )}\n\n      {name && (\n        <input type=\"hidden\" name={name} value={pattern} disabled={disabled} />\n      )}\n    </div>\n  )\n}\n\nexport { RegexInput }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/default/lib/regex-input-utils.ts",
      "content": "export interface RegexFlagInfo {\n  flag: string\n  label: string\n  description: string\n}\n\nexport const REGEX_FLAGS: Record<string, RegexFlagInfo> = {\n  i: {\n    flag: \"i\",\n    label: \"Case insensitive\",\n    description: \"Case-insensitive matching\",\n  },\n  m: {\n    flag: \"m\",\n    label: \"Multiline\",\n    description: \"^ and $ match start and end of each line\",\n  },\n  s: {\n    flag: \"s\",\n    label: \"Dot all\",\n    description: \". matches newlines as well\",\n  },\n  u: {\n    flag: \"u\",\n    label: \"Unicode\",\n    description: \"Treat pattern as a sequence of Unicode code points\",\n  },\n  g: {\n    flag: \"g\",\n    label: \"Global\",\n    description: \"Find all matches rather than stopping after first\",\n  },\n}\n\nexport const DEFAULT_AVAILABLE_FLAGS = [\"i\", \"m\", \"s\"] as const\n\nexport interface RegexCaptureGroup {\n  number: number\n  name?: string\n  value: string\n  start: number\n  end: number\n}\n\nexport interface RegexMatch {\n  match: string\n  index: number\n  length: number\n  groups: RegexCaptureGroup[]\n}\n\nexport interface RegexValidationResult {\n  isValid: boolean\n  error: string | null\n  regex: RegExp | null\n}\n\nexport interface RegexMatchOptions {\n  maxMatches?: number\n  maxSampleLength?: number\n  maxIterations?: number\n  timeoutMs?: number\n}\n\nexport interface RegexMatchResult {\n  matches: RegexMatch[]\n  matchCount: number\n  truncated: boolean\n  executionTimeMs: number\n  error: string | null\n}\n\nexport interface RegexSegment {\n  text: string\n  isMatch: boolean\n  matchIndex?: number\n}\n\n/**\n * Normalizes flags by removing duplicate or invalid characters and sorting alphabetically.\n */\nexport function normalizeFlags(flags: string): string {\n  if (!flags) return \"\"\n  const valid = new Set([\"d\", \"g\", \"i\", \"m\", \"s\", \"u\", \"v\", \"y\"])\n  const unique = new Set<string>()\n  for (const char of flags) {\n    if (valid.has(char)) {\n      unique.add(char)\n    }\n  }\n  return Array.from(unique).sort().join(\"\")\n}\n\n/**\n * Toggles a flag in the current flags string.\n * Rejects invalid flag characters.\n */\nexport function toggleFlag(currentFlags: string, flag: string): string {\n  if (!/^[dgimsuyv]$/.test(flag)) {\n    return normalizeFlags(currentFlags)\n  }\n  const norm = normalizeFlags(currentFlags)\n  const set = new Set(norm)\n  if (set.has(flag)) {\n    set.delete(flag)\n  } else {\n    set.add(flag)\n  }\n  return Array.from(set).sort().join(\"\")\n}\n\n/**\n * Validates a regular expression pattern and flags.\n */\nexport function validateRegex(\n  pattern: string,\n  flags: string = \"\"\n): RegexValidationResult {\n  if (!pattern) {\n    return { isValid: true, error: null, regex: null }\n  }\n\n  try {\n    const cleanFlags = normalizeFlags(flags)\n    const regex = new RegExp(pattern, cleanFlags)\n    return { isValid: true, error: null, regex }\n  } catch (err) {\n    const message =\n      err instanceof Error ? err.message : \"Invalid regular expression syntax\"\n    return { isValid: false, error: message, regex: null }\n  }\n}\n\ntype RegExpExecWithIndices = RegExpExecArray & {\n  indices?: Array<[number, number] | undefined> & {\n    groups?: Record<string, [number, number] | undefined>\n  }\n}\n\n/**\n * Finds all matches and capture groups within sample text.\n * Enforces execution limits (sample length cap, match cap, iteration cap,\n * inter-iteration timeout check, and zero-length loop guard).\n * Note: for interruptible bounding of a single catastrophic regex.exec call\n * in browser environments, use `findRegexMatchesAsync`.\n */\nexport function findRegexMatches(\n  pattern: string,\n  flags: string,\n  sample: string,\n  options?: RegexMatchOptions\n): RegexMatchResult {\n  const maxMatches = options?.maxMatches ?? 100\n  const maxSampleLength = options?.maxSampleLength ?? 20000\n  const maxIterations = options?.maxIterations ?? 5000\n  const timeoutMs = options?.timeoutMs ?? 150\n\n  if (!pattern || !sample || maxMatches <= 0) {\n    return {\n      matches: [],\n      matchCount: 0,\n      truncated: false,\n      executionTimeMs: 0,\n      error: null,\n    }\n  }\n\n  const effectiveSample =\n    sample.length > maxSampleLength ? sample.slice(0, maxSampleLength) : sample\n  const truncatedByLength = sample.length > maxSampleLength\n\n  // Compile regex with global flag to iterate matches and 'd' flag for accurate capture indices\n  const baseFlags = normalizeFlags(flags)\n  const flagSet = new Set(baseFlags.split(\"\"))\n  flagSet.add(\"g\")\n  flagSet.add(\"d\")\n  const searchFlagsWithIndices = Array.from(flagSet).join(\"\")\n\n  let regex: RegExp\n  try {\n    regex = new RegExp(pattern, searchFlagsWithIndices)\n  } catch {\n    // Fallback if 'd' flag is not supported\n    try {\n      regex = new RegExp(\n        pattern,\n        baseFlags.includes(\"g\") ? baseFlags : baseFlags + \"g\"\n      )\n    } catch (err) {\n      return {\n        matches: [],\n        matchCount: 0,\n        truncated: false,\n        executionTimeMs: 0,\n        error:\n          err instanceof Error ? err.message : \"Invalid regular expression\",\n      }\n    }\n  }\n\n  const startTime =\n    typeof performance !== \"undefined\" ? performance.now() : Date.now()\n  const matches: RegexMatch[] = []\n  let iterations = 0\n  let truncated = truncatedByLength\n\n  let execResult: RegExpExecArray | null\n\n  while ((execResult = regex.exec(effectiveSample)) !== null) {\n    iterations++\n\n    const matchText = execResult[0]\n    const matchIndex = execResult.index\n\n    // Extract capture groups using indices when available\n    const groups: RegexCaptureGroup[] = []\n    const execWithIndices = execResult as RegExpExecWithIndices\n    const indices = execWithIndices.indices\n    const namedIndices = indices?.groups\n    const namedGroups = execResult.groups ?? {}\n\n    // In RegExpExecArray, index 0 is full match, 1..n are capture groups\n    for (let i = 1; i < execResult.length; i++) {\n      const val = execResult[i]\n      if (val !== undefined) {\n        const range = indices?.[i]\n        let start = range ? range[0] : -1\n        let end = range ? range[1] : -1\n\n        let groupName: string | undefined\n        if (namedIndices) {\n          for (const [name, gRange] of Object.entries(namedIndices)) {\n            if (\n              gRange &&\n              gRange[0] === start &&\n              gRange[1] === end &&\n              !groups.some((g) => g.name === name)\n            ) {\n              groupName = name\n              break\n            }\n          }\n        } else {\n          for (const [name, gVal] of Object.entries(namedGroups)) {\n            if (gVal === val && !groups.some((g) => g.name === name)) {\n              groupName = name\n              break\n            }\n          }\n        }\n\n        if (start === -1) {\n          const groupStart = matchText.indexOf(val)\n          start = groupStart >= 0 ? matchIndex + groupStart : matchIndex\n          end = start + val.length\n        }\n\n        groups.push({\n          number: i,\n          name: groupName,\n          value: val,\n          start,\n          end,\n        })\n      }\n    }\n\n    matches.push({\n      match: matchText,\n      index: matchIndex,\n      length: matchText.length,\n      groups,\n    })\n\n    if (matches.length >= maxMatches) {\n      truncated = true\n      break\n    }\n\n    // Guard against zero-length matches (e.g. ^, a*, (?=...)) creating infinite loops\n    // Advance with Unicode code-point semantics when u or v flag is present\n    if (matchText.length === 0) {\n      const isUnicode = baseFlags.includes(\"u\") || baseFlags.includes(\"v\")\n      const codePoint = effectiveSample.codePointAt(matchIndex) ?? 0\n      const step = isUnicode && codePoint > 0xffff ? 2 : 1\n      regex.lastIndex = matchIndex + step\n      if (regex.lastIndex > effectiveSample.length) {\n        break\n      }\n    }\n\n    const elapsed =\n      (typeof performance !== \"undefined\" ? performance.now() : Date.now()) -\n      startTime\n    if (iterations >= maxIterations || elapsed >= timeoutMs) {\n      truncated = true\n      break\n    }\n  }\n\n  const executionTimeMs =\n    (typeof performance !== \"undefined\" ? performance.now() : Date.now()) -\n    startTime\n\n  return {\n    matches,\n    matchCount: matches.length,\n    truncated,\n    executionTimeMs: Math.round(executionTimeMs * 10) / 10,\n    error: null,\n  }\n}\n\nfunction createRegexWorkerScript(): string {\n  return `${normalizeFlags.toString()}\n${findRegexMatches.toString()}\nself.onmessage = function (event) {\n  var data = event.data\n  self.postMessage(\n    findRegexMatches(data.pattern, data.flags, data.sample, data.options)\n  )\n}`\n}\n\n/**\n * Runs `findRegexMatches` inside an interruptible Web Worker when available so\n * catastrophic backtracking can be terminated after `timeoutMs` or on abort\n * without blocking the main thread. Falls back to `findRegexMatches` when\n * Workers are unavailable.\n */\nexport function findRegexMatchesAsync(\n  pattern: string,\n  flags: string,\n  sample: string,\n  options?: RegexMatchOptions & { signal?: AbortSignal }\n): Promise<RegexMatchResult> {\n  const maxMatches = options?.maxMatches ?? 100\n  const timeoutMs = options?.timeoutMs ?? 150\n  const signal = options?.signal\n\n  if (signal?.aborted) {\n    return Promise.resolve({\n      matches: [],\n      matchCount: 0,\n      truncated: false,\n      executionTimeMs: 0,\n      error: null,\n    })\n  }\n\n  if (\n    !pattern ||\n    !sample ||\n    maxMatches <= 0 ||\n    typeof Worker === \"undefined\" ||\n    typeof Blob === \"undefined\" ||\n    typeof URL === \"undefined\" ||\n    typeof URL.createObjectURL !== \"function\"\n  ) {\n    return Promise.resolve(findRegexMatches(pattern, flags, sample, options))\n  }\n\n  return new Promise((resolve) => {\n    const workerOptions: RegexMatchOptions = {\n      maxMatches: options?.maxMatches,\n      maxSampleLength: options?.maxSampleLength,\n      maxIterations: options?.maxIterations,\n      timeoutMs,\n    }\n\n    let worker: Worker\n    let blobUrl: string | undefined\n    try {\n      const blob = new Blob([createRegexWorkerScript()], {\n        type: \"text/javascript\",\n      })\n      blobUrl = URL.createObjectURL(blob)\n      worker = new Worker(blobUrl)\n    } catch {\n      if (blobUrl) URL.revokeObjectURL(blobUrl)\n      resolve(findRegexMatches(pattern, flags, sample, workerOptions))\n      return\n    }\n\n    const activeBlobUrl = blobUrl\n    let settled = false\n\n    const finish = (result: RegexMatchResult) => {\n      if (settled) return\n      settled = true\n      clearTimeout(timer)\n      signal?.removeEventListener(\"abort\", onAbort)\n      worker.terminate()\n      URL.revokeObjectURL(activeBlobUrl)\n      resolve(result)\n    }\n\n    const onAbort = () => {\n      finish({\n        matches: [],\n        matchCount: 0,\n        truncated: false,\n        executionTimeMs: 0,\n        error: null,\n      })\n    }\n\n    signal?.addEventListener(\"abort\", onAbort, { once: true })\n\n    const timer = setTimeout(() => {\n      finish({\n        matches: [],\n        matchCount: 0,\n        truncated: true,\n        executionTimeMs: timeoutMs,\n        error: null,\n      })\n    }, timeoutMs)\n\n    worker.onmessage = (event: MessageEvent<RegexMatchResult>) => {\n      finish(event.data)\n    }\n\n    worker.onerror = () => {\n      finish({\n        matches: [],\n        matchCount: 0,\n        truncated: false,\n        executionTimeMs: 0,\n        error: \"Regex worker failed\",\n      })\n    }\n\n    worker.postMessage({\n      pattern,\n      flags,\n      sample,\n      options: workerOptions,\n    })\n  })\n}\n\n/**\n * Splits sample text into match and non-match segments for highlighting.\n */\nexport function highlightSampleText(\n  sample: string,\n  matches: RegexMatch[]\n): RegexSegment[] {\n  if (!sample) return []\n  if (!matches || matches.length === 0) {\n    return [{ text: sample, isMatch: false }]\n  }\n\n  const segments: RegexSegment[] = []\n  let currentIndex = 0\n\n  for (let i = 0; i < matches.length; i++) {\n    const m = matches[i]\n    if (m.index > currentIndex) {\n      segments.push({\n        text: sample.slice(currentIndex, m.index),\n        isMatch: false,\n      })\n    }\n\n    if (m.length > 0) {\n      segments.push({\n        text: sample.slice(m.index, m.index + m.length),\n        isMatch: true,\n        matchIndex: i + 1,\n      })\n    }\n\n    currentIndex = Math.max(currentIndex, m.index + m.length)\n  }\n\n  if (currentIndex < sample.length) {\n    segments.push({\n      text: sample.slice(currentIndex),\n      isMatch: false,\n    })\n  }\n\n  return segments\n}\n",
      "type": "registry:lib"
    }
  ],
  "type": "registry:ui"
}