@digitaldefiance/branded-enum 0.0.2 → 0.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/cjs/index.js +149 -0
  2. package/dist/cjs/index.js.map +1 -0
  3. package/dist/cjs/lib/accessors.js +55 -0
  4. package/dist/cjs/lib/accessors.js.map +1 -0
  5. package/dist/cjs/lib/advanced.js +558 -0
  6. package/dist/cjs/lib/advanced.js.map +1 -0
  7. package/dist/cjs/lib/branded-enum.js +15 -0
  8. package/dist/cjs/lib/branded-enum.js.map +1 -0
  9. package/dist/cjs/lib/decorators.js +202 -0
  10. package/dist/cjs/lib/decorators.js.map +1 -0
  11. package/dist/cjs/lib/factory.js +45 -0
  12. package/dist/cjs/lib/factory.js.map +1 -0
  13. package/dist/cjs/lib/guards.js +119 -0
  14. package/dist/cjs/lib/guards.js.map +1 -0
  15. package/dist/cjs/lib/merge.js +47 -0
  16. package/dist/cjs/lib/merge.js.map +1 -0
  17. package/dist/cjs/lib/registry.js +85 -0
  18. package/dist/cjs/lib/registry.js.map +1 -0
  19. package/dist/cjs/lib/types.js +38 -0
  20. package/dist/cjs/lib/types.js.map +1 -0
  21. package/dist/cjs/lib/utils.js +80 -0
  22. package/dist/cjs/lib/utils.js.map +1 -0
  23. package/dist/cjs/package.json +1 -0
  24. package/dist/esm/index.d.ts.map +1 -0
  25. package/dist/esm/index.js.map +1 -0
  26. package/dist/esm/lib/accessors.d.ts.map +1 -0
  27. package/dist/esm/lib/accessors.js.map +1 -0
  28. package/dist/esm/lib/advanced.d.ts.map +1 -0
  29. package/dist/esm/lib/advanced.js.map +1 -0
  30. package/dist/esm/lib/branded-enum.d.ts.map +1 -0
  31. package/dist/esm/lib/branded-enum.js.map +1 -0
  32. package/dist/esm/lib/decorators.d.ts.map +1 -0
  33. package/dist/esm/lib/decorators.js.map +1 -0
  34. package/dist/esm/lib/factory.d.ts.map +1 -0
  35. package/dist/esm/lib/factory.js.map +1 -0
  36. package/dist/esm/lib/guards.d.ts.map +1 -0
  37. package/dist/esm/lib/guards.js.map +1 -0
  38. package/dist/esm/lib/merge.d.ts.map +1 -0
  39. package/dist/esm/lib/merge.js.map +1 -0
  40. package/dist/esm/lib/registry.d.ts.map +1 -0
  41. package/dist/esm/lib/registry.js.map +1 -0
  42. package/dist/esm/lib/types.d.ts.map +1 -0
  43. package/dist/esm/lib/types.js.map +1 -0
  44. package/dist/esm/lib/utils.d.ts.map +1 -0
  45. package/dist/esm/lib/utils.js.map +1 -0
  46. package/package.json +12 -9
  47. package/dist/index.d.ts.map +0 -1
  48. package/dist/index.js.map +0 -1
  49. package/dist/lib/accessors.d.ts.map +0 -1
  50. package/dist/lib/accessors.js.map +0 -1
  51. package/dist/lib/advanced.d.ts.map +0 -1
  52. package/dist/lib/advanced.js.map +0 -1
  53. package/dist/lib/branded-enum.d.ts.map +0 -1
  54. package/dist/lib/branded-enum.js.map +0 -1
  55. package/dist/lib/decorators.d.ts.map +0 -1
  56. package/dist/lib/decorators.js.map +0 -1
  57. package/dist/lib/factory.d.ts.map +0 -1
  58. package/dist/lib/factory.js.map +0 -1
  59. package/dist/lib/guards.d.ts.map +0 -1
  60. package/dist/lib/guards.js.map +0 -1
  61. package/dist/lib/merge.d.ts.map +0 -1
  62. package/dist/lib/merge.js.map +0 -1
  63. package/dist/lib/registry.d.ts.map +0 -1
  64. package/dist/lib/registry.js.map +0 -1
  65. package/dist/lib/types.d.ts.map +0 -1
  66. package/dist/lib/types.js.map +0 -1
  67. package/dist/lib/utils.d.ts.map +0 -1
  68. package/dist/lib/utils.js.map +0 -1
  69. /package/dist/{index.d.ts → esm/index.d.ts} +0 -0
  70. /package/dist/{index.js → esm/index.js} +0 -0
  71. /package/dist/{lib → esm/lib}/accessors.d.ts +0 -0
  72. /package/dist/{lib → esm/lib}/accessors.js +0 -0
  73. /package/dist/{lib → esm/lib}/advanced.d.ts +0 -0
  74. /package/dist/{lib → esm/lib}/advanced.js +0 -0
  75. /package/dist/{lib → esm/lib}/branded-enum.d.ts +0 -0
  76. /package/dist/{lib → esm/lib}/branded-enum.js +0 -0
  77. /package/dist/{lib → esm/lib}/decorators.d.ts +0 -0
  78. /package/dist/{lib → esm/lib}/decorators.js +0 -0
  79. /package/dist/{lib → esm/lib}/factory.d.ts +0 -0
  80. /package/dist/{lib → esm/lib}/factory.js +0 -0
  81. /package/dist/{lib → esm/lib}/guards.d.ts +0 -0
  82. /package/dist/{lib → esm/lib}/guards.js +0 -0
  83. /package/dist/{lib → esm/lib}/merge.d.ts +0 -0
  84. /package/dist/{lib → esm/lib}/merge.js +0 -0
  85. /package/dist/{lib → esm/lib}/registry.d.ts +0 -0
  86. /package/dist/{lib → esm/lib}/registry.js +0 -0
  87. /package/dist/{lib → esm/lib}/types.d.ts +0 -0
  88. /package/dist/{lib → esm/lib}/types.js +0 -0
  89. /package/dist/{lib → esm/lib}/utils.d.ts +0 -0
  90. /package/dist/{lib → esm/lib}/utils.js +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/lib/advanced.ts"],"sourcesContent":["/**\n * Advanced enum operations for branded enums.\n *\n * Provides functions for deriving new enums from existing ones,\n * including subsetting, exclusion, and transformation operations.\n */\n\nimport { AnyBrandedEnum, BrandedEnum, ENUM_ID, ENUM_VALUES, EnumKeys, EnumValues } from './types.js';\nimport { createBrandedEnum } from './factory.js';\n\n/**\n * Checks if an object is a branded enum (has Symbol metadata).\n *\n * @param obj - The object to check\n * @returns true if obj is a branded enum\n */\nfunction isBrandedEnum(obj: unknown): obj is AnyBrandedEnum {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n ENUM_ID in obj &&\n ENUM_VALUES in obj &&\n typeof (obj as AnyBrandedEnum)[ENUM_ID] === 'string' &&\n (obj as AnyBrandedEnum)[ENUM_VALUES] instanceof Set\n );\n}\n\n/**\n * Creates a new branded enum containing only the specified keys from the source enum.\n *\n * This function derives a subset of an existing branded enum by selecting specific keys.\n * The resulting enum is registered as an independent enum in the global registry.\n *\n * Type safety is maintained - the resulting enum's type reflects only the selected keys.\n *\n * @template E - The source branded enum type\n * @template K - The keys to include in the subset (must be keys of E)\n * @param newId - Unique identifier for the new subset enum. Must not already be registered.\n * @param sourceEnum - The branded enum to derive the subset from\n * @param keys - Array of keys to include in the subset. All keys must exist in sourceEnum.\n * @returns A new branded enum containing only the specified key-value pairs\n * @throws {Error} Throws `Error` with message `enumSubset requires a branded enum as the source`\n * if sourceEnum is not a valid branded enum.\n * @throws {Error} Throws `Error` with message `enumSubset requires at least one key`\n * if keys array is empty.\n * @throws {Error} Throws `Error` with message `Key \"${key}\" does not exist in enum \"${enumId}\"`\n * if any specified key does not exist in the source enum.\n * @throws {Error} Throws `Error` with message `Branded enum with ID \"${newId}\" already exists`\n * if newId is already registered.\n *\n * @example\n * // Basic usage - create a subset of colors\n * const AllColors = createBrandedEnum('all-colors', {\n * Red: 'red',\n * Green: 'green',\n * Blue: 'blue',\n * Yellow: 'yellow',\n * } as const);\n *\n * const PrimaryColors = enumSubset('primary-colors', AllColors, ['Red', 'Blue', 'Yellow']);\n * // PrimaryColors has: Red, Blue, Yellow (no Green)\n *\n * PrimaryColors.Red; // 'red'\n * PrimaryColors.Blue; // 'blue'\n * // PrimaryColors.Green; // TypeScript error - Green doesn't exist\n *\n * @example\n * // Type safety with subset\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * Archived: 'archived',\n * } as const);\n *\n * const ActiveStatuses = enumSubset('active-statuses', Status, ['Active', 'Pending']);\n * type ActiveStatusValue = typeof ActiveStatuses[keyof typeof ActiveStatuses];\n * // ActiveStatusValue = 'active' | 'pending'\n *\n * @example\n * // Error handling for invalid keys\n * try {\n * enumSubset('invalid', AllColors, ['Red', 'Purple']); // Purple doesn't exist\n * } catch (e) {\n * console.log(e.message);\n * // 'Key \"Purple\" does not exist in enum \"all-colors\"'\n * }\n */\nexport function enumSubset<\n E extends AnyBrandedEnum,\n K extends keyof E & string,\n>(\n newId: string,\n sourceEnum: E,\n keys: readonly K[]\n): BrandedEnum<Pick<E, K> & Record<string, string>> {\n // Validate that sourceEnum is a branded enum\n if (!isBrandedEnum(sourceEnum)) {\n throw new Error('enumSubset requires a branded enum as the source');\n }\n\n // Validate that keys array is not empty\n if (keys.length === 0) {\n throw new Error('enumSubset requires at least one key');\n }\n\n const sourceEnumId = sourceEnum[ENUM_ID];\n\n // Build the subset values object\n const subsetValues: Record<string, string> = {};\n\n for (const key of keys) {\n // Validate that the key exists in the source enum\n if (!(key in sourceEnum)) {\n throw new Error(\n `Key \"${key}\" does not exist in enum \"${sourceEnumId}\"`\n );\n }\n\n // Copy the key-value pair\n subsetValues[key] = (sourceEnum as Record<string, string>)[key];\n }\n\n // Create and return the new branded enum (this handles registration)\n return createBrandedEnum(newId, subsetValues) as BrandedEnum<\n Pick<E, K> & Record<string, string>\n >;\n}\n\n/**\n * Creates a new branded enum by excluding the specified keys from the source enum.\n *\n * This function derives a new enum from an existing branded enum by removing specific keys.\n * It is the complement of `enumSubset` - instead of specifying which keys to include,\n * you specify which keys to exclude.\n *\n * The resulting enum is registered as an independent enum in the global registry.\n * Type safety is maintained - the resulting enum's type reflects only the remaining keys.\n *\n * @template E - The source branded enum type\n * @template K - The keys to exclude from the result (must be keys of E)\n * @param newId - Unique identifier for the new enum. Must not already be registered.\n * @param sourceEnum - The branded enum to derive from\n * @param keysToExclude - Array of keys to exclude. All keys must exist in sourceEnum.\n * @returns A new branded enum containing all key-value pairs except the excluded ones\n * @throws {Error} Throws `Error` with message `enumExclude requires a branded enum as the source`\n * if sourceEnum is not a valid branded enum.\n * @throws {Error} Throws `Error` with message `enumExclude: excluding all keys would result in an empty enum`\n * if excluding all keys would leave no keys remaining.\n * @throws {Error} Throws `Error` with message `Key \"${key}\" does not exist in enum \"${enumId}\"`\n * if any specified key to exclude does not exist in the source enum.\n * @throws {Error} Throws `Error` with message `Branded enum with ID \"${newId}\" already exists`\n * if newId is already registered.\n *\n * @example\n * // Basic usage - exclude specific colors\n * const AllColors = createBrandedEnum('all-colors', {\n * Red: 'red',\n * Green: 'green',\n * Blue: 'blue',\n * Yellow: 'yellow',\n * } as const);\n *\n * const NonPrimaryColors = enumExclude('non-primary', AllColors, ['Red', 'Blue', 'Yellow']);\n * // NonPrimaryColors has only: Green\n *\n * NonPrimaryColors.Green; // 'green'\n * // NonPrimaryColors.Red; // TypeScript error - Red was excluded\n *\n * @example\n * // Exclude deprecated values\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * Deprecated: 'deprecated',\n * } as const);\n *\n * const CurrentStatuses = enumExclude('current-statuses', Status, ['Deprecated']);\n * type CurrentStatusValue = typeof CurrentStatuses[keyof typeof CurrentStatuses];\n * // CurrentStatusValue = 'active' | 'inactive' | 'pending'\n *\n * @example\n * // Error handling for invalid keys\n * try {\n * enumExclude('invalid', AllColors, ['Purple']); // Purple doesn't exist\n * } catch (e) {\n * console.log(e.message);\n * // 'Key \"Purple\" does not exist in enum \"all-colors\"'\n * }\n */\nexport function enumExclude<\n E extends AnyBrandedEnum,\n K extends keyof E & string,\n>(\n newId: string,\n sourceEnum: E,\n keysToExclude: readonly K[]\n): BrandedEnum<Omit<E, K> & Record<string, string>> {\n // Validate that sourceEnum is a branded enum\n if (!isBrandedEnum(sourceEnum)) {\n throw new Error('enumExclude requires a branded enum as the source');\n }\n\n const sourceEnumId = sourceEnum[ENUM_ID];\n\n // Validate that all keys to exclude exist in the source enum\n for (const key of keysToExclude) {\n if (!(key in sourceEnum)) {\n throw new Error(\n `Key \"${key}\" does not exist in enum \"${sourceEnumId}\"`\n );\n }\n }\n\n // Create a Set for O(1) lookup of excluded keys\n const excludeSet = new Set<string>(keysToExclude);\n\n // Get all keys from the source enum (excluding Symbol metadata)\n const allKeys = Object.keys(sourceEnum);\n\n // Build the result values object with non-excluded keys\n const resultValues: Record<string, string> = {};\n\n for (const key of allKeys) {\n if (!excludeSet.has(key)) {\n resultValues[key] = (sourceEnum as Record<string, string>)[key];\n }\n }\n\n // Validate that we have at least one key remaining\n if (Object.keys(resultValues).length === 0) {\n throw new Error(\n 'enumExclude: excluding all keys would result in an empty enum'\n );\n }\n\n // Create and return the new branded enum (this handles registration)\n return createBrandedEnum(newId, resultValues) as BrandedEnum<\n Omit<E, K> & Record<string, string>\n >;\n}\n\n/**\n * Type representing the result of mapping enum values through a transform function.\n * Preserves the keys but transforms the value types.\n */\ntype MappedEnumValues<E extends Record<string, string>> = {\n [K in keyof E]: string;\n};\n\n/**\n * Creates a new branded enum by transforming all values through a mapper function.\n *\n * This function derives a new enum from an existing branded enum by applying a\n * transformation function to each value. The keys remain unchanged, but the values\n * are transformed according to the provided mapper.\n *\n * Common use cases include:\n * - Prefixing values (e.g., adding a namespace)\n * - Suffixing values (e.g., adding a version)\n * - Case transformation (e.g., uppercase, lowercase)\n * - Custom transformations (e.g., encoding, formatting)\n *\n * The resulting enum is registered as an independent enum in the global registry.\n *\n * @template E - The source branded enum type\n * @param newId - Unique identifier for the new enum. Must not already be registered.\n * @param sourceEnum - The branded enum to derive from\n * @param mapper - Function that transforms each value. Receives the original value\n * and the key, and returns the transformed value.\n * @returns A new branded enum with transformed values\n * @throws {Error} Throws `Error` with message `enumMap requires a branded enum as the source`\n * if sourceEnum is not a valid branded enum.\n * @throws {Error} Throws `Error` with message `enumMap mapper must return a string`\n * if the mapper function returns a non-string value.\n * @throws {Error} Throws `Error` with message `Branded enum with ID \"${newId}\" already exists`\n * if newId is already registered.\n *\n * @example\n * // Prefix all values with a namespace\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * } as const);\n *\n * const PrefixedStatus = enumMap('prefixed-status', Status, (value) => `app.${value}`);\n * // PrefixedStatus.Active === 'app.active'\n * // PrefixedStatus.Inactive === 'app.inactive'\n *\n * @example\n * // Uppercase all values\n * const Colors = createBrandedEnum('colors', {\n * Red: 'red',\n * Green: 'green',\n * Blue: 'blue',\n * } as const);\n *\n * const UpperColors = enumMap('upper-colors', Colors, (value) => value.toUpperCase());\n * // UpperColors.Red === 'RED'\n * // UpperColors.Green === 'GREEN'\n * // UpperColors.Blue === 'BLUE'\n *\n * @example\n * // Transform with key context\n * const Sizes = createBrandedEnum('sizes', {\n * Small: 's',\n * Medium: 'm',\n * Large: 'l',\n * } as const);\n *\n * const VerboseSizes = enumMap('verbose-sizes', Sizes, (value, key) => `${key.toLowerCase()}-${value}`);\n * // VerboseSizes.Small === 'small-s'\n * // VerboseSizes.Medium === 'medium-m'\n * // VerboseSizes.Large === 'large-l'\n */\nexport function enumMap<E extends AnyBrandedEnum>(\n newId: string,\n sourceEnum: E,\n mapper: (value: string, key: string) => string\n): BrandedEnum<MappedEnumValues<E> & Record<string, string>> {\n // Validate that sourceEnum is a branded enum\n if (!isBrandedEnum(sourceEnum)) {\n throw new Error('enumMap requires a branded enum as the source');\n }\n\n // Get all keys from the source enum (excluding Symbol metadata)\n const allKeys = Object.keys(sourceEnum);\n\n // Build the result values object with transformed values\n const resultValues: Record<string, string> = {};\n\n for (const key of allKeys) {\n const originalValue = sourceEnum[key as keyof E] as string;\n const transformedValue = mapper(originalValue, key);\n\n // Validate that the mapper returned a string\n if (typeof transformedValue !== 'string') {\n throw new Error('enumMap mapper must return a string');\n }\n\n resultValues[key] = transformedValue;\n }\n\n // Create and return the new branded enum (this handles registration)\n return createBrandedEnum(newId, resultValues) as BrandedEnum<\n MappedEnumValues<E> & Record<string, string>\n >;\n}\n\n/**\n * Type representing an enum where each key maps to itself as a value.\n */\ntype KeysAsValues<K extends readonly string[]> = {\n [P in K[number]]: P;\n};\n\n/**\n * Creates a branded enum from an array of keys where each key equals its value.\n *\n * This is a convenience function for the common pattern where enum keys and values\n * are identical, such as `{ Active: 'Active', Inactive: 'Inactive' }`.\n *\n * The resulting enum is registered as an independent enum in the global registry.\n * Type safety is maintained - the resulting enum's type reflects the exact literal\n * types of the provided keys.\n *\n * @template K - The array of string keys (use `as const` for literal types)\n * @param enumId - Unique identifier for the new enum. Must not already be registered.\n * @param keys - Array of strings that will become both keys and values.\n * Use `as const` for literal type inference.\n * @returns A new branded enum where each key maps to itself\n * @throws {Error} Throws `Error` with message `enumFromKeys requires at least one key`\n * if keys array is empty.\n * @throws {Error} Throws `Error` with message `enumFromKeys requires all keys to be non-empty strings`\n * if any key is not a non-empty string.\n * @throws {Error} Throws `Error` with message `enumFromKeys: duplicate key \"${key}\" found`\n * if the keys array contains duplicates.\n * @throws {Error} Throws `Error` with message `Branded enum with ID \"${enumId}\" already exists`\n * if enumId is already registered.\n *\n * @example\n * // Basic usage - create enum from string array\n * const Status = enumFromKeys('status', ['Active', 'Inactive', 'Pending'] as const);\n * // Equivalent to: { Active: 'Active', Inactive: 'Inactive', Pending: 'Pending' }\n *\n * Status.Active; // 'Active'\n * Status.Inactive; // 'Inactive'\n * Status.Pending; // 'Pending'\n *\n * @example\n * // Type inference with as const\n * const Colors = enumFromKeys('colors', ['Red', 'Green', 'Blue'] as const);\n * type ColorValue = typeof Colors[keyof typeof Colors];\n * // ColorValue = 'Red' | 'Green' | 'Blue'\n *\n * @example\n * // Useful for string literal unions\n * const Directions = enumFromKeys('directions', ['North', 'South', 'East', 'West'] as const);\n *\n * function move(direction: typeof Directions[keyof typeof Directions]) {\n * // direction is 'North' | 'South' | 'East' | 'West'\n * }\n *\n * move(Directions.North); // OK\n * move('North'); // Also OK due to literal type\n *\n * @example\n * // Error handling\n * try {\n * enumFromKeys('empty', []); // Empty array\n * } catch (e) {\n * console.log(e.message);\n * // 'enumFromKeys requires at least one key'\n * }\n */\nexport function enumFromKeys<K extends readonly string[]>(\n enumId: string,\n keys: K\n): BrandedEnum<KeysAsValues<K> & Record<string, string>> {\n // Validate that keys array is not empty\n if (keys.length === 0) {\n throw new Error('enumFromKeys requires at least one key');\n }\n\n // Track seen keys to detect duplicates\n const seenKeys = new Set<string>();\n\n // Build the values object where each key maps to itself\n const values: Record<string, string> = {};\n\n for (const key of keys) {\n // Validate that each key is a non-empty string\n if (typeof key !== 'string' || key.length === 0) {\n throw new Error('enumFromKeys requires all keys to be non-empty strings');\n }\n\n // Check for duplicate keys\n if (seenKeys.has(key)) {\n throw new Error(`enumFromKeys: duplicate key \"${key}\" found`);\n }\n\n seenKeys.add(key);\n values[key] = key;\n }\n\n // Create and return the new branded enum (this handles registration)\n return createBrandedEnum(enumId, values) as BrandedEnum<\n KeysAsValues<K> & Record<string, string>\n >;\n}\n\n/**\n * Result of comparing two branded enums with enumDiff.\n */\nexport interface EnumDiffResult {\n /** Keys that exist only in the first enum */\n readonly onlyInFirst: ReadonlyArray<{ key: string; value: string }>;\n /** Keys that exist only in the second enum */\n readonly onlyInSecond: ReadonlyArray<{ key: string; value: string }>;\n /** Keys that exist in both enums but have different values */\n readonly differentValues: ReadonlyArray<{\n key: string;\n firstValue: string;\n secondValue: string;\n }>;\n /** Keys that exist in both enums with the same values */\n readonly sameValues: ReadonlyArray<{ key: string; value: string }>;\n}\n\n/**\n * Compares two branded enums and returns their differences.\n *\n * This function analyzes two branded enums and categorizes their keys into:\n * - Keys only in the first enum\n * - Keys only in the second enum\n * - Keys in both with different values\n * - Keys in both with the same values\n *\n * Useful for:\n * - Migration: Identifying what changed between enum versions\n * - Debugging: Understanding differences between similar enums\n * - Validation: Ensuring enums have expected overlap or differences\n *\n * @template E1 - The first branded enum type\n * @template E2 - The second branded enum type\n * @param firstEnum - The first branded enum to compare\n * @param secondEnum - The second branded enum to compare\n * @returns An EnumDiffResult object containing categorized differences\n * @throws {Error} Throws `Error` with message `enumDiff requires branded enums as arguments`\n * if either argument is not a valid branded enum.\n *\n * @example\n * // Compare two versions of a status enum\n * const StatusV1 = createBrandedEnum('status-v1', {\n * Active: 'active',\n * Inactive: 'inactive',\n * } as const);\n *\n * const StatusV2 = createBrandedEnum('status-v2', {\n * Active: 'active',\n * Inactive: 'disabled', // Changed value\n * Pending: 'pending', // New key\n * } as const);\n *\n * const diff = enumDiff(StatusV1, StatusV2);\n * // diff.onlyInFirst: []\n * // diff.onlyInSecond: [{ key: 'Pending', value: 'pending' }]\n * // diff.differentValues: [{ key: 'Inactive', firstValue: 'inactive', secondValue: 'disabled' }]\n * // diff.sameValues: [{ key: 'Active', value: 'active' }]\n *\n * @example\n * // Find keys removed between versions\n * const ColorsOld = createBrandedEnum('colors-old', {\n * Red: 'red',\n * Green: 'green',\n * Blue: 'blue',\n * } as const);\n *\n * const ColorsNew = createBrandedEnum('colors-new', {\n * Red: 'red',\n * Blue: 'blue',\n * } as const);\n *\n * const diff = enumDiff(ColorsOld, ColorsNew);\n * // diff.onlyInFirst: [{ key: 'Green', value: 'green' }]\n * // diff.onlyInSecond: []\n *\n * @example\n * // Check if enums are identical\n * const diff = enumDiff(enumA, enumB);\n * const areIdentical = diff.onlyInFirst.length === 0 &&\n * diff.onlyInSecond.length === 0 &&\n * diff.differentValues.length === 0;\n */\nexport function enumDiff(\n firstEnum: AnyBrandedEnum,\n secondEnum: AnyBrandedEnum\n): EnumDiffResult {\n // Validate that both arguments are branded enums\n if (!isBrandedEnum(firstEnum) || !isBrandedEnum(secondEnum)) {\n throw new Error('enumDiff requires branded enums as arguments');\n }\n\n // Get all keys from both enums (excluding Symbol metadata)\n const firstKeys = new Set(Object.keys(firstEnum));\n const secondKeys = new Set(Object.keys(secondEnum));\n\n const onlyInFirst: Array<{ key: string; value: string }> = [];\n const onlyInSecond: Array<{ key: string; value: string }> = [];\n const differentValues: Array<{\n key: string;\n firstValue: string;\n secondValue: string;\n }> = [];\n const sameValues: Array<{ key: string; value: string }> = [];\n\n // Find keys only in first enum and keys in both\n for (const key of firstKeys) {\n const firstValue = (firstEnum as Record<string, string>)[key];\n\n if (!secondKeys.has(key)) {\n // Key only exists in first enum\n onlyInFirst.push({ key, value: firstValue });\n } else {\n // Key exists in both - compare values\n const secondValue = (secondEnum as Record<string, string>)[key];\n\n if (firstValue === secondValue) {\n sameValues.push({ key, value: firstValue });\n } else {\n differentValues.push({ key, firstValue, secondValue });\n }\n }\n }\n\n // Find keys only in second enum\n for (const key of secondKeys) {\n if (!firstKeys.has(key)) {\n const secondValue = (secondEnum as Record<string, string>)[key];\n onlyInSecond.push({ key, value: secondValue });\n }\n }\n\n return {\n onlyInFirst,\n onlyInSecond,\n differentValues,\n sameValues,\n };\n}\n\n/**\n * Result entry for a shared value found across multiple enums.\n */\nexport interface EnumIntersectEntry {\n /** The shared value that exists in multiple enums */\n readonly value: string;\n /** Array of enum IDs that contain this value */\n readonly enumIds: readonly string[];\n}\n\n/**\n * Finds values that exist in multiple branded enums.\n *\n * This function analyzes multiple branded enums and identifies values that\n * appear in more than one enum. For each shared value, it returns the value\n * along with the IDs of all enums that contain it.\n *\n * Useful for:\n * - Detecting value collisions across enums\n * - Finding common values for potential refactoring\n * - Debugging i18n key conflicts\n * - Identifying intentional value overlaps\n *\n * @param enums - Array of branded enums to analyze for intersections\n * @returns Array of EnumIntersectEntry objects, each containing a shared value\n * and the IDs of enums containing that value. Only values appearing in 2+\n * enums are included. Results are sorted by value for consistent ordering.\n * @throws {Error} Throws `Error` with message `enumIntersect requires at least two branded enums`\n * if fewer than two enums are provided.\n * @throws {Error} Throws `Error` with message `enumIntersect requires all arguments to be branded enums`\n * if any argument is not a valid branded enum.\n *\n * @example\n * // Find shared values between color enums\n * const PrimaryColors = createBrandedEnum('primary', {\n * Red: 'red',\n * Blue: 'blue',\n * Yellow: 'yellow',\n * } as const);\n *\n * const WarmColors = createBrandedEnum('warm', {\n * Red: 'red',\n * Orange: 'orange',\n * Yellow: 'yellow',\n * } as const);\n *\n * const shared = enumIntersect(PrimaryColors, WarmColors);\n * // shared = [\n * // { value: 'red', enumIds: ['primary', 'warm'] },\n * // { value: 'yellow', enumIds: ['primary', 'warm'] }\n * // ]\n *\n * @example\n * // Detect i18n key collisions across multiple libraries\n * const LibAKeys = createBrandedEnum('lib-a', {\n * Submit: 'submit',\n * Cancel: 'cancel',\n * } as const);\n *\n * const LibBKeys = createBrandedEnum('lib-b', {\n * Submit: 'submit',\n * Reset: 'reset',\n * } as const);\n *\n * const LibCKeys = createBrandedEnum('lib-c', {\n * Submit: 'submit',\n * Clear: 'clear',\n * } as const);\n *\n * const collisions = enumIntersect(LibAKeys, LibBKeys, LibCKeys);\n * // collisions = [\n * // { value: 'submit', enumIds: ['lib-a', 'lib-b', 'lib-c'] }\n * // ]\n *\n * @example\n * // Check if enums have any overlap\n * const shared = enumIntersect(enumA, enumB);\n * if (shared.length === 0) {\n * console.log('No shared values between enums');\n * }\n */\nexport function enumIntersect(\n ...enums: AnyBrandedEnum[]\n): EnumIntersectEntry[] {\n // Validate that at least two enums are provided\n if (enums.length < 2) {\n throw new Error('enumIntersect requires at least two branded enums');\n }\n\n // Validate that all arguments are branded enums\n for (const enumObj of enums) {\n if (!isBrandedEnum(enumObj)) {\n throw new Error('enumIntersect requires all arguments to be branded enums');\n }\n }\n\n // Build a map of value -> Set of enum IDs containing that value\n const valueToEnumIds = new Map<string, Set<string>>();\n\n for (const enumObj of enums) {\n const enumId = enumObj[ENUM_ID];\n const values = enumObj[ENUM_VALUES];\n\n for (const value of values) {\n if (!valueToEnumIds.has(value)) {\n valueToEnumIds.set(value, new Set());\n }\n valueToEnumIds.get(value)!.add(enumId);\n }\n }\n\n // Filter to only values that appear in multiple enums\n const result: EnumIntersectEntry[] = [];\n\n for (const [value, enumIds] of valueToEnumIds) {\n if (enumIds.size >= 2) {\n result.push({\n value,\n enumIds: Array.from(enumIds).sort(),\n });\n }\n }\n\n // Sort by value for consistent ordering\n result.sort((a, b) => a.value.localeCompare(b.value));\n\n return result;\n}\n\n/**\n * Converts a branded enum to a plain Record object, stripping all metadata.\n *\n * This function creates a new plain object containing only the key-value pairs\n * from the branded enum, without any Symbol metadata properties. The result is\n * a simple `Record<string, string>` that can be safely serialized, spread, or\n * used in contexts where branded enum metadata is not needed.\n *\n * Useful for:\n * - Serialization scenarios where you need a plain object\n * - Interoperability with APIs that expect plain objects\n * - Creating snapshots of enum state without metadata\n * - Passing enum data to external systems\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to convert\n * @returns A plain Record<string, string> containing only the key-value pairs\n * @throws {Error} Throws `Error` with message `enumToRecord requires a branded enum`\n * if enumObj is not a valid branded enum.\n *\n * @example\n * // Basic usage - convert to plain object\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * } as const);\n *\n * const plainStatus = enumToRecord(Status);\n * // plainStatus = { Active: 'active', Inactive: 'inactive', Pending: 'pending' }\n * // No Symbol metadata, just a plain object\n *\n * @example\n * // Serialization scenario\n * const Colors = createBrandedEnum('colors', {\n * Red: 'red',\n * Green: 'green',\n * Blue: 'blue',\n * } as const);\n *\n * // Send to an API that expects plain objects\n * const payload = {\n * availableColors: enumToRecord(Colors),\n * };\n * await fetch('/api/config', {\n * method: 'POST',\n * body: JSON.stringify(payload),\n * });\n *\n * @example\n * // Comparing with spread operator\n * const Status = createBrandedEnum('status', { Active: 'active' } as const);\n *\n * // Both produce the same result for enumerable properties:\n * const spread = { ...Status };\n * const record = enumToRecord(Status);\n * // spread and record are equivalent plain objects\n *\n * // But enumToRecord is explicit about intent and validates input\n *\n * @example\n * // Type safety\n * const Sizes = createBrandedEnum('sizes', {\n * Small: 's',\n * Medium: 'm',\n * Large: 'l',\n * } as const);\n *\n * const record = enumToRecord(Sizes);\n * // record type is Record<string, string>\n * // Can be used anywhere a plain object is expected\n */\nexport function enumToRecord<E extends AnyBrandedEnum>(\n enumObj: E\n): Record<string, string> {\n // Validate that enumObj is a branded enum\n if (!isBrandedEnum(enumObj)) {\n throw new Error('enumToRecord requires a branded enum');\n }\n\n // Create a new plain object with only the enumerable key-value pairs\n const result: Record<string, string> = {};\n\n for (const key of Object.keys(enumObj)) {\n result[key] = enumObj[key as keyof E] as string;\n }\n\n return result;\n}\n\n/**\n * The key used to store the enum watcher registry on globalThis.\n * Namespaced to avoid collisions with other libraries.\n */\nconst WATCHER_REGISTRY_KEY = '__brandedEnumWatcherRegistry__' as const;\n\n/**\n * Type of access event that triggered the callback.\n */\nexport type EnumAccessType = 'get' | 'has' | 'keys' | 'values' | 'entries';\n\n/**\n * Information about an enum access event.\n */\nexport interface EnumAccessEvent {\n /** The enum ID of the accessed enum */\n readonly enumId: string;\n /** The type of access that occurred */\n readonly accessType: EnumAccessType;\n /** The key that was accessed (for 'get' and 'has' types) */\n readonly key?: string;\n /** The value that was returned (for 'get' type) */\n readonly value?: string;\n /** Timestamp of the access */\n readonly timestamp: number;\n}\n\n/**\n * Callback function type for enum access events.\n */\nexport type EnumWatchCallback = (event: EnumAccessEvent) => void;\n\n/**\n * Internal registry for enum watchers.\n */\ninterface EnumWatcherRegistry {\n /** Map from enum ID to Set of callbacks */\n readonly watchers: Map<string, Set<EnumWatchCallback>>;\n /** Global callbacks that receive all enum access events */\n readonly globalWatchers: Set<EnumWatchCallback>;\n}\n\n/**\n * Gets or initializes the watcher registry on globalThis.\n */\nfunction getWatcherRegistry(): EnumWatcherRegistry {\n const global = globalThis as typeof globalThis & {\n [WATCHER_REGISTRY_KEY]?: EnumWatcherRegistry;\n };\n\n if (!global[WATCHER_REGISTRY_KEY]) {\n global[WATCHER_REGISTRY_KEY] = {\n watchers: new Map(),\n globalWatchers: new Set(),\n };\n }\n\n return global[WATCHER_REGISTRY_KEY];\n}\n\n/**\n * Result of calling watchEnum, containing the watched proxy and unwatch function.\n */\nexport interface WatchEnumResult<E extends AnyBrandedEnum> {\n /** The proxied enum that triggers callbacks on access */\n readonly watched: E;\n /** Function to remove the watcher and stop receiving callbacks */\n readonly unwatch: () => void;\n}\n\n/**\n * Creates a watched version of a branded enum that triggers callbacks on access.\n *\n * This function wraps a branded enum in a Proxy that intercepts property access\n * and calls registered callbacks. This is useful for debugging, development tooling,\n * and understanding how enums are used throughout an application.\n *\n * The watched enum behaves identically to the original enum - all values, metadata,\n * and type information are preserved. The only difference is that access events\n * are reported to the callback.\n *\n * **Note:** This feature is intended for development and debugging purposes.\n * Using watched enums in production may have performance implications due to\n * the Proxy overhead.\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to watch\n * @param callback - Function called whenever the enum is accessed\n * @returns An object containing the watched enum proxy and an unwatch function\n * @throws {Error} Throws `Error` with message `watchEnum requires a branded enum`\n * if enumObj is not a valid branded enum.\n *\n * @example\n * // Basic usage - log all enum accesses\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * } as const);\n *\n * const { watched, unwatch } = watchEnum(Status, (event) => {\n * console.log(`Accessed ${event.enumId}.${event.key} = ${event.value}`);\n * });\n *\n * watched.Active; // Logs: \"Accessed status.Active = active\"\n * watched.Inactive; // Logs: \"Accessed status.Inactive = inactive\"\n *\n * // Stop watching\n * unwatch();\n * watched.Active; // No longer logs\n *\n * @example\n * // Track enum usage for debugging\n * const accessLog: EnumAccessEvent[] = [];\n *\n * const { watched: WatchedColors } = watchEnum(Colors, (event) => {\n * accessLog.push(event);\n * });\n *\n * // Use the watched enum in your code\n * doSomething(WatchedColors.Red);\n * doSomethingElse(WatchedColors.Blue);\n *\n * // Later, analyze the access log\n * console.log(`Enum accessed ${accessLog.length} times`);\n * console.log('Keys accessed:', accessLog.map(e => e.key));\n *\n * @example\n * // Detect unused enum values\n * const usedKeys = new Set<string>();\n *\n * const { watched } = watchEnum(MyEnum, (event) => {\n * if (event.key) usedKeys.add(event.key);\n * });\n *\n * // After running your application/tests\n * const allKeys = Object.keys(MyEnum);\n * const unusedKeys = allKeys.filter(k => !usedKeys.has(k));\n * console.log('Unused enum keys:', unusedKeys);\n *\n * @example\n * // Performance monitoring\n * const { watched } = watchEnum(Status, (event) => {\n * if (event.accessType === 'get') {\n * performance.mark(`enum-access-${event.enumId}-${event.key}`);\n * }\n * });\n */\nexport function watchEnum<E extends AnyBrandedEnum>(\n enumObj: E,\n callback: EnumWatchCallback\n): WatchEnumResult<E> {\n // Validate that enumObj is a branded enum\n if (!isBrandedEnum(enumObj)) {\n throw new Error('watchEnum requires a branded enum');\n }\n\n const enumId = enumObj[ENUM_ID];\n const registry = getWatcherRegistry();\n\n // Add callback to the registry for this enum\n if (!registry.watchers.has(enumId)) {\n registry.watchers.set(enumId, new Set());\n }\n registry.watchers.get(enumId)!.add(callback);\n\n // Track if this watcher is still active\n let isActive = true;\n\n // Create a Proxy to intercept access\n const proxy = new Proxy(enumObj, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n\n // Only trigger callback for active watchers and string keys (not symbols)\n if (isActive && typeof prop === 'string') {\n const event: EnumAccessEvent = {\n enumId,\n accessType: 'get',\n key: prop,\n value: typeof value === 'string' ? value : undefined,\n timestamp: Date.now(),\n };\n\n // Call the specific callback\n callback(event);\n\n // Also call any global watchers\n for (const globalCallback of registry.globalWatchers) {\n globalCallback(event);\n }\n }\n\n return value;\n },\n\n has(target, prop) {\n const result = Reflect.has(target, prop);\n\n // Only trigger callback for active watchers and string keys\n if (isActive && typeof prop === 'string') {\n const event: EnumAccessEvent = {\n enumId,\n accessType: 'has',\n key: prop,\n timestamp: Date.now(),\n };\n\n callback(event);\n\n for (const globalCallback of registry.globalWatchers) {\n globalCallback(event);\n }\n }\n\n return result;\n },\n\n ownKeys(target) {\n const keys = Reflect.ownKeys(target);\n\n if (isActive) {\n const event: EnumAccessEvent = {\n enumId,\n accessType: 'keys',\n timestamp: Date.now(),\n };\n\n callback(event);\n\n for (const globalCallback of registry.globalWatchers) {\n globalCallback(event);\n }\n }\n\n return keys;\n },\n\n getOwnPropertyDescriptor(target, prop) {\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n });\n\n // Create unwatch function\n const unwatch = () => {\n isActive = false;\n const callbacks = registry.watchers.get(enumId);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n registry.watchers.delete(enumId);\n }\n }\n };\n\n return {\n watched: proxy as E,\n unwatch,\n };\n}\n\n/**\n * Registers a global callback that receives access events from all watched enums.\n *\n * This is useful for centralized logging or monitoring of enum usage across\n * an entire application without needing to wrap each enum individually.\n *\n * @param callback - Function called for every enum access event\n * @returns A function to unregister the global callback\n *\n * @example\n * // Centralized enum access logging\n * const unregister = watchAllEnums((event) => {\n * console.log(`[${event.enumId}] ${event.accessType}: ${event.key}`);\n * });\n *\n * // All watched enums will now trigger this callback\n * watchedStatus.Active; // Logs: \"[status] get: Active\"\n * watchedColors.Red; // Logs: \"[colors] get: Red\"\n *\n * // Stop global watching\n * unregister();\n */\nexport function watchAllEnums(callback: EnumWatchCallback): () => void {\n const registry = getWatcherRegistry();\n registry.globalWatchers.add(callback);\n\n return () => {\n registry.globalWatchers.delete(callback);\n };\n}\n\n/**\n * Clears all enum watchers (both specific and global).\n *\n * This is primarily useful for testing or when you need to reset\n * the watcher state completely.\n *\n * @example\n * // In test cleanup\n * afterEach(() => {\n * clearAllEnumWatchers();\n * });\n */\nexport function clearAllEnumWatchers(): void {\n const registry = getWatcherRegistry();\n registry.watchers.clear();\n registry.globalWatchers.clear();\n}\n\n/**\n * Gets the number of active watchers for a specific enum.\n *\n * @param enumId - The enum ID to check\n * @returns The number of active watchers for this enum\n *\n * @example\n * const { watched } = watchEnum(Status, callback1);\n * watchEnum(Status, callback2);\n *\n * getEnumWatcherCount('status'); // 2\n */\nexport function getEnumWatcherCount(enumId: string): number {\n const registry = getWatcherRegistry();\n return registry.watchers.get(enumId)?.size ?? 0;\n}\n\n/**\n * Gets the number of global watchers.\n *\n * @returns The number of active global watchers\n */\nexport function getGlobalWatcherCount(): number {\n const registry = getWatcherRegistry();\n return registry.globalWatchers.size;\n}\n\n\n/**\n * A helper function for exhaustiveness checking in switch statements.\n *\n * This function should be called in the `default` case of a switch statement\n * when you want to ensure all cases are handled. If the switch is exhaustive,\n * TypeScript will infer that this function is never called (the value is `never`).\n * If a case is missing, TypeScript will show a compile-time error.\n *\n * At runtime, if this function is somehow called (e.g., due to a type assertion\n * or JavaScript interop), it throws a descriptive error.\n *\n * @param value - The value that should be unreachable. TypeScript should infer this as `never`.\n * @param message - Optional custom error message. Defaults to a descriptive message including the value.\n * @returns Never returns - always throws an error if called at runtime.\n * @throws {Error} Throws `Error` with message `Exhaustive check failed: unexpected value \"${value}\"`\n * or the custom message if provided.\n *\n * @example\n * // Basic usage with a branded enum\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * } as const);\n *\n * type StatusValue = typeof Status[keyof typeof Status];\n *\n * function handleStatus(status: StatusValue): string {\n * switch (status) {\n * case Status.Active:\n * return 'User is active';\n * case Status.Inactive:\n * return 'User is inactive';\n * case Status.Pending:\n * return 'User is pending';\n * default:\n * // TypeScript knows this is unreachable if all cases are handled\n * return exhaustive(status);\n * }\n * }\n *\n * @example\n * // Compile-time error when a case is missing\n * function handleStatusIncomplete(status: StatusValue): string {\n * switch (status) {\n * case Status.Active:\n * return 'User is active';\n * case Status.Inactive:\n * return 'User is inactive';\n * // Missing: case Status.Pending\n * default:\n * // TypeScript error: Argument of type '\"pending\"' is not assignable to parameter of type 'never'\n * return exhaustive(status);\n * }\n * }\n *\n * @example\n * // Custom error message\n * function processValue(value: StatusValue): void {\n * switch (value) {\n * case Status.Active:\n * case Status.Inactive:\n * case Status.Pending:\n * console.log('Handled:', value);\n * break;\n * default:\n * exhaustive(value, `Unknown status value encountered: ${value}`);\n * }\n * }\n *\n * @example\n * // Works with any discriminated union, not just branded enums\n * type Shape =\n * | { kind: 'circle'; radius: number }\n * | { kind: 'square'; side: number }\n * | { kind: 'rectangle'; width: number; height: number };\n *\n * function getArea(shape: Shape): number {\n * switch (shape.kind) {\n * case 'circle':\n * return Math.PI * shape.radius ** 2;\n * case 'square':\n * return shape.side ** 2;\n * case 'rectangle':\n * return shape.width * shape.height;\n * default:\n * return exhaustive(shape);\n * }\n * }\n */\nexport function exhaustive(value: never, message?: string): never {\n const errorMessage =\n message ?? `Exhaustive check failed: unexpected value \"${String(value)}\"`;\n throw new Error(errorMessage);\n}\n\n/**\n * Creates an exhaustiveness guard function bound to a specific branded enum.\n *\n * This factory function returns a guard function that can be used in switch\n * statement default cases. The returned function provides better error messages\n * by including the enum ID in the error.\n *\n * This is useful when you want to:\n * - Have consistent error messages that include the enum name\n * - Create reusable guards for specific enums\n * - Provide more context in error messages for debugging\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to create a guard for\n * @returns A function that throws an error with the enum ID included in the message\n * @throws {Error} Throws `Error` with message `exhaustiveGuard requires a branded enum`\n * if enumObj is not a valid branded enum.\n *\n * @example\n * // Create a guard for a specific enum\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * } as const);\n *\n * const assertStatusExhaustive = exhaustiveGuard(Status);\n *\n * type StatusValue = typeof Status[keyof typeof Status];\n *\n * function handleStatus(status: StatusValue): string {\n * switch (status) {\n * case Status.Active:\n * return 'Active';\n * case Status.Inactive:\n * return 'Inactive';\n * case Status.Pending:\n * return 'Pending';\n * default:\n * // Error message will include \"status\" enum ID\n * return assertStatusExhaustive(status);\n * }\n * }\n *\n * @example\n * // Inline usage without storing the guard\n * function processStatus(status: StatusValue): void {\n * switch (status) {\n * case Status.Active:\n * case Status.Inactive:\n * case Status.Pending:\n * console.log('Processing:', status);\n * break;\n * default:\n * exhaustiveGuard(Status)(status);\n * }\n * }\n *\n * @example\n * // Runtime error message example\n * // If somehow called with an unexpected value at runtime:\n * // Error: Exhaustive check failed for enum \"status\": unexpected value \"unknown\"\n *\n * @example\n * // Compile-time error when case is missing\n * function incompleteHandler(status: StatusValue): string {\n * switch (status) {\n * case Status.Active:\n * return 'Active';\n * // Missing: Inactive and Pending cases\n * default:\n * // TypeScript error: Argument of type '\"inactive\" | \"pending\"' is not assignable to parameter of type 'never'\n * return assertStatusExhaustive(status);\n * }\n * }\n */\nexport function exhaustiveGuard<E extends AnyBrandedEnum>(\n enumObj: E\n): (value: never) => never {\n // Validate that enumObj is a branded enum\n if (!isBrandedEnum(enumObj)) {\n throw new Error('exhaustiveGuard requires a branded enum');\n }\n\n const enumId = enumObj[ENUM_ID];\n\n return (value: never): never => {\n throw new Error(\n `Exhaustive check failed for enum \"${enumId}\": unexpected value \"${String(value)}\"`\n );\n };\n}\n\n// =============================================================================\n// JSON Schema Generation\n// =============================================================================\n\n/**\n * Options for customizing JSON Schema generation.\n */\nexport interface ToJsonSchemaOptions {\n /**\n * Custom title for the schema. Defaults to the enum ID.\n */\n readonly title?: string;\n\n /**\n * Description for the schema. If not provided, a default description\n * mentioning the enum ID will be used.\n */\n readonly description?: string;\n\n /**\n * Whether to include the $schema property. Defaults to true.\n */\n readonly includeSchema?: boolean;\n\n /**\n * The JSON Schema draft version to use. Defaults to 'draft-07'.\n */\n readonly schemaVersion?: 'draft-04' | 'draft-06' | 'draft-07' | '2019-09' | '2020-12';\n}\n\n/**\n * JSON Schema representation of a branded enum.\n *\n * This interface represents the structure of the generated JSON Schema,\n * following the JSON Schema specification.\n */\nexport interface EnumJsonSchema {\n /**\n * The JSON Schema version URI (if includeSchema is true).\n */\n readonly $schema?: string;\n\n /**\n * The title of the schema (typically the enum ID).\n */\n readonly title: string;\n\n /**\n * Description of the schema.\n */\n readonly description: string;\n\n /**\n * The type constraint - always 'string' for branded enums.\n */\n readonly type: 'string';\n\n /**\n * The enum constraint containing all valid values.\n */\n readonly enum: readonly string[];\n}\n\n/**\n * Maps schema version options to their corresponding $schema URIs.\n */\nconst SCHEMA_VERSION_URIS: Record<NonNullable<ToJsonSchemaOptions['schemaVersion']>, string> = {\n 'draft-04': 'http://json-schema.org/draft-04/schema#',\n 'draft-06': 'http://json-schema.org/draft-06/schema#',\n 'draft-07': 'http://json-schema.org/draft-07/schema#',\n '2019-09': 'https://json-schema.org/draft/2019-09/schema',\n '2020-12': 'https://json-schema.org/draft/2020-12/schema',\n};\n\n/**\n * Generates a JSON Schema from a branded enum.\n *\n * This function creates a JSON Schema object that validates strings against\n * the values of a branded enum. The generated schema can be used with any\n * JSON Schema validator to ensure that input values are valid enum members.\n *\n * The schema includes:\n * - `$schema`: The JSON Schema version URI (optional, defaults to draft-07)\n * - `title`: The enum ID or a custom title\n * - `description`: A description of the enum\n * - `type`: Always 'string' for branded enums\n * - `enum`: An array of all valid enum values\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to generate a schema for\n * @param options - Optional configuration for schema generation\n * @returns A JSON Schema object that validates against the enum values\n * @throws {Error} Throws `Error` with message `toJsonSchema requires a branded enum`\n * if enumObj is not a valid branded enum.\n *\n * @example\n * // Basic usage - generate schema with defaults\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * } as const);\n *\n * const schema = toJsonSchema(Status);\n * // {\n * // $schema: 'http://json-schema.org/draft-07/schema#',\n * // title: 'status',\n * // description: 'Enum values for status',\n * // type: 'string',\n * // enum: ['active', 'inactive', 'pending']\n * // }\n *\n * @example\n * // Custom title and description\n * const Priority = createBrandedEnum('priority', {\n * High: 'high',\n * Medium: 'medium',\n * Low: 'low',\n * } as const);\n *\n * const schema = toJsonSchema(Priority, {\n * title: 'Task Priority',\n * description: 'The priority level of a task',\n * });\n * // {\n * // $schema: 'http://json-schema.org/draft-07/schema#',\n * // title: 'Task Priority',\n * // description: 'The priority level of a task',\n * // type: 'string',\n * // enum: ['high', 'medium', 'low']\n * // }\n *\n * @example\n * // Without $schema property\n * const schema = toJsonSchema(Status, { includeSchema: false });\n * // {\n * // title: 'status',\n * // description: 'Enum values for status',\n * // type: 'string',\n * // enum: ['active', 'inactive', 'pending']\n * // }\n *\n * @example\n * // Using a different schema version\n * const schema = toJsonSchema(Status, { schemaVersion: '2020-12' });\n * // {\n * // $schema: 'https://json-schema.org/draft/2020-12/schema',\n * // title: 'status',\n * // description: 'Enum values for status',\n * // type: 'string',\n * // enum: ['active', 'inactive', 'pending']\n * // }\n *\n * @example\n * // Use with JSON Schema validators\n * import Ajv from 'ajv';\n *\n * const schema = toJsonSchema(Status);\n * const ajv = new Ajv();\n * const validate = ajv.compile(schema);\n *\n * validate('active'); // true\n * validate('inactive'); // true\n * validate('unknown'); // false\n *\n * @example\n * // Embed in a larger schema\n * const userSchema = {\n * type: 'object',\n * properties: {\n * name: { type: 'string' },\n * status: toJsonSchema(Status, { includeSchema: false }),\n * },\n * required: ['name', 'status'],\n * };\n *\n * @example\n * // Generate schemas for API documentation\n * const schemas = {\n * Status: toJsonSchema(Status),\n * Priority: toJsonSchema(Priority),\n * };\n *\n * // Export for OpenAPI/Swagger\n * const openApiComponents = {\n * schemas: Object.fromEntries(\n * Object.entries(schemas).map(([name, schema]) => [\n * name,\n * { ...schema, $schema: undefined }, // OpenAPI doesn't use $schema\n * ])\n * ),\n * };\n */\nexport function toJsonSchema<E extends AnyBrandedEnum>(\n enumObj: E,\n options: ToJsonSchemaOptions = {}\n): EnumJsonSchema {\n // Validate that enumObj is a branded enum\n if (!isBrandedEnum(enumObj)) {\n throw new Error('toJsonSchema requires a branded enum');\n }\n\n const enumId = enumObj[ENUM_ID];\n const values = enumObj[ENUM_VALUES];\n\n // Extract options with defaults\n const {\n title = enumId,\n description = `Enum values for ${enumId}`,\n includeSchema = true,\n schemaVersion = 'draft-07',\n } = options;\n\n // Build the schema object\n const schema: EnumJsonSchema = {\n title,\n description,\n type: 'string',\n enum: Array.from(values).sort(),\n };\n\n // Add $schema if requested\n if (includeSchema) {\n return {\n $schema: SCHEMA_VERSION_URIS[schemaVersion],\n ...schema,\n };\n }\n\n return schema;\n}\n\n// =============================================================================\n// Zod Schema Generation\n// =============================================================================\n\n/**\n * Options for customizing Zod schema definition generation.\n */\nexport interface ToZodSchemaOptions {\n /**\n * Optional description to include in the schema definition.\n * When provided, the generated schema will include a `description` field\n * that can be used with Zod's `.describe()` method.\n */\n readonly description?: string;\n}\n\n/**\n * Zod-compatible schema definition for a branded enum.\n *\n * This interface represents a schema definition object that can be used\n * to construct a Zod enum schema without depending on Zod at runtime.\n * The definition follows Zod's internal structure for enum schemas.\n *\n * To use with Zod:\n * ```typescript\n * import { z } from 'zod';\n * const def = toZodSchema(MyEnum);\n * const schema = z.enum(def.values);\n * if (def.description) {\n * schema.describe(def.description);\n * }\n * ```\n */\nexport interface ZodEnumSchemaDefinition<T extends readonly [string, ...string[]]> {\n /**\n * The type identifier for this schema definition.\n * Always 'ZodEnum' to indicate this is an enum schema.\n */\n readonly typeName: 'ZodEnum';\n\n /**\n * The enum values as a readonly tuple.\n * This matches Zod's requirement for `z.enum()` which requires\n * at least one value (hence the `[string, ...string[]]` type).\n */\n readonly values: T;\n\n /**\n * Optional description for the schema.\n * Can be used with Zod's `.describe()` method.\n */\n readonly description?: string;\n\n /**\n * The enum ID from the branded enum.\n * Useful for debugging and documentation purposes.\n */\n readonly enumId: string;\n}\n\n/**\n * Generates a Zod-compatible schema definition from a branded enum.\n *\n * This function creates a schema definition object that can be used to\n * construct a Zod enum schema. The library maintains zero dependencies\n * by returning a definition object rather than a Zod instance.\n *\n * The returned definition includes:\n * - `typeName`: Always 'ZodEnum' to identify the schema type\n * - `values`: A tuple of all enum values (sorted for consistency)\n * - `description`: Optional description for the schema\n * - `enumId`: The branded enum's ID for reference\n *\n * **Zero Dependencies**: This function does not import or depend on Zod.\n * It returns a plain object that you can use to construct a Zod schema\n * in your own code where Zod is available.\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to generate a schema definition for\n * @param options - Optional configuration for schema generation\n * @returns A Zod-compatible schema definition object\n * @throws {Error} Throws `Error` with message `toZodSchema requires a branded enum`\n * if enumObj is not a valid branded enum.\n * @throws {Error} Throws `Error` with message `toZodSchema requires an enum with at least one value`\n * if the enum has no values (Zod requires at least one value for z.enum()).\n *\n * @example\n * // Basic usage - generate schema definition\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * } as const);\n *\n * const schemaDef = toZodSchema(Status);\n * // {\n * // typeName: 'ZodEnum',\n * // values: ['active', 'inactive', 'pending'],\n * // enumId: 'status'\n * // }\n *\n * @example\n * // Use with Zod to create an actual schema\n * import { z } from 'zod';\n *\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * } as const);\n *\n * const def = toZodSchema(Status);\n * const statusSchema = z.enum(def.values);\n *\n * // Validate values\n * statusSchema.parse('active'); // 'active'\n * statusSchema.parse('invalid'); // throws ZodError\n *\n * @example\n * // With description\n * const Priority = createBrandedEnum('priority', {\n * High: 'high',\n * Medium: 'medium',\n * Low: 'low',\n * } as const);\n *\n * const def = toZodSchema(Priority, {\n * description: 'Task priority level',\n * });\n * // {\n * // typeName: 'ZodEnum',\n * // values: ['high', 'low', 'medium'],\n * // description: 'Task priority level',\n * // enumId: 'priority'\n * // }\n *\n * // Use with Zod\n * const schema = z.enum(def.values).describe(def.description!);\n *\n * @example\n * // Type-safe schema creation helper\n * import { z } from 'zod';\n *\n * function createZodEnumFromBranded<E extends BrandedEnum<Record<string, string>>>(\n * enumObj: E,\n * description?: string\n * ) {\n * const def = toZodSchema(enumObj, { description });\n * const schema = z.enum(def.values);\n * return description ? schema.describe(description) : schema;\n * }\n *\n * const statusSchema = createZodEnumFromBranded(Status, 'User status');\n *\n * @example\n * // Generate schemas for multiple enums\n * const schemas = {\n * status: toZodSchema(Status),\n * priority: toZodSchema(Priority),\n * category: toZodSchema(Category),\n * };\n *\n * // Later, construct Zod schemas as needed\n * import { z } from 'zod';\n * const zodSchemas = Object.fromEntries(\n * Object.entries(schemas).map(([key, def]) => [key, z.enum(def.values)])\n * );\n *\n * @example\n * // Use in form validation\n * import { z } from 'zod';\n *\n * const statusDef = toZodSchema(Status);\n * const priorityDef = toZodSchema(Priority);\n *\n * const taskSchema = z.object({\n * title: z.string().min(1),\n * status: z.enum(statusDef.values),\n * priority: z.enum(priorityDef.values),\n * });\n *\n * type Task = z.infer<typeof taskSchema>;\n * // { title: string; status: 'active' | 'inactive' | 'pending'; priority: 'high' | 'medium' | 'low' }\n */\nexport function toZodSchema<E extends AnyBrandedEnum>(\n enumObj: E,\n options: ToZodSchemaOptions = {}\n): ZodEnumSchemaDefinition<readonly [string, ...string[]]> {\n // Validate that enumObj is a branded enum\n if (!isBrandedEnum(enumObj)) {\n throw new Error('toZodSchema requires a branded enum');\n }\n\n const enumId = enumObj[ENUM_ID];\n const values = enumObj[ENUM_VALUES];\n\n // Convert Set to sorted array\n const valuesArray = Array.from(values).sort();\n\n // Zod's z.enum() requires at least one value\n if (valuesArray.length === 0) {\n throw new Error('toZodSchema requires an enum with at least one value');\n }\n\n // Build the schema definition\n const definition: ZodEnumSchemaDefinition<readonly [string, ...string[]]> = {\n typeName: 'ZodEnum',\n values: valuesArray as unknown as readonly [string, ...string[]],\n enumId,\n };\n\n // Add description if provided\n if (options.description !== undefined) {\n return {\n ...definition,\n description: options.description,\n };\n }\n\n return definition;\n}\n\n// =============================================================================\n// Enum Serializer\n// =============================================================================\n\n/**\n * Options for customizing enum serialization behavior.\n */\nexport interface EnumSerializerOptions<T extends string = string> {\n /**\n * Custom transform function applied during serialization.\n * Transforms the enum value before it is serialized.\n * \n * @param value - The original enum value\n * @returns The transformed value for serialization\n */\n readonly serialize?: (value: T) => string;\n\n /**\n * Custom transform function applied during deserialization.\n * Transforms the serialized value before validation.\n * This is applied BEFORE validation against the enum.\n * \n * @param value - The serialized value\n * @returns The transformed value to validate against the enum\n */\n readonly deserialize?: (value: string) => string;\n}\n\n/**\n * Result of a successful deserialization.\n * \n * @template T - The type of the deserialized value\n */\nexport interface DeserializeSuccess<T> {\n /** Indicates the deserialization was successful */\n readonly success: true;\n /** The validated and deserialized enum value */\n readonly value: T;\n}\n\n/**\n * Result of a failed deserialization.\n */\nexport interface DeserializeFailure {\n /** Indicates the deserialization failed */\n readonly success: false;\n /** Error information about the failure */\n readonly error: {\n /** Human-readable error message */\n readonly message: string;\n /** The input value that failed deserialization */\n readonly input: unknown;\n /** The enum ID (if available) */\n readonly enumId?: string;\n /** The valid values for the enum (if available) */\n readonly validValues?: readonly string[];\n };\n}\n\n/**\n * Union type representing the result of deserialization.\n * \n * @template T - The type of the successfully deserialized value\n */\nexport type DeserializeResult<T> = DeserializeSuccess<T> | DeserializeFailure;\n\n/**\n * A serializer/deserializer pair for branded enum values.\n * \n * Provides methods to serialize enum values (optionally with transformation)\n * and deserialize values back with validation against the enum.\n * \n * @template E - The branded enum type\n */\nexport interface EnumSerializer<E extends AnyBrandedEnum> {\n /**\n * The branded enum this serializer is bound to.\n */\n readonly enumObj: E;\n\n /**\n * The enum ID for reference.\n */\n readonly enumId: string;\n\n /**\n * Serializes an enum value to a string.\n * \n * If a custom serialize transform was provided, it is applied to the value.\n * \n * @param value - The enum value to serialize\n * @returns The serialized string value\n */\n serialize(value: EnumValues<E>): string;\n\n /**\n * Deserializes a string value back to an enum value.\n * \n * If a custom deserialize transform was provided, it is applied before validation.\n * Returns a result object indicating success or failure with detailed error info.\n * \n * @param value - The string value to deserialize\n * @returns A DeserializeResult indicating success or failure\n */\n deserialize(value: unknown): DeserializeResult<EnumValues<E>>;\n\n /**\n * Deserializes a string value, throwing an error if invalid.\n * \n * This is a convenience method that throws instead of returning a result object.\n * \n * @param value - The string value to deserialize\n * @returns The validated enum value\n * @throws Error if the value is not valid for the enum\n */\n deserializeOrThrow(value: unknown): EnumValues<E>;\n}\n\n/**\n * Creates a serializer/deserializer pair for a branded enum.\n * \n * The serializer provides methods to convert enum values to strings (with optional\n * transformation) and to deserialize strings back to validated enum values.\n * \n * This is useful for:\n * - Storing enum values in databases or localStorage with custom formats\n * - Transmitting enum values over APIs with encoding/decoding\n * - Migrating between different value formats\n * - Adding prefixes/suffixes for namespacing during serialization\n * \n * **Serialization Flow:**\n * 1. Take an enum value\n * 2. Apply custom `serialize` transform (if provided)\n * 3. Return the serialized string\n * \n * **Deserialization Flow:**\n * 1. Take a string input\n * 2. Apply custom `deserialize` transform (if provided)\n * 3. Validate the result against the enum\n * 4. Return success with the value, or failure with error details\n * \n * @template E - The branded enum type\n * @param enumObj - The branded enum to create a serializer for\n * @param options - Optional configuration for custom transforms\n * @returns An EnumSerializer object with serialize and deserialize methods\n * @throws {Error} Throws `Error` with message `enumSerializer requires a branded enum`\n * if enumObj is not a valid branded enum.\n * \n * @example\n * // Basic usage without transforms\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * } as const);\n * \n * const serializer = enumSerializer(Status);\n * \n * // Serialize\n * const serialized = serializer.serialize(Status.Active); // 'active'\n * \n * // Deserialize\n * const result = serializer.deserialize('active');\n * if (result.success) {\n * console.log(result.value); // 'active'\n * }\n * \n * @example\n * // With custom transforms - add prefix during serialization\n * const Priority = createBrandedEnum('priority', {\n * High: 'high',\n * Medium: 'medium',\n * Low: 'low',\n * } as const);\n * \n * const serializer = enumSerializer(Priority, {\n * serialize: (value) => `priority:${value}`,\n * deserialize: (value) => value.replace('priority:', ''),\n * });\n * \n * // Serialize adds prefix\n * serializer.serialize(Priority.High); // 'priority:high'\n * \n * // Deserialize removes prefix and validates\n * const result = serializer.deserialize('priority:high');\n * if (result.success) {\n * console.log(result.value); // 'high'\n * }\n * \n * @example\n * // Base64 encoding for storage\n * const Secret = createBrandedEnum('secret', {\n * Token: 'token',\n * Key: 'key',\n * } as const);\n * \n * const serializer = enumSerializer(Secret, {\n * serialize: (value) => btoa(value),\n * deserialize: (value) => atob(value),\n * });\n * \n * serializer.serialize(Secret.Token); // 'dG9rZW4=' (base64 of 'token')\n * serializer.deserialize('dG9rZW4='); // { success: true, value: 'token' }\n * \n * @example\n * // Error handling\n * const result = serializer.deserialize('invalid');\n * if (!result.success) {\n * console.log(result.error.message);\n * // 'Value \"invalid\" is not a member of enum \"status\"'\n * console.log(result.error.validValues);\n * // ['active', 'inactive']\n * }\n * \n * @example\n * // Using deserializeOrThrow for simpler code when errors should throw\n * try {\n * const value = serializer.deserializeOrThrow('active');\n * console.log(value); // 'active'\n * } catch (e) {\n * console.error('Invalid value:', e.message);\n * }\n * \n * @example\n * // Case-insensitive deserialization\n * const Colors = createBrandedEnum('colors', {\n * Red: 'red',\n * Green: 'green',\n * Blue: 'blue',\n * } as const);\n * \n * const caseInsensitiveSerializer = enumSerializer(Colors, {\n * deserialize: (value) => value.toLowerCase(),\n * });\n * \n * caseInsensitiveSerializer.deserialize('RED'); // { success: true, value: 'red' }\n * caseInsensitiveSerializer.deserialize('Red'); // { success: true, value: 'red' }\n * caseInsensitiveSerializer.deserialize('red'); // { success: true, value: 'red' }\n */\nexport function enumSerializer<E extends AnyBrandedEnum>(\n enumObj: E,\n options: EnumSerializerOptions<EnumValues<E>> = {}\n): EnumSerializer<E> {\n // Validate that enumObj is a branded enum\n if (!isBrandedEnum(enumObj)) {\n throw new Error('enumSerializer requires a branded enum');\n }\n\n const enumId = enumObj[ENUM_ID];\n const values = enumObj[ENUM_VALUES];\n const validValues = Array.from(values).sort();\n\n const { serialize: serializeTransform, deserialize: deserializeTransform } = options;\n\n return {\n enumObj,\n enumId,\n\n serialize(value: EnumValues<E>): string {\n // Apply custom transform if provided\n if (serializeTransform) {\n return serializeTransform(value);\n }\n return value;\n },\n\n deserialize(value: unknown): DeserializeResult<EnumValues<E>> {\n // Check if value is a string\n if (typeof value !== 'string') {\n const valueType = value === null ? 'null' : typeof value;\n return {\n success: false,\n error: {\n message: `Expected a string value, received ${valueType}`,\n input: value,\n enumId,\n validValues,\n },\n };\n }\n\n // Apply custom deserialize transform if provided\n let transformedValue = value;\n if (deserializeTransform) {\n try {\n transformedValue = deserializeTransform(value);\n } catch (e) {\n return {\n success: false,\n error: {\n message: `Deserialize transform failed: ${e instanceof Error ? e.message : String(e)}`,\n input: value,\n enumId,\n validValues,\n },\n };\n }\n }\n\n // Validate against the enum\n if (!values.has(transformedValue)) {\n return {\n success: false,\n error: {\n message: `Value \"${transformedValue}\" is not a member of enum \"${enumId}\"`,\n input: value,\n enumId,\n validValues,\n },\n };\n }\n\n return {\n success: true,\n value: transformedValue as EnumValues<E>,\n };\n },\n\n deserializeOrThrow(value: unknown): EnumValues<E> {\n const result = this.deserialize(value);\n if (!result.success) {\n throw new Error(result.error.message);\n }\n return result.value;\n },\n };\n}\n"],"names":["ENUM_ID","ENUM_VALUES","createBrandedEnum","isBrandedEnum","obj","Set","enumSubset","newId","sourceEnum","keys","Error","length","sourceEnumId","subsetValues","key","enumExclude","keysToExclude","excludeSet","allKeys","Object","resultValues","has","enumMap","mapper","originalValue","transformedValue","enumFromKeys","enumId","seenKeys","values","add","enumDiff","firstEnum","secondEnum","firstKeys","secondKeys","onlyInFirst","onlyInSecond","differentValues","sameValues","firstValue","push","value","secondValue","enumIntersect","enums","enumObj","valueToEnumIds","Map","set","get","result","enumIds","size","Array","from","sort","a","b","localeCompare","enumToRecord","WATCHER_REGISTRY_KEY","getWatcherRegistry","global","globalThis","watchers","globalWatchers","watchEnum","callback","registry","isActive","proxy","Proxy","target","prop","receiver","Reflect","event","accessType","undefined","timestamp","Date","now","globalCallback","ownKeys","getOwnPropertyDescriptor","unwatch","callbacks","delete","watched","watchAllEnums","clearAllEnumWatchers","clear","getEnumWatcherCount","getGlobalWatcherCount","exhaustive","message","errorMessage","String","exhaustiveGuard","SCHEMA_VERSION_URIS","toJsonSchema","options","title","description","includeSchema","schemaVersion","schema","type","enum","$schema","toZodSchema","valuesArray","definition","typeName","enumSerializer","validValues","serialize","serializeTransform","deserialize","deserializeTransform","valueType","success","error","input","e","deserializeOrThrow"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAG;oBACV,OAAO;wBACLH,SAAS;wBACTC,OAAO;4BACL3B,SAAS,CAAC,8BAA8B,EAAE6B,aAAanH,QAAQmH,EAAE7B,OAAO,GAAGE,OAAO2B,GAAG,CAAC;4BACtFD,OAAOlF;4BACPf;4BACAyF;wBACF;oBACF;gBACF;YACF;YAEA,4BAA4B;YAC5B,IAAI,CAACvF,OAAOR,GAAG,CAACI,mBAAmB;gBACjC,OAAO;oBACLiG,SAAS;oBACTC,OAAO;wBACL3B,SAAS,CAAC,OAAO,EAAEvE,iBAAiB,2BAA2B,EAAEE,OAAO,CAAC,CAAC;wBAC1EiG,OAAOlF;wBACPf;wBACAyF;oBACF;gBACF;YACF;YAEA,OAAO;gBACLM,SAAS;gBACThF,OAAOjB;YACT;QACF;QAEAqG,oBAAmBpF,KAAc;YAC/B,MAAMS,SAAS,IAAI,CAACoE,WAAW,CAAC7E;YAChC,IAAI,CAACS,OAAOuE,OAAO,EAAE;gBACnB,MAAM,IAAIhH,MAAMyC,OAAOwE,KAAK,CAAC3B,OAAO;YACtC;YACA,OAAO7C,OAAOT,KAAK;QACrB;IACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"branded-enum.d.ts","sourceRoot":"","sources":["../../src/lib/branded-enum.ts"],"names":[],"mappings":"AAAA,wBAAgB,WAAW,IAAI,MAAM,CAEpC"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/lib/branded-enum.ts"],"sourcesContent":["export function brandedEnum(): string {\n return 'branded-enum';\n}\n"],"names":["brandedEnum"],"rangeMappings":";;","mappings":"AAAA,OAAO,SAASA;IACd,OAAO;AACT"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../../src/lib/decorators.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,cAAc,EACd,WAAW,EAKX,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAsBpB;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkDG;AACH,wBAAgB,SAAS,CAEvB,CAAC,SAAS,WAAW,CAAC,GAAG,CAAC,EAE1B,OAAO,EAAE,CAAC,EACV,OAAO,GAAE,gBAAqB,GAC7B,CAAC,CAAC,SAAS,MAAM,GAAG,IAAI,GAAG,SAAS,EACrC,MAAM,EAAE,4BAA4B,CAAC,OAAO,EAAE,CAAC,CAAC,EAChD,OAAO,EAAE,6BAA6B,CAAC,OAAO,EAAE,CAAC,CAAC,KAC/C,4BAA4B,CAAC,OAAO,EAAE,CAAC,CAAC,CAwG5C;AA8DD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAIzD;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,EAAE,CAI5D;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,IAAI,iBAAiB,EAAE,CAGzD;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,IAAI,IAAI,CAK5C;AAED;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,SAAS,CACvB,GAAG,KAAK,EAAE,cAAc,EAAE,GAEzB,CAAC,CAAC,SAAS,KAAK,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,GAAG,EACvC,MAAM,EAAE,CAAC,EACT,OAAO,EAAE,qBAAqB,CAAC,CAAC,CAAC,KAC9B,CAAC,CA0BL"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/lib/decorators.ts"],"sourcesContent":["/**\n * Decorators for branded enums.\n *\n * Provides runtime validation decorators for class properties\n * that should only accept values from branded enums.\n */\n\nimport {\n AnyBrandedEnum,\n BrandedEnum,\n ENUM_ID,\n ENUM_VALUES,\n CONSUMER_REGISTRY_KEY,\n EnumConsumerRegistry,\n EnumConsumerEntry,\n} from './types.js';\n\n/**\n * Checks if an object is a branded enum (has Symbol metadata).\n *\n * @param obj - The object to check\n * @returns true if obj is a branded enum\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction isBrandedEnum(obj: unknown): obj is BrandedEnum<any> {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n ENUM_ID in obj &&\n ENUM_VALUES in obj &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n typeof (obj as BrandedEnum<any>)[ENUM_ID] === 'string' &&\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (obj as BrandedEnum<any>)[ENUM_VALUES] instanceof Set\n );\n}\n\n/**\n * Options for the EnumValue decorator.\n */\nexport interface EnumValueOptions {\n /**\n * Whether the property is optional (can be undefined).\n * @default false\n */\n optional?: boolean;\n\n /**\n * Whether the property is nullable (can be null).\n * @default false\n */\n nullable?: boolean;\n}\n\n/**\n * Property decorator that validates values against a branded enum at runtime.\n *\n * When a value is assigned to the decorated property, it validates that the value\n * is a member of the specified branded enum. If validation fails, a descriptive\n * error is thrown.\n *\n * Supports optional and nullable properties through the options parameter.\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to validate against\n * @param options - Optional configuration for nullable/optional support\n * @returns A property decorator function\n * @throws {Error} Throws `Error` if enumObj is not a valid branded enum\n * @throws {Error} Throws `Error` at runtime if assigned value is not in the enum\n *\n * @example\n * // Basic usage\n * const Status = createBrandedEnum('status', { Active: 'active', Inactive: 'inactive' } as const);\n *\n * class User {\n * \\@EnumValue(Status)\n * accessor status: string = Status.Active;\n * }\n *\n * const user = new User();\n * user.status = Status.Active; // OK\n * user.status = 'invalid'; // Throws Error\n *\n * @example\n * // Optional property\n * class Config {\n * \\@EnumValue(Status, { optional: true })\n * accessor status: string | undefined;\n * }\n *\n * const config = new Config();\n * config.status = undefined; // OK\n * config.status = Status.Active; // OK\n *\n * @example\n * // Nullable property\n * class Settings {\n * \\@EnumValue(Status, { nullable: true })\n * accessor status: string | null = null;\n * }\n *\n * const settings = new Settings();\n * settings.status = null; // OK\n * settings.status = Status.Active; // OK\n */\nexport function EnumValue<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n E extends BrandedEnum<any>,\n>(\n enumObj: E,\n options: EnumValueOptions = {}\n): <V extends string | null | undefined>(\n target: ClassAccessorDecoratorTarget<unknown, V>,\n context: ClassAccessorDecoratorContext<unknown, V>\n) => ClassAccessorDecoratorResult<unknown, V> {\n // Validate that enumObj is a branded enum at decorator creation time\n if (!isBrandedEnum(enumObj)) {\n throw new Error(\n 'EnumValue decorator requires a branded enum as the first argument'\n );\n }\n\n const enumId = enumObj[ENUM_ID];\n const valueSet = enumObj[ENUM_VALUES];\n const { optional = false, nullable = false } = options;\n\n return function <V extends string | null | undefined>(\n target: ClassAccessorDecoratorTarget<unknown, V>,\n context: ClassAccessorDecoratorContext<unknown, V>\n ): ClassAccessorDecoratorResult<unknown, V> {\n const propertyName = String(context.name);\n\n return {\n get(this: unknown): V {\n return target.get.call(this);\n },\n\n set(this: unknown, value: V): void {\n // Handle undefined values\n if (value === undefined) {\n if (optional) {\n target.set.call(this, value);\n return;\n }\n throw new Error(\n `Property \"${propertyName}\" cannot be undefined. Expected a value from enum \"${enumId}\"`\n );\n }\n\n // Handle null values\n if (value === null) {\n if (nullable) {\n target.set.call(this, value as V);\n return;\n }\n throw new Error(\n `Property \"${propertyName}\" cannot be null. Expected a value from enum \"${enumId}\"`\n );\n }\n\n // Validate that value is a string\n if (typeof value !== 'string') {\n throw new Error(\n `Property \"${propertyName}\" must be a string value from enum \"${enumId}\", got ${typeof value}`\n );\n }\n\n // Validate that value is in the enum\n if (!valueSet.has(value)) {\n const validValues = Array.from(valueSet).join(', ');\n throw new Error(\n `Property \"${propertyName}\" received invalid value \"${value}\". Expected one of: ${validValues} (from enum \"${enumId}\")`\n );\n }\n\n target.set.call(this, value);\n },\n\n init(this: unknown, value: V): V {\n // Handle undefined initial values\n if (value === undefined) {\n if (optional) {\n return value;\n }\n throw new Error(\n `Property \"${propertyName}\" cannot be initialized as undefined. Expected a value from enum \"${enumId}\"`\n );\n }\n\n // Handle null initial values\n if (value === null) {\n if (nullable) {\n return value;\n }\n throw new Error(\n `Property \"${propertyName}\" cannot be initialized as null. Expected a value from enum \"${enumId}\"`\n );\n }\n\n // Validate that value is a string\n if (typeof value !== 'string') {\n throw new Error(\n `Property \"${propertyName}\" must be initialized with a string value from enum \"${enumId}\", got ${typeof value}`\n );\n }\n\n // Validate that value is in the enum\n if (!valueSet.has(value)) {\n const validValues = Array.from(valueSet).join(', ');\n throw new Error(\n `Property \"${propertyName}\" initialized with invalid value \"${value}\". Expected one of: ${validValues} (from enum \"${enumId}\")`\n );\n }\n\n return value;\n },\n };\n };\n}\n\n/**\n * Gets the consumer registry, initializing it lazily on globalThis.\n *\n * @returns The global enum consumer registry\n */\nfunction getConsumerRegistry(): EnumConsumerRegistry {\n const global = globalThis as typeof globalThis & {\n [CONSUMER_REGISTRY_KEY]?: EnumConsumerRegistry;\n };\n\n if (!(CONSUMER_REGISTRY_KEY in global)) {\n global[CONSUMER_REGISTRY_KEY] = {\n consumers: new Map(),\n enumToConsumers: new Map(),\n };\n }\n\n return global[CONSUMER_REGISTRY_KEY]!;\n}\n\n/**\n * Registers a class as a consumer of the specified branded enums.\n *\n * @param classRef - The class constructor\n * @param className - The name of the class\n * @param enumIds - Array of enum IDs that the class consumes\n */\nfunction registerEnumConsumer(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n classRef: new (...args: any[]) => any,\n className: string,\n enumIds: string[]\n): void {\n const registry = getConsumerRegistry();\n\n // Get or create the consumer entry\n let entry = registry.consumers.get(className);\n if (!entry) {\n entry = {\n classRef,\n className,\n enumIds: new Set(),\n };\n registry.consumers.set(className, entry);\n }\n\n // Add enum IDs to the consumer entry and update reverse index\n for (const enumId of enumIds) {\n entry.enumIds.add(enumId);\n\n // Update reverse index\n let consumers = registry.enumToConsumers.get(enumId);\n if (!consumers) {\n consumers = new Set();\n registry.enumToConsumers.set(enumId, consumers);\n }\n consumers.add(className);\n }\n}\n\n/**\n * Gets all class names that consume a specific branded enum.\n *\n * @param enumId - The enum ID to look up\n * @returns Array of class names that consume the enum\n *\n * @example\n * const Status = createBrandedEnum('status', { Active: 'active' } as const);\n *\n * \\@EnumClass(Status)\n * class User { }\n *\n * getEnumConsumers('status'); // ['User']\n */\nexport function getEnumConsumers(enumId: string): string[] {\n const registry = getConsumerRegistry();\n const consumers = registry.enumToConsumers.get(enumId);\n return consumers ? Array.from(consumers) : [];\n}\n\n/**\n * Gets all enum IDs consumed by a specific class.\n *\n * @param className - The class name to look up\n * @returns Array of enum IDs consumed by the class\n *\n * @example\n * const Status = createBrandedEnum('status', { Active: 'active' } as const);\n * const Priority = createBrandedEnum('priority', { High: 'high' } as const);\n *\n * \\@EnumClass(Status, Priority)\n * class Task { }\n *\n * getConsumedEnums('Task'); // ['status', 'priority']\n */\nexport function getConsumedEnums(className: string): string[] {\n const registry = getConsumerRegistry();\n const entry = registry.consumers.get(className);\n return entry ? Array.from(entry.enumIds) : [];\n}\n\n/**\n * Gets all registered enum consumer entries.\n *\n * @returns Array of all consumer entries\n *\n * @example\n * getAllEnumConsumers(); // [{ className: 'User', enumIds: Set(['status']) }, ...]\n */\nexport function getAllEnumConsumers(): EnumConsumerEntry[] {\n const registry = getConsumerRegistry();\n return Array.from(registry.consumers.values());\n}\n\n/**\n * Clears the consumer registry. Useful for testing.\n * @internal\n */\nexport function clearConsumerRegistry(): void {\n const global = globalThis as typeof globalThis & {\n [CONSUMER_REGISTRY_KEY]?: EnumConsumerRegistry;\n };\n delete global[CONSUMER_REGISTRY_KEY];\n}\n\n/**\n * Class decorator that registers a class as a consumer of branded enums.\n *\n * This decorator tracks which classes use which branded enums, enabling\n * debugging and introspection of enum usage across the codebase.\n *\n * @param enums - One or more branded enums that the class consumes\n * @returns A class decorator function\n * @throws {Error} Throws `Error` if any argument is not a valid branded enum\n *\n * @example\n * const Status = createBrandedEnum('status', { Active: 'active', Inactive: 'inactive' } as const);\n * const Priority = createBrandedEnum('priority', { High: 'high', Low: 'low' } as const);\n *\n * \\@EnumClass(Status, Priority)\n * class Task {\n * status = Status.Active;\n * priority = Priority.High;\n * }\n *\n * // Query which classes consume an enum\n * getEnumConsumers('status'); // ['Task']\n *\n * // Query which enums a class consumes\n * getConsumedEnums('Task'); // ['status', 'priority']\n */\nexport function EnumClass(\n ...enums: AnyBrandedEnum[]\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): <T extends new (...args: any[]) => any>(\n target: T,\n context: ClassDecoratorContext<T>\n) => T {\n // Validate all enums at decorator creation time\n const enumIds: string[] = [];\n for (let i = 0; i < enums.length; i++) {\n const enumObj = enums[i];\n if (!isBrandedEnum(enumObj)) {\n throw new Error(\n `EnumClass decorator argument at index ${i} is not a valid branded enum`\n );\n }\n enumIds.push(enumObj[ENUM_ID]);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function <T extends new (...args: any[]) => any>(\n target: T,\n context: ClassDecoratorContext<T>\n ): T {\n const className = String(context.name);\n\n // Register the class as a consumer of the enums\n registerEnumConsumer(target, className, enumIds);\n\n // Return the class unchanged\n return target;\n };\n}\n"],"names":["ENUM_ID","ENUM_VALUES","CONSUMER_REGISTRY_KEY","isBrandedEnum","obj","Set","EnumValue","enumObj","options","Error","enumId","valueSet","optional","nullable","target","context","propertyName","String","name","get","call","set","value","undefined","has","validValues","Array","from","join","init","getConsumerRegistry","global","globalThis","consumers","Map","enumToConsumers","registerEnumConsumer","classRef","className","enumIds","registry","entry","add","getEnumConsumers","getConsumedEnums","getAllEnumConsumers","values","clearConsumerRegistry","EnumClass","enums","i","length","push"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ources":["../../src/lib/factory.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,WAAW,EAIZ,MAAM,YAAY,CAAC;AAGpB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAChE,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,CAAC,GACR,WAAW,CAAC,CAAC,CAAC,CA6BhB"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/lib/factory.ts"],"sourcesContent":["/**\n * Factory function for creating branded enums.\n *\n * Creates enum-like objects with runtime metadata for identification,\n * while keeping values as raw strings for serialization compatibility.\n */\n\nimport {\n BrandedEnum,\n BrandedEnumMetadata,\n ENUM_ID,\n ENUM_VALUES,\n} from './types.js';\nimport { registerEnum } from './registry.js';\n\n/**\n * Creates a branded enum with runtime metadata.\n *\n * The returned object:\n * - Contains all provided key-value pairs as enumerable properties\n * - Has non-enumerable Symbol properties for metadata (ENUM_ID, ENUM_VALUES)\n * - Is frozen to prevent modification\n * - Is registered in the global registry\n *\n * @template T - The shape of the values object (use `as const` for literal types)\n * @param enumId - Unique identifier for this enum. Must be unique across all\n * branded enums in the application.\n * @param values - Object containing key-value pairs where keys are enum member\n * names and values are the string values. Use `as const` for literal type inference.\n * @returns A frozen branded enum object with attached metadata\n * @throws {Error} Throws `Error` with message `Branded enum with ID \"${enumId}\" already exists`\n * if an enum with the same ID has already been registered.\n *\n * @example\n * // Basic usage\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * } as const);\n *\n * Status.Active // 'active' (raw string)\n * getEnumId(Status) // 'status'\n *\n * @example\n * // Type inference with as const\n * const Colors = createBrandedEnum('colors', {\n * Red: 'red',\n * Green: 'green',\n * Blue: 'blue',\n * } as const);\n *\n * type ColorValue = typeof Colors[keyof typeof Colors]; // 'red' | 'green' | 'blue'\n *\n * @example\n * // Error handling for duplicate IDs\n * createBrandedEnum('myEnum', { A: 'a' } as const);\n * createBrandedEnum('myEnum', { B: 'b' } as const); // Throws Error\n */\nexport function createBrandedEnum<T extends Record<string, string>>(\n enumId: string,\n values: T\n): BrandedEnum<T> {\n // Create the enum object with user values\n const enumObj = { ...values } as T & BrandedEnumMetadata;\n\n // Collect all values into a Set for O(1) membership checks\n const valueSet = new Set<string>(Object.values(values));\n\n // Attach non-enumerable Symbol properties for metadata\n Object.defineProperty(enumObj, ENUM_ID, {\n value: enumId,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n Object.defineProperty(enumObj, ENUM_VALUES, {\n value: valueSet,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n // Freeze the object to prevent modification\n const frozenEnum = Object.freeze(enumObj) as BrandedEnum<T>;\n\n // Register in global registry (throws if duplicate ID)\n registerEnum(frozenEnum);\n\n return frozenEnum;\n}\n"],"names":["ENUM_ID","ENUM_VALUES","registerEnum","createBrandedEnum","enumId","values","enumObj","valueSet","Set","Object","defineProperty","value","enumerable","writable","configurable","frozenEnum","freeze"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA;;;;;CAKC,GAED,SAGEA,OAAO,EACPC,WAAW,QACN,aAAa;AACpB,SAASC,YAAY,QAAQ,gBAAgB;AAE7C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0CC,GACD,OAAO,SAASC,kBACdC,MAAc,EACdC,MAAS;IAET,0CAA0C;IAC1C,MAAMC,UAAU;QAAE,GAAGD,MAAM;IAAC;IAE5B,2DAA2D;IAC3D,MAAME,WAAW,IAAIC,IAAYC,OAAOJ,MAAM,CAACA;IAE/C,uDAAuD;IACvDI,OAAOC,cAAc,CAACJ,SAASN,SAAS;QACtCW,OAAOP;QACPQ,YAAY;QACZC,UAAU;QACVC,cAAc;IAChB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;IACjC,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IACxB,iCAAiC;IACjC,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;CAChC;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,mCAAmC;IACnC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,6CAA6C;IAC7C,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,6CAA6C;IAC7C,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,iCAAiC;IACjC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,mDAAmD;IACnD,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC1C;AAED;;GAEG;AACH,MAAM,MAAM,kBAAkB,GAC1B,qBAAqB,GACrB,oBAAoB,GACpB,mBAAmB,CAAC;AAExB;;;;GAIG;AACH,MAAM,MAAM,eAAe,CAAC,CAAC,IAAI,gBAAgB,CAAC,CAAC,CAAC,GAAG,gBAAgB,CAAC;AAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiGG;AACH,wBAAgB,aAAa,CAAC,CAAC,SAAS,cAAc,EACpD,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,CAAC,GACT,eAAe,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAkDhC"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/lib/guards.ts"],"sourcesContent":["/**\n * Type guards for branded enums.\n *\n * Provides runtime type checking and assertion functions\n * for validating values against branded enums.\n */\n\nimport {\n AnyBrandedEnum,\n BrandedEnum,\n BrandedEnumValue,\n ENUM_ID,\n ENUM_VALUES,\n EnumValues,\n} from './types.js';\n\n/**\n * Checks if an object is a branded enum (has Symbol metadata).\n *\n * @param obj - The object to check\n * @returns true if obj is a branded enum\n */\nfunction isBrandedEnum(obj: unknown): obj is AnyBrandedEnum {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n ENUM_ID in obj &&\n ENUM_VALUES in obj &&\n typeof (obj as AnyBrandedEnum)[ENUM_ID] === 'string' &&\n (obj as AnyBrandedEnum)[ENUM_VALUES] instanceof Set\n );\n}\n\n/**\n * Checks if a value belongs to a specific branded enum.\n *\n * Returns true if and only if:\n * - enumObj is a valid branded enum (has Symbol metadata)\n * - value is a string\n * - value exists in the enum's value Set\n *\n * This function provides TypeScript type narrowing - when it returns true,\n * the value's type is narrowed to the enum's value type.\n *\n * @template E - The branded enum type\n * @param value - The value to check. Can be any type; non-strings return false.\n * @param enumObj - The branded enum to check against\n * @returns `true` if value is in the enum (with type narrowing), `false` otherwise.\n * Returns `false` for non-string values, null, undefined, or if enumObj\n * is not a branded enum.\n *\n * @example\n * // Basic type guard usage\n * const Status = createBrandedEnum('status', { Active: 'active', Inactive: 'inactive' } as const);\n *\n * function handleStatus(value: unknown) {\n * if (isFromEnum(value, Status)) {\n * // value is narrowed to 'active' | 'inactive'\n * console.log('Valid status:', value);\n * } else {\n * console.log('Invalid status');\n * }\n * }\n *\n * @example\n * // Returns false for non-string values\n * isFromEnum(123, Status); // false\n * isFromEnum(null, Status); // false\n * isFromEnum(undefined, Status); // false\n *\n * @example\n * // Returns false for non-branded enum objects\n * isFromEnum('active', { Active: 'active' }); // false (not a branded enum)\n */\nexport function isFromEnum<E extends AnyBrandedEnum>(\n value: unknown,\n enumObj: E\n): value is EnumValues<E> {\n // Return false for non-string values\n if (typeof value !== 'string') {\n return false;\n }\n\n // Return false if enumObj is not a branded enum\n if (!isBrandedEnum(enumObj)) {\n return false;\n }\n\n // Check if value exists in enum's value Set\n return enumObj[ENUM_VALUES].has(value);\n}\n\n/**\n * Asserts that a value belongs to a branded enum, throwing if not.\n *\n * Use this function when you want to validate a value and throw an error\n * if it's invalid, rather than handling the false case manually.\n *\n * @template E - The branded enum type\n * @param value - The value to check. Can be any type.\n * @param enumObj - The branded enum to check against\n * @returns The value with narrowed type if valid\n * @throws {Error} Throws `Error` with message `Second argument is not a branded enum`\n * if enumObj is not a valid branded enum.\n * @throws {Error} Throws `Error` with message `Value \"${value}\" is not a member of enum \"${enumId}\"`\n * if the value is not found in the enum.\n *\n * @example\n * // Successful assertion\n * const Status = createBrandedEnum('status', { Active: 'active', Inactive: 'inactive' } as const);\n * const validated = assertFromEnum('active', Status);\n * // validated is typed as 'active' | 'inactive'\n *\n * @example\n * // Throws for invalid value\n * try {\n * assertFromEnum('unknown', Status);\n * } catch (e) {\n * console.log(e.message); // 'Value \"unknown\" is not a member of enum \"status\"'\n * }\n *\n * @example\n * // Throws for non-branded enum\n * try {\n * assertFromEnum('active', { Active: 'active' });\n * } catch (e) {\n * console.log(e.message); // 'Second argument is not a branded enum'\n * }\n */\nexport function assertFromEnum<E extends AnyBrandedEnum>(\n value: unknown,\n enumObj: E\n): EnumValues<E> {\n // Check if enumObj is a branded enum\n if (!isBrandedEnum(enumObj)) {\n throw new Error('Second argument is not a branded enum');\n }\n\n // Check if value is in the enum\n if (!isFromEnum(value, enumObj)) {\n const enumId = enumObj[ENUM_ID];\n throw new Error(`Value \"${value}\" is not a member of enum \"${enumId}\"`);\n }\n\n return value as EnumValues<E>;\n}\n\n/**\n * Safely parses a value against a branded enum, returning a default if invalid.\n *\n * This is a non-throwing alternative to `assertFromEnum`. Instead of throwing\n * an error when the value is not in the enum, it returns the provided default value.\n *\n * Use this function when you want to handle invalid values gracefully without\n * try/catch blocks, such as when parsing user input or external data.\n *\n * @template E - The branded enum type\n * @param value - The value to parse. Can be any type; non-strings will return the default.\n * @param enumObj - The branded enum to validate against\n * @param defaultValue - The value to return if parsing fails. Must be a valid enum value.\n * @returns The original value if it exists in the enum, otherwise the default value.\n * The return type is narrowed to the enum's value type.\n *\n * @example\n * // Basic usage with default fallback\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * } as const);\n *\n * // Valid value returns as-is\n * parseEnum('active', Status, Status.Pending); // 'active'\n *\n * // Invalid value returns default\n * parseEnum('unknown', Status, Status.Pending); // 'pending'\n *\n * // Non-string value returns default\n * parseEnum(null, Status, Status.Inactive); // 'inactive'\n * parseEnum(123, Status, Status.Inactive); // 'inactive'\n *\n * @example\n * // Parsing user input safely\n * function handleUserStatus(input: unknown): void {\n * const status = parseEnum(input, Status, Status.Pending);\n * // status is guaranteed to be 'active' | 'inactive' | 'pending'\n * console.log('Processing status:', status);\n * }\n *\n * @example\n * // Parsing API response with fallback\n * interface ApiResponse {\n * status?: string;\n * }\n *\n * function processResponse(response: ApiResponse) {\n * const status = parseEnum(response.status, Status, Status.Inactive);\n * // Handles undefined, null, or invalid status values gracefully\n * return { status };\n * }\n *\n * @example\n * // Chaining with optional values\n * const userStatus = parseEnum(\n * localStorage.getItem('userStatus'),\n * Status,\n * Status.Active\n * );\n */\nexport function parseEnum<E extends AnyBrandedEnum>(\n value: unknown,\n enumObj: E,\n defaultValue: EnumValues<E>\n): EnumValues<E> {\n // If the value is valid, return it\n if (isFromEnum(value, enumObj)) {\n return value;\n }\n\n // Otherwise return the default\n return defaultValue;\n}\n\n// =============================================================================\n// Safe Parse Result Types\n// =============================================================================\n\n/**\n * Represents a successful parse result from safeParseEnum.\n *\n * @template T - The type of the successfully parsed value\n */\nexport interface SafeParseSuccess<T> {\n /** Indicates the parse was successful */\n readonly success: true;\n /** The validated enum value */\n readonly value: T;\n}\n\n/**\n * Represents a failed parse result from safeParseEnum.\n *\n * Contains detailed error information for debugging and user feedback.\n */\nexport interface SafeParseFailure {\n /** Indicates the parse failed */\n readonly success: false;\n /** Detailed error information */\n readonly error: SafeParseError;\n}\n\n/**\n * Detailed error information for a failed parse.\n */\nexport interface SafeParseError {\n /** Human-readable error message */\n readonly message: string;\n /** The code identifying the type of error */\n readonly code: SafeParseErrorCode;\n /** The input value that failed validation */\n readonly input: unknown;\n /** The enum ID (if available) */\n readonly enumId?: string;\n /** The valid values for the enum (if available) */\n readonly validValues?: readonly string[];\n}\n\n/**\n * Error codes for safe parse failures.\n */\nexport type SafeParseErrorCode =\n | 'INVALID_ENUM_OBJECT'\n | 'INVALID_VALUE_TYPE'\n | 'VALUE_NOT_IN_ENUM';\n\n/**\n * Union type representing the result of safeParseEnum.\n *\n * @template T - The type of the successfully parsed value\n */\nexport type SafeParseResult<T> = SafeParseSuccess<T> | SafeParseFailure;\n\n/**\n * Safely parses a value against a branded enum, returning a result object.\n *\n * This function provides validated deserialization with detailed error information.\n * Unlike `parseEnum` which returns a default value on failure, or `assertFromEnum`\n * which throws an error, `safeParseEnum` returns a discriminated union result\n * that allows for explicit success/failure handling.\n *\n * The result is either:\n * - `{ success: true, value: T }` - The value is valid and typed correctly\n * - `{ success: false, error: SafeParseError }` - The value is invalid with details\n *\n * Error codes:\n * - `INVALID_ENUM_OBJECT` - The enumObj is not a valid branded enum\n * - `INVALID_VALUE_TYPE` - The value is not a string\n * - `VALUE_NOT_IN_ENUM` - The value is a string but not in the enum\n *\n * @template E - The branded enum type\n * @param value - The value to parse. Can be any type.\n * @param enumObj - The branded enum to validate against\n * @returns A SafeParseResult containing either the validated value or error details\n *\n * @example\n * // Basic usage with success\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * } as const);\n *\n * const result = safeParseEnum('active', Status);\n * if (result.success) {\n * console.log('Valid status:', result.value); // 'active'\n * } else {\n * console.log('Error:', result.error.message);\n * }\n *\n * @example\n * // Handling invalid value\n * const result = safeParseEnum('unknown', Status);\n * if (!result.success) {\n * console.log(result.error.code); // 'VALUE_NOT_IN_ENUM'\n * console.log(result.error.message); // 'Value \"unknown\" is not a member of enum \"status\"'\n * console.log(result.error.validValues); // ['active', 'inactive']\n * }\n *\n * @example\n * // Handling non-string input\n * const result = safeParseEnum(123, Status);\n * if (!result.success) {\n * console.log(result.error.code); // 'INVALID_VALUE_TYPE'\n * console.log(result.error.message); // 'Expected a string value, received number'\n * }\n *\n * @example\n * // Parsing API response\n * interface ApiResponse {\n * status?: string;\n * }\n *\n * function processResponse(response: ApiResponse) {\n * const result = safeParseEnum(response.status, Status);\n * if (result.success) {\n * return { status: result.value };\n * } else {\n * // Log detailed error for debugging\n * console.error('Invalid status:', result.error);\n * return { status: Status.Inactive }; // fallback\n * }\n * }\n *\n * @example\n * // Form validation with detailed errors\n * function validateForm(data: Record<string, unknown>) {\n * const statusResult = safeParseEnum(data.status, Status);\n * const errors: string[] = [];\n *\n * if (!statusResult.success) {\n * errors.push(`Status: ${statusResult.error.message}`);\n * }\n *\n * return {\n * isValid: errors.length === 0,\n * errors,\n * data: statusResult.success ? { status: statusResult.value } : null,\n * };\n * }\n *\n * @example\n * // Type narrowing with result\n * const result = safeParseEnum(userInput, Status);\n * if (result.success) {\n * // result.value is typed as 'active' | 'inactive'\n * handleStatus(result.value);\n * } else {\n * // result.error is typed as SafeParseError\n * showError(result.error.message);\n * }\n */\nexport function safeParseEnum<E extends AnyBrandedEnum>(\n value: unknown,\n enumObj: E\n): SafeParseResult<EnumValues<E>> {\n // Check if enumObj is a branded enum\n if (!isBrandedEnum(enumObj)) {\n return {\n success: false,\n error: {\n message: 'Second argument is not a branded enum',\n code: 'INVALID_ENUM_OBJECT',\n input: value,\n },\n };\n }\n\n const enumId = enumObj[ENUM_ID];\n const validValues = Array.from(enumObj[ENUM_VALUES]).sort();\n\n // Check if value is a string\n if (typeof value !== 'string') {\n const valueType = value === null ? 'null' : typeof value;\n return {\n success: false,\n error: {\n message: `Expected a string value, received ${valueType}`,\n code: 'INVALID_VALUE_TYPE',\n input: value,\n enumId,\n validValues,\n },\n };\n }\n\n // Check if value is in the enum\n if (!enumObj[ENUM_VALUES].has(value)) {\n return {\n success: false,\n error: {\n message: `Value \"${value}\" is not a member of enum \"${enumId}\"`,\n code: 'VALUE_NOT_IN_ENUM',\n input: value,\n enumId,\n validValues,\n },\n };\n }\n\n // Success case\n return {\n success: true,\n value: value as EnumValues<E>,\n };\n}\n"],"names":["ENUM_ID","ENUM_VALUES","isBrandedEnum","obj","Set","isFromEnum","value","enumObj","has","assertFromEnum","Error","enumId","parseEnum","defaultValue","safeParseEnum","success","error","message","code","input","validValues","Array","from","sort","valueType"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA;;;;;CAKC,GAED,SAIEA,OAAO,EACPC,WAAW,QAEN,aAAa;AAEpB;;;;;CAKC,GACD,SAASC,cAAcC,GAAY;IACjC,OACEA,QAAQ,QACR,OAAOA,QAAQ,YACfH,WAAWG,OACXF,eAAeE,OACf,OAAO,AAACA,GAAsB,CAACH,QAAQ,KAAK,YAC5C,AAACG,GAAsB,CAACF,YAAY,YAAYG;AAEpD;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwCC,GACD,OAAO,SAASC,WACdC,KAAc,EACdC,OAAU;IAEV,qCAAqC;IACrC,IAAI,OAAOD,UAAU,UAAU;QAC7B,OAAO;IACT;IAEA,gDAAgD;IAChD,IAAI,CAACJ,cAAcK,UAAU;QAC3B,OAAO;IACT;IAEA,4CAA4C;IAC5C,OAAOA,OAAO,CAACN,YAAY,CAACO,GAAG,CAACF;AAClC;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAoCC,GACD,OAAO,SAASG,eACdH,KAAc,EACdC,OAAU;IAEV,qCAAqC;IACrC,IAAI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QAAQ;QACpC,OAAO;YACLS,SAAS;YACTC,OAAO;gBACLC,SAAS,CAAC,OAAO,EAAEX,MAAM,2BAA2B,EAAEK,OAAO,CAAC,CAAC;gBAC/DO,MAAM;gBACNC,OAAOb;gBACPK;gBACAS;YACF;QACF;IACF;IAEA,eAAe;IACf,OAAO;QACLL,SAAS;QACTT,OAAOA;IACT;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"merge.d.ts","sourceRoot":"","sources":["../../src/lib/merge.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,cAAc,EAAE,WAAW,EAAwB,MAAM,YAAY,CAAC;AA2B/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,SAAS,cAAc,EAAE,EAC5D,KAAK,EAAE,MAAM,EACb,GAAG,KAAK,EAAE,CAAC,GACV,WAAW,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CA6BrC"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/lib/merge.ts"],"sourcesContent":["/**\n * Enum composition functions for branded enums.\n *\n * Enables merging multiple branded enums into a new combined enum\n * while maintaining type safety and registry tracking.\n */\n\nimport { AnyBrandedEnum, BrandedEnum, ENUM_ID, ENUM_VALUES } from './types.js';\nimport { createBrandedEnum } from './factory.js';\n\n/**\n * Type helper to extract the values type from a branded enum.\n */\ntype ExtractValues<E> = E extends BrandedEnum<infer T> ? T : never;\n\n/**\n * Type helper to merge multiple branded enum value types into one.\n */\ntype MergedValues<T extends AnyBrandedEnum[]> = {\n [K in keyof T]: ExtractValues<T[K]>;\n}[number];\n\n/**\n * Checks if an object is a branded enum.\n */\nfunction isBrandedEnum(obj: unknown): obj is AnyBrandedEnum {\n return (\n typeof obj === 'object' &&\n obj !== null &&\n ENUM_ID in obj &&\n ENUM_VALUES in obj\n );\n}\n\n/**\n * Merges multiple branded enums into a new branded enum.\n *\n * Creates a new branded enum that contains all key-value pairs from all\n * source enums. The merged enum is registered in the global registry\n * as a new independent enum.\n *\n * Key collision handling:\n * - Duplicate keys (same key in multiple enums) throw an error\n * - Duplicate values (same value in multiple enums) are allowed\n *\n * @template T - Tuple of branded enum types being merged\n * @param newId - Unique identifier for the merged enum. Must not already\n * be registered.\n * @param enums - One or more branded enums to merge\n * @returns A new branded enum containing all values from source enums\n * @throws {Error} Throws `Error` with message\n * `Cannot merge enums: duplicate key \"${key}\" found in enums \"${enumId1}\" and \"${enumId2}\"`\n * if the same key exists in multiple source enums.\n * @throws {Error} Throws `Error` with message\n * `Branded enum with ID \"${newId}\" already exists` if newId is already registered.\n * @throws {Error} Throws `Error` with message `All arguments must be branded enums`\n * if any argument is not a valid branded enum.\n *\n * @example\n * // Basic merge\n * const Colors = createBrandedEnum('colors', { Red: 'red', Blue: 'blue' } as const);\n * const Sizes = createBrandedEnum('sizes', { Small: 'small', Large: 'large' } as const);\n *\n * const Combined = mergeEnums('combined', Colors, Sizes);\n * // Combined has: Red, Blue, Small, Large\n *\n * Combined.Red; // 'red'\n * Combined.Small; // 'small'\n *\n * @example\n * // Duplicate values are allowed\n * const Status1 = createBrandedEnum('status1', { Active: 'active' } as const);\n * const Status2 = createBrandedEnum('status2', { Enabled: 'active' } as const);\n *\n * const Merged = mergeEnums('merged', Status1, Status2);\n * // Both Active and Enabled have value 'active' - this is allowed\n *\n * @example\n * // Duplicate keys throw an error\n * const Enum1 = createBrandedEnum('enum1', { Key: 'value1' } as const);\n * const Enum2 = createBrandedEnum('enum2', { Key: 'value2' } as const);\n *\n * try {\n * mergeEnums('merged', Enum1, Enum2);\n * } catch (e) {\n * console.log(e.message);\n * // 'Cannot merge enums: duplicate key \"Key\" found in enums \"enum1\" and \"enum2\"'\n * }\n */\nexport function mergeEnums<T extends readonly AnyBrandedEnum[]>(\n newId: string,\n ...enums: T\n): BrandedEnum<Record<string, string>> {\n // Collect all key-value pairs, checking for duplicate keys\n const mergedValues: Record<string, string> = {};\n const seenKeys = new Map<string, string>(); // key -> source enumId\n\n for (const enumObj of enums) {\n if (!isBrandedEnum(enumObj)) {\n throw new Error('All arguments must be branded enums');\n }\n\n const sourceEnumId = enumObj[ENUM_ID];\n\n // Iterate over enumerable properties (user-defined keys only)\n for (const [key, value] of Object.entries(enumObj)) {\n // Check for duplicate keys\n if (seenKeys.has(key)) {\n const originalEnumId = seenKeys.get(key);\n throw new Error(\n `Cannot merge enums: duplicate key \"${key}\" found in enums \"${originalEnumId}\" and \"${sourceEnumId}\"`\n );\n }\n\n seenKeys.set(key, sourceEnumId);\n mergedValues[key] = value as string;\n }\n }\n\n // Create and return the new branded enum (this handles registration)\n return createBrandedEnum(newId, mergedValues) as BrandedEnum<MergedValues<[...T]>>;\n}\n"],"names":["ENUM_ID","ENUM_VALUES","createBrandedEnum","isBrandedEnum","obj","mergeEnums","newId","enums","mergedValues","seenKeys","Map","enumObj","Error","sourceEnumId","key","value","Object","entries","has","originalEnumId","get","set"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA;;;;;CAKC,GAED,SAAsCA,OAAO,EAAEC,WAAW,QAAQ,aAAa;AAC/E,SAASC,iBAAiB,QAAQ,eAAe;AAcjD;;CAEC,GACD,SAASC,cAAcC,GAAY;IACjC,OACE,OAAOA,QAAQ,YACfA,QAAQ,QACRJ,WAAWI,OACXH,eAAeG;AAEnB;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsDC,GACD,OAAO,SAASC,WACdC,KAAa,EACb,GAAGC,KAAQ;IAEX,2DAA2D;IAC3D,MAAMC,eAAuC,CAAC;IAC9C,MAAMC,WAAW,IAAIC,OAAuB,uBAAuB;IAEnE,KAAK,MAAMC,WAAWJ,MAAO;QAC3B,IAAI,CAACJ,c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@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/lib/registry.ts"],"sourcesContent":["/**\n * Global registry for branded enums.\n *\n * Uses globalThis to ensure cross-bundle compatibility - all instances\n * of the library share the same registry regardless of how they're bundled.\n */\n\nimport {\n BrandedEnum,\n BrandedEnumRegistry,\n RegistryEntry,\n REGISTRY_KEY,\n ENUM_ID,\n ENUM_VALUES,\n} from './types.js';\n\n/**\n * Gets the global registry, initializing it lazily if needed.\n * Uses globalThis for cross-bundle compatibility.\n *\n * The registry is shared across all instances of the library, even when\n * bundled separately or loaded as different module formats (ESM/CJS).\n *\n * @returns The global branded enum registry containing all registered enums\n * and a value index for reverse lookups.\n *\n * @example\n * const registry = getRegistry();\n * console.log(registry.enums.size); // Number of registered enums\n */\nexport function getRegistry(): BrandedEnumRegistry {\n const global = globalThis as typeof globalThis & {\n [REGISTRY_KEY]?: BrandedEnumRegistry;\n };\n\n if (!(REGISTRY_KEY in global) || !global[REGISTRY_KEY]) {\n global[REGISTRY_KEY] = {\n enums: new Map<string, RegistryEntry>(),\n valueIndex: new Map<string, Set<string>>(),\n };\n }\n\n return global[REGISTRY_KEY];\n}\n\n/**\n * Registers a branded enum in the global registry.\n * Also updates the value index for reverse lookups.\n *\n * @param enumObj - The branded enum to register\n * @throws Error if an enum with the same ID is already registered\n */\nexport function registerEnum<T extends Record<string, string>>(\n enumObj: BrandedEnum<T>\n): void {\n const registry = getRegistry();\n const enumId = enumObj[ENUM_ID];\n const values = enumObj[ENUM_VALUES];\n\n // Check for duplicate ID\n if (registry.enums.has(enumId)) {\n throw new Error(`Branded enum with ID \"${enumId}\" already exists`);\n }\n\n // Create registry entry\n const entry: RegistryEntry = {\n enumId,\n enumObj: enumObj as BrandedEnum<Record<string, string>>,\n values,\n };\n\n // Add to enums map\n registry.enums.set(enumId, entry);\n\n // Update value index for reverse lookups\n for (const value of values) {\n let enumIds = registry.valueIndex.get(value);\n if (!enumIds) {\n enumIds = new Set<string>();\n registry.valueIndex.set(value, enumIds);\n }\n enumIds.add(enumId);\n }\n}\n\n/**\n * Gets all registered enum IDs.\n *\n * Returns an array of all enum IDs that have been registered via\n * `createBrandedEnum`. Useful for debugging or introspection.\n *\n * @returns Array of all registered enum IDs. Returns empty array if no\n * enums have been registered.\n *\n * @example\n * createBrandedEnum('colors', { Red: 'red' } as const);\n * createBrandedEnum('sizes', { Small: 'small' } as const);\n *\n * getAllEnumIds(); // ['colors', 'sizes']\n */\nexport function getAllEnumIds(): string[] {\n const registry = getRegistry();\n return Array.from(registry.enums.keys());\n}\n\n/**\n * Gets a branded enum by its ID.\n *\n * Retrieves a previously registered branded enum from the global registry.\n * Useful when you need to access an enum dynamically by its ID.\n *\n * @param enumId - The enum ID to look up\n * @returns The branded enum object if found, or `undefined` if no enum\n * with the given ID has been registered.\n *\n * @example\n * const Status = createBrandedEnum('status', { Active: 'active' } as const);\n *\n * const retrieved = getEnumById('status');\n * console.log(retrieved === Status); // true\n *\n * const notFound = getEnumById('nonexistent');\n * console.log(notFound); // undefined\n */\nexport function getEnumById(\n enumId: string\n): BrandedEnum<Record<string, string>> | undefined {\n const registry = getRegistry();\n const entry = registry.enums.get(enumId);\n return entry?.enumObj;\n}\n\n/**\n * Finds all enum IDs that contain a given value.\n *\n * Performs a reverse lookup to find which enums contain a specific value.\n * Useful for debugging value collisions or routing values to handlers.\n *\n * @param value - The string value to search for\n * @returns Array of enum IDs that contain the value. Returns empty array\n * if no enums contain the value.\n *\n * @example\n * // Single enum containing value\n * createBrandedEnum('colors', { Red: 'red', Blue: 'blue' } as const);\n * findEnumSources('red'); // ['colors']\n *\n * @example\n * // Multiple enums with same value (collision detection)\n * createBrandedEnum('status1', { Active: 'active' } as const);\n * createBrandedEnum('status2', { Enabled: 'active' } as const);\n * findEnumSources('active'); // ['status1', 'status2']\n *\n * @example\n * // Value not found\n * findEnumSources('nonexistent'); // []\n */\nexport function findEnumSources(value: string): string[] {\n const registry = getRegistry();\n const enumIds = registry.valueIndex.get(value);\n return enumIds ? Array.from(enumIds) : [];\n}\n"],"names":["REGISTRY_KEY","ENUM_ID","ENUM_VALUES","getRegistry","global","globalThis","enums","Map","valueIndex","registerEnum","enumObj","registry","enumId","values","has","Error","entry","set","value","enumIds","get","Set","add","getAllEnumIds","Array","from","keys","getEnumById","findEnumSources"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA;;;;;CAKC,GAED,SAIEA,YAAY,EACZC,OAAO,EACPC,WAAW,QACN,aAAa;AAEpB;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC;IACd,MAAMC,SAASC;IAIf,IAAI,CAAEL,CAAAA,gBAAgBI,MAAK,KAAM,CAACA,MAAM,CAACJ,aAAa,EAAE;QACtDI,MAAM,CAACJ,aAAa,GAAG;YACrBM,OAAO,IAAIC;YACXC,YAAY,IAAID;QAClB;IACF;IAEA,OAAOH,MAAM,CAACJ,aAAa;AAC7B;AAEA;;;;;;CAMC,GACD,OAAO,SAASS,aACdC,OAAuB;IAEvB,MAAMC,WAAWR;IACjB,MAAMS,SAASF,OAAO,CAACT,QAAQ;IAC/B,MAAMY,SAASH,OAAO,CAACR,YAAY;IAEnC,yBAAyB;IACzB,IAAIS,SAASL,KAAK,CAACQ,GAAG,CAACF,SAAS;QAC9B,MAAM,IAAIG,MAAM,CAAC,sBAAsB,EAAEH,OAAO,gBAAgB,CAAC;IACnE;IAEA,wBAAwB;IACxB,MAAMI,QAAuB;QAC3BJ;QACAF,SAASA;QACTG;IACF;IAEA,mBAAmB;IACnBF,SAASL,KAAK,CAACW,GAAG,CAACL,QAAQI;IAE3B,yCAAyC;IACzC,KAAK,MAAME,SAASL,OAAQ;QAC1B,IAAIM,UAAUR,SAASH,UAAU,CAACY,GAAG,CAACF;QACtC,IAAI,CAACC,SAAS;YACZA,U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lib/types.ts"],"sourcesContent":["/**\n * Core type definitions for branded-enum library\n *\n * These types enable runtime-identifiable enum-like objects in TypeScript\n * with zero runtime overhead for value access.\n */\n\n/**\n * Symbol key for storing the enum ID metadata.\n * Using a Symbol prevents collision with user-defined keys.\n */\nexport const ENUM_ID: unique symbol = Symbol('ENUM_ID');\n\n/**\n * Symbol key for storing the enum values Set.\n * Using a Symbol prevents collision with user-defined keys.\n */\nexport const ENUM_VALUES: unique symbol = Symbol('ENUM_VALUES');\n\n/**\n * Metadata attached to branded enums via Symbol properties.\n * These properties are non-enumerable and won't appear in\n * Object.keys(), Object.values(), or JSON serialization.\n */\nexport interface BrandedEnumMetadata {\n readonly [ENUM_ID]: string;\n readonly [ENUM_VALUES]: Set<string>;\n}\n\n/**\n * A branded enum object - combines the user's values object with metadata.\n * The object is frozen (Readonly) to prevent modification after creation.\n *\n * @template T - The shape of the enum values object (Record<string, string>)\n */\nexport type BrandedEnum<T extends Record<string, string>> = Readonly<T> &\n BrandedEnumMetadata;\n\n/**\n * Base constraint type for branded enums that works with both\n * `as const` objects and regular Record<string, string> objects.\n *\n * This type is more permissive than `BrandedEnum<Record<string, string>>`\n * and allows literal types from `as const` assertions.\n */\nexport type AnyBrandedEnum = {\n readonly [ENUM_ID]: string;\n readonly [ENUM_VALUES]: Set<string>;\n};\n\n/**\n * Utility type to extract the union of all value types from a branded enum.\n * Useful for typing variables that can hold any value from the enum.\n *\n * @template E - A BrandedEnum type\n *\n * @example\n * const Status = createBrandedEnum('status', { Active: 'active', Inactive: 'inactive' } as const);\n * type StatusValue = BrandedEnumValue<typeof Status>; // 'active' | 'inactive'\n */\nexport type BrandedEnumValue<E extends AnyBrandedEnum> =\n E extends BrandedEnum<infer T> ? T[keyof T] : never;\n\n/**\n * Registry entry for tracking a single branded enum in the global registry.\n */\nexport interface RegistryEntry {\n /** The unique identifier for this enum */\n readonly enumId: string;\n /** The branded enum object itself */\n readonly enumObj: BrandedEnum<Record<string, string>>;\n /** Set of all values in this enum for O(1) lookup */\n readonly values: Set<string>;\n}\n\n/**\n * Global registry structure stored on globalThis.\n * Enables cross-bundle tracking of all branded enums.\n */\nexport interface BrandedEnumRegistry {\n /** Map from enumId to registry entry */\n readonly enums: Map<string, RegistryEntry>;\n /** Reverse index: value -> Set of enumIds containing that value */\n readonly valueIndex: Map<string, Set<string>>;\n}\n\n/**\n * The key used to store the registry on globalThis.\n * Namespaced to avoid collisions with other libraries.\n */\nexport const REGISTRY_KEY = '__brandedEnumRegistry__' as const;\n\n/**\n * The key used to store the enum consumer registry on globalThis.\n * Tracks which classes consume which branded enums.\n */\nexport const CONSUMER_REGISTRY_KEY = '__brandedEnumConsumerRegistry__' as const;\n\n/**\n * Entry tracking a class that consumes branded enums.\n */\nexport interface EnumConsumerEntry {\n /** The class constructor function */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly classRef: new (...args: any[]) => any;\n /** The class name */\n readonly className: string;\n /** Set of enum IDs that this class consumes */\n readonly enumIds: Set<string>;\n}\n\n/**\n * Global registry for tracking enum consumers (classes decorated with @EnumClass).\n * Enables debugging and introspection of enum usage across the codebase.\n */\nexport interface EnumConsumerRegistry {\n /** Map from class name to consumer entry */\n readonly consumers: Map<string, EnumConsumerEntry>;\n /** Reverse index: enumId -> Set of class names consuming that enum */\n readonly enumToConsumers: Map<string, Set<string>>;\n}\n\n// =============================================================================\n// Compile-Time Validation Types\n// =============================================================================\n\n/**\n * Extracts the union of all keys from a branded enum.\n *\n * This utility type provides compile-time access to all key names of a branded enum,\n * excluding the Symbol metadata keys (ENUM_ID and ENUM_VALUES).\n *\n * @template E - A BrandedEnum type\n *\n * @example\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * } as const);\n *\n * type StatusKeys = EnumKeys<typeof Status>;\n * // StatusKeys = 'Active' | 'Inactive' | 'Pending'\n *\n * @example\n * // Use in function parameters\n * function getStatusLabel<E extends AnyBrandedEnum>(\n * enumObj: E,\n * key: EnumKeys<E>\n * ): string {\n * return enumObj[key] as string;\n * }\n */\nexport type EnumKeys<E> = E extends BrandedEnum<infer T>\n ? keyof T & string\n : E extends AnyBrandedEnum\n ? Exclude<keyof E, typeof ENUM_ID | typeof ENUM_VALUES> & string\n : never;\n\n/**\n * Extracts the union of all values from a branded enum.\n *\n * This is an alias for BrandedEnumValue that provides a more intuitive name\n * when working with compile-time type utilities.\n *\n * @template E - A BrandedEnum type\n *\n * @example\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * } as const);\n *\n * type StatusValues = EnumValues<typeof Status>;\n * // StatusValues = 'active' | 'inactive' | 'pending'\n *\n * @example\n * // Use for type-safe value handling\n * function processStatus(value: EnumValues<typeof Status>) {\n * // value is 'active' | 'inactive' | 'pending'\n * }\n */\nexport type EnumValues<E> = E extends BrandedEnum<infer T>\n ? T[keyof T]\n : E extends AnyBrandedEnum\n ? Exclude<E[Exclude<keyof E, typeof ENUM_ID | typeof ENUM_VALUES>], Set<string>> & string\n : never;\n\n/**\n * Validates that a value type V is a valid value of branded enum E at compile time.\n *\n * If V is a valid value of E, this type resolves to V.\n * If V is NOT a valid value of E, this type resolves to `never`, causing a compile error\n * when used in contexts that expect a non-never type.\n *\n * This enables compile-time validation of enum values without runtime overhead.\n *\n * @template E - A BrandedEnum type\n * @template V - The value type to validate\n *\n * @example\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * } as const);\n *\n * // Valid - 'active' is in Status\n * type Valid = ValidEnumValue<typeof Status, 'active'>; // 'active'\n *\n * // Invalid - 'unknown' is not in Status\n * type Invalid = ValidEnumValue<typeof Status, 'unknown'>; // never\n *\n * @example\n * // Use in function to enforce valid values at compile time\n * function setStatus<V extends string>(\n * value: ValidEnumValue<typeof Status, V>\n * ): void {\n * // Only compiles if value is 'active' | 'inactive'\n * }\n *\n * setStatus('active'); // OK\n * setStatus('inactive'); // OK\n * // setStatus('unknown'); // Compile error: Argument of type 'never' is not assignable\n *\n * @example\n * // Type-level assertion\n * type AssertActive = ValidEnumValue<typeof Status, 'active'>; // 'active' - OK\n * type AssertBad = ValidEnumValue<typeof Status, 'bad'>; // never - indicates invalid\n */\nexport type ValidEnumValue<E, V extends string> = V extends EnumValues<E>\n ? V\n : never;\n\n/**\n * Creates a strict parameter type that only accepts valid values from a branded enum.\n *\n * This utility type is designed for function parameters where you want to enforce\n * that only values from a specific branded enum are accepted at compile time.\n *\n * Unlike using `BrandedEnumValue<E>` directly, `StrictEnumParam` provides better\n * error messages and works well with generic functions.\n *\n * @template E - A BrandedEnum type\n *\n * @example\n * const Status = createBrandedEnum('status', {\n * Active: 'active',\n * Inactive: 'inactive',\n * Pending: 'pending',\n * } as const);\n *\n * // Function that only accepts Status values\n * function updateStatus(newStatus: StrictEnumParam<typeof Status>): void {\n * console.log(`Status updated to: ${newStatus}`);\n * }\n *\n * updateStatus(Status.Active); // OK\n * updateStatus('active'); // OK (literal type matches)\n * // updateStatus('unknown'); // Compile error\n *\n * @example\n * // Use with multiple enum parameters\n * const Priority = createBrandedEnum('priority', {\n * High: 'high',\n * Medium: 'medium',\n * Low: 'low',\n * } as const);\n *\n * function createTask(\n * status: StrictEnumParam<typeof Status>,\n * priority: StrictEnumParam<typeof Priority>\n * ): void {\n * // Both parameters are type-safe\n * }\n *\n * createTask(Status.Active, Priority.High); // OK\n * createTask('active', 'high'); // OK\n * // createTask('active', 'invalid'); // Compile error on second param\n *\n * @example\n * // Generic function with strict enum constraint\n * function processValue<E extends AnyBrandedEnum>(\n * enumObj: E,\n * value: StrictEnumParam<E>\n * ): void {\n * // value is guaranteed to be a valid value of enumObj\n * }\n */\nexport type StrictEnumParam<E> = EnumValues<E>;\n"],"names":["ENUM_ID","Symbol","ENUM_VALUES","REGISTRY_KEY","CONSUMER_REGISTRY_KEY"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;","mappings":"AAAA;;;;;CAKC,GAED;;;CAGC,GACD,OAAO,MAAMA,UAAyBC,OAAO,WAAW;AAExD;;;CAGC,GACD,OAAO,MAAMC,cAA6BD,OAAO,eAAe;AAqEhE;;;CAGC,GACD,OAAO,MAAME,eAAe,0BAAmC;AAE/D;;;CAGC,GACD,OAAO,MAAMC,wBAAwB,kCAA2C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/lib/utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,cAAc,EAKd,QAAQ,EACR,UAAU,EACX,MAAM,YAAY,CAAC;AAmBpB;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,cAAc,EAC/C,OAAO,EAAE,CAAC,EACV,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,UAAU,CAAC,CAAC,CAAC,CAQxB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAgB,cAAc,CAAC,CAAC,SAAS,cAAc,EACrD,OAAO,EAAE,CAAC,EACV,KAAK,EAAE,MAAM,GACZ,QAAQ,CAAC,CAAC,CAAC,GAAG,SAAS,CAUzB;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,cAAc,EACjD,OAAO,EAAE,CAAC,EACV,GAAG,EAAE,OAAO,GACX,GAAG,IAAI,QAAQ,CAAC,CAAC,CAAC,CAQpB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAiB,WAAW,CAAC,CAAC,SAAS,cAAc,EACnD,OAAO,EAAE,CAAC,GACT,gBAAgB,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAOhD"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/lib/utils.ts"],"sourcesContent":["/**\n * Utility functions for branded enums.\n *\n * Provides additional functionality beyond standard enum operations,\n * including reverse lookup, key validation, and iteration.\n */\n\nimport {\n AnyBrandedEnum,\n BrandedEnum,\n BrandedEnumValue,\n ENUM_ID,\n ENUM_VALUES,\n EnumKeys,\n EnumValues,\n} from './types.js';\n\n/**\n * Checks if an object is a branded enum (has Symbol metadata).\n *\n * @param obj - The object to check\n * @returns true if obj is a branded enum\n */\nfunction isBrandedEnum(obj: unknown): obj is AnyBrandedEnum {\n return (\n obj !== null &&\n typeof obj === 'object' &&\n ENUM_ID in obj &&\n ENUM_VALUES in obj &&\n typeof (obj as AnyBrandedEnum)[ENUM_ID] === 'string' &&\n (obj as AnyBrandedEnum)[ENUM_VALUES] instanceof Set\n );\n}\n\n/**\n * Checks if a value exists in a branded enum (reverse lookup).\n *\n * Similar to `isFromEnum`, but with arguments in a different order that\n * may be more natural for some use cases. Also provides type narrowing.\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to search in\n * @param value - The value to check. Can be any type; non-strings return false.\n * @returns `true` if the value exists in the enum (with type narrowing),\n * `false` otherwise. Returns `false` for non-string values or if\n * enumObj is not a branded enum.\n *\n * @example\n * // Check if value exists\n * const Status = createBrandedEnum('status', { Active: 'active', Inactive: 'inactive' } as const);\n * hasValue(Status, 'active'); // true\n * hasValue(Status, 'unknown'); // false\n *\n * @example\n * // Returns false for non-string values\n * hasValue(Status, 123); // false\n * hasValue(Status, null); // false\n */\nexport function hasValue<E extends AnyBrandedEnum>(\n enumObj: E,\n value: unknown\n): value is EnumValues<E> {\n if (!isBrandedEnum(enumObj)) {\n return false;\n }\n if (typeof value !== 'string') {\n return false;\n }\n return enumObj[ENUM_VALUES].has(value);\n}\n\n/**\n * Gets the key name for a value in a branded enum.\n *\n * Performs a reverse lookup to find which key maps to a given value.\n * If multiple keys have the same value, returns the first one found\n * (order is not guaranteed).\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to search in\n * @param value - The string value to look up\n * @returns The key name that maps to the value, or `undefined` if the\n * value is not found or enumObj is not a branded enum.\n *\n * @example\n * // Find key for value\n * const Status = createBrandedEnum('status', { Active: 'active', Inactive: 'inactive' } as const);\n * getKeyForValue(Status, 'active'); // 'Active'\n * getKeyForValue(Status, 'inactive'); // 'Inactive'\n *\n * @example\n * // Returns undefined for unknown values\n * getKeyForValue(Status, 'unknown'); // undefined\n *\n * @example\n * // Roundtrip: value -> key -> value\n * const key = getKeyForValue(Status, 'active'); // 'Active'\n * Status[key]; // 'active'\n */\nexport function getKeyForValue<E extends AnyBrandedEnum>(\n enumObj: E,\n value: string\n): EnumKeys<E> | undefined {\n if (!isBrandedEnum(enumObj)) {\n return undefined;\n }\n for (const key of Object.keys(enumObj)) {\n if ((enumObj as Record<string, unknown>)[key] === value) {\n return key as EnumKeys<E>;\n }\n }\n return undefined;\n}\n\n/**\n * Checks if a key exists in a branded enum.\n *\n * Validates whether a given key is a valid member of the enum.\n * Returns false for Symbol keys (metadata) and non-string keys.\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to check\n * @param key - The key to validate. Can be any type; non-strings return false.\n * @returns `true` if the key exists in the enum (with type narrowing),\n * `false` otherwise. Returns `false` for metadata Symbol keys or if\n * enumObj is not a branded enum.\n *\n * @example\n * // Check if key exists\n * const Status = createBrandedEnum('status', { Active: 'active', Inactive: 'inactive' } as const);\n * isValidKey(Status, 'Active'); // true\n * isValidKey(Status, 'Inactive'); // true\n * isValidKey(Status, 'Unknown'); // false\n *\n * @example\n * // Returns false for non-string keys\n * isValidKey(Status, 123); // false\n * isValidKey(Status, Symbol('test')); // false\n */\nexport function isValidKey<E extends AnyBrandedEnum>(\n enumObj: E,\n key: unknown\n): key is EnumKeys<E> {\n if (!isBrandedEnum(enumObj)) {\n return false;\n }\n if (typeof key !== 'string') {\n return false;\n }\n return Object.prototype.hasOwnProperty.call(enumObj, key);\n}\n\n/**\n * Returns an iterator of [key, value] pairs for a branded enum.\n *\n * Provides a way to iterate over all key-value pairs in the enum using\n * a for...of loop. Only yields user-defined entries, not metadata.\n * Equivalent to `Object.entries(enumObj)` but with proper typing.\n *\n * @template E - The branded enum type\n * @param enumObj - The branded enum to iterate over\n * @returns An iterator yielding [key, value] tuples. Returns an empty\n * iterator if enumObj is not a branded enum.\n *\n * @example\n * // Iterate over entries\n * const Status = createBrandedEnum('status', { Active: 'active', Inactive: 'inactive' } as const);\n *\n * for (const [key, value] of enumEntries(Status)) {\n * console.log(`${key}: ${value}`);\n * }\n * // Output:\n * // Active: active\n * // Inactive: inactive\n *\n * @example\n * // Convert to array\n * const entries = [...enumEntries(Status)];\n * // [['Active', 'active'], ['Inactive', 'inactive']]\n *\n * @example\n * // Use with Array.from\n * const entriesArray = Array.from(enumEntries(Status));\n */\nexport function* enumEntries<E extends AnyBrandedEnum>(\n enumObj: E\n): IterableIterator<[EnumKeys<E>, EnumValues<E>]> {\n if (!isBrandedEnum(enumObj)) {\n return;\n }\n for (const [key, value] of Object.entries(enumObj)) {\n yield [key as EnumKeys<E>, value as EnumValues<E>];\n }\n}\n"],"names":["ENUM_ID","ENUM_VALUES","isBrandedEnum","obj","Set","hasValue","enumObj","value","has","getKeyForValue","undefined","key","Object","keys","isValidKey","prototype","hasOwnProperty","call","enumEntries","entries"],"rangeMappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","mappings":"AAAA;;;;;CAKC,GAED,SAIEA,OAAO,EACPC,WAAW,QAGN,aAAa;AAEpB;;;;;CAKC,GACD,SAASC,cAAcC,GAAY;IACjC,OACEA,QAAQ,QACR,OAAOA,QAAQ,YACfH,WAAWG,OACXF,eAAeE,OACf,OAAO,AAACA,GAAsB,CAACH,QAAQ,KAAK,YAC5C,AAACG,GAAsB,CAACF,YAAY,YAAYG;AAEpD;AAEA;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GACD,OAAO,SAASC,SACdC,OAAU,EACVC,KAAc;IAEd,IAAI,CAACL,cAAcI,UAAU;QAC3B,OAAO;IACT;IACA,IAAI,OAAOC,UAAU,UAAU;QAC7B,OAAO;IACT;IACA,OAAOD,OAAO,CAACL,YAAY,CAACO,GAAG,CAACD;AAClC;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASE,eACdH,OAAU,EACVC,KAAa;IAEb,IAAI,CAACL,cAAcI,UAAU;QAC3B,OAAOI;IACT;IACA,KAAK,MAAMC,OAAOC,OAAOC,IAAI,CAACP,SAAU;QACtC,IAAI,AAACA,OAAmC,CAACK,IAAI,KAAKJ,OAAO;YACvD,OAAOI;QACT;IACF;IACA,OAAOD;AACT;AAEA;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,SAASI,WACdR,OAAU,EACVK,GAAY;IAEZ,IAAI,CAACT,cAAcI,UAAU;QAC3B,OAAO;IACT;IACA,IAAI,OAAOK,QAAQ,UAAU;QAC3B,OAAO;IACT;IACA,OAAOC,OAAOG,SAAS,CAACC,cAAc,CAACC,IAAI,CAACX,SAASK;AACvD;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA+BC,GACD,OAAO,UAAUO,YACfZ,OAAU;IAEV,IAAI,CAACJ,cAAcI,UAAU;QAC3B;IACF;IACA,KAAK,MAAM,CAACK,KAAKJ,MAAM,IAAIK,OAAOO,OAAO,CAACb,SAAU;QAClD,MAAM;YAACK;YAAoBJ;SAAuB;IACpD;AACF"}
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes