@reharik/smart-enum 0.3.3 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +18 -362
  2. package/dist/{chunk-TXDI7ASS.js → chunk-6PARBLRO.js} +2 -2
  3. package/dist/{chunk-CZ6TMH26.js → chunk-6ZOLTEJT.js} +2 -2
  4. package/dist/{chunk-SOZ6HB6K.js → chunk-OOVDWS5T.js} +26 -6
  5. package/dist/chunk-OOVDWS5T.js.map +1 -0
  6. package/dist/{chunk-3RPLSRWV.js → chunk-RHESWOIM.js} +2 -2
  7. package/dist/core.cjs +17 -5
  8. package/dist/core.cjs.map +1 -1
  9. package/dist/core.d.cts +2 -2
  10. package/dist/core.d.ts +2 -2
  11. package/dist/core.js +2 -2
  12. package/dist/database.cjs +17 -5
  13. package/dist/database.cjs.map +1 -1
  14. package/dist/database.d.cts +2 -2
  15. package/dist/database.d.ts +2 -2
  16. package/dist/database.js +2 -2
  17. package/dist/graphql.cjs +14 -1
  18. package/dist/graphql.cjs.map +1 -1
  19. package/dist/graphql.d.cts +3 -1
  20. package/dist/graphql.d.ts +3 -1
  21. package/dist/graphql.js +14 -1
  22. package/dist/graphql.js.map +1 -1
  23. package/dist/index.cjs +29 -5
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +20 -1
  26. package/dist/index.d.ts +20 -1
  27. package/dist/index.js +9 -5
  28. package/dist/{transformation-CVR7F8nY.d.cts → transformation-BMIA2TEH.d.cts} +23 -1
  29. package/dist/{transformation-CVR7F8nY.d.ts → transformation-BMIA2TEH.d.ts} +23 -1
  30. package/dist/transport.cjs +17 -5
  31. package/dist/transport.cjs.map +1 -1
  32. package/dist/transport.d.cts +2 -2
  33. package/dist/transport.d.ts +2 -2
  34. package/dist/transport.js +2 -2
  35. package/package.json +1 -1
  36. package/dist/chunk-SOZ6HB6K.js.map +0 -1
  37. /package/dist/{chunk-TXDI7ASS.js.map → chunk-6PARBLRO.js.map} +0 -0
  38. /package/dist/{chunk-CZ6TMH26.js.map → chunk-6ZOLTEJT.js.map} +0 -0
  39. /package/dist/{chunk-3RPLSRWV.js.map → chunk-RHESWOIM.js.map} +0 -0
@@ -83,6 +83,10 @@ type StandardEnumItem = StandardEnumItemBase & {
83
83
  readonly __smart_enum_brand: true;
84
84
  readonly __smart_enum_type: string;
85
85
  readonly toPostgres: () => string;
86
+ readonly toJSON: () => string | {
87
+ __smart_enum_type: string;
88
+ value: string;
89
+ };
86
90
  };
87
91
  type EnumInputItem = Partial<{
88
92
  key: string;
@@ -193,9 +197,27 @@ type RevivePayloadOptions = {
193
197
  pathEnumMapping: PathEnumMapping;
194
198
  strict?: boolean;
195
199
  };
200
+ /**
201
+ * Serialization mode controls how smart-enum items are serialized to JSON.
202
+ *
203
+ * - 'wrapped' (default): toJSON returns { __smart_enum_type, value }.
204
+ * Use this when payloads need to be self-describing for revival on the
205
+ * receiving end (e.g. REST APIs with explicit revive middleware).
206
+ *
207
+ * - 'value': toJSON returns just the wire value string.
208
+ * Use this when the receiving end already knows the enum types from
209
+ * schema context (e.g. GraphQL boundaries).
210
+ *
211
+ * Resolution order at toJSON call time:
212
+ * 1. Per-enum `serializeAs` option (if set on enumeration())
213
+ * 2. Global default (set via setDefaultSerializationMode)
214
+ * 3. 'wrapped' (built-in default, preserves backward compatibility)
215
+ */
216
+ type SerializationMode = 'wrapped' | 'value';
196
217
  type EnumerationProps<TInput> = {
197
218
  input: TInput;
198
219
  propertyAutoFormatters?: PropertyAutoFormatter[];
220
+ serializeAs?: SerializationMode;
199
221
  };
200
222
  type Enumeration<TEnum> = TEnum extends Record<string, infer V> ? V extends {
201
223
  __smart_enum_brand: true;
@@ -292,4 +314,4 @@ declare function reviveSmartEnums<R>(input: unknown, registry: Record<string, An
292
314
  */
293
315
  declare const reviveEnumField: <TItem>(value: unknown, smartEnum: AnyEnumLike<TItem>, strict?: boolean) => TItem | undefined;
294
316
 
295
- export { type AnyEnumLike as A, type DatabaseFormat as D, type Enumeration as E, type FieldEnumMapping as F, type Logger as L, type PathEnumMapping as P, type RevivedSmartEnums as R, type SmartApiHelperConfig as S, isSmartEnum as a, reviveEnumField as b, type LogLevel as c, type SmartEnumMappingsConfig as d, enumeration as e, type SerializedSmartEnums as f, type SmartEnumItemSerialized as g, type EnumLikeBase as h, isSmartEnumItem as i, type SmartEnumLike as j, type ReviveRowOptions as k, type RevivePayloadOptions as l, type StandardEnumItemBase as m, type StandardEnumItem as n, type SmartEnumMemberUnion as o, type SmartEnumSubsetView as p, reviveSmartEnums as r, serializeSmartEnums as s };
317
+ export { type AnyEnumLike as A, type DatabaseFormat as D, type Enumeration as E, type FieldEnumMapping as F, type Logger as L, type PathEnumMapping as P, type RevivedSmartEnums as R, type SerializationMode as S, isSmartEnum as a, reviveEnumField as b, type SmartApiHelperConfig as c, type LogLevel as d, enumeration as e, type SmartEnumMappingsConfig as f, type SerializedSmartEnums as g, type SmartEnumItemSerialized as h, isSmartEnumItem as i, type EnumLikeBase as j, type SmartEnumLike as k, type ReviveRowOptions as l, type RevivePayloadOptions as m, type StandardEnumItemBase as n, type StandardEnumItem as o, type SmartEnumMemberUnion as p, type SmartEnumSubsetView as q, reviveSmartEnums as r, serializeSmartEnums as s };
@@ -83,6 +83,10 @@ type StandardEnumItem = StandardEnumItemBase & {
83
83
  readonly __smart_enum_brand: true;
84
84
  readonly __smart_enum_type: string;
85
85
  readonly toPostgres: () => string;
86
+ readonly toJSON: () => string | {
87
+ __smart_enum_type: string;
88
+ value: string;
89
+ };
86
90
  };
87
91
  type EnumInputItem = Partial<{
88
92
  key: string;
@@ -193,9 +197,27 @@ type RevivePayloadOptions = {
193
197
  pathEnumMapping: PathEnumMapping;
194
198
  strict?: boolean;
195
199
  };
200
+ /**
201
+ * Serialization mode controls how smart-enum items are serialized to JSON.
202
+ *
203
+ * - 'wrapped' (default): toJSON returns { __smart_enum_type, value }.
204
+ * Use this when payloads need to be self-describing for revival on the
205
+ * receiving end (e.g. REST APIs with explicit revive middleware).
206
+ *
207
+ * - 'value': toJSON returns just the wire value string.
208
+ * Use this when the receiving end already knows the enum types from
209
+ * schema context (e.g. GraphQL boundaries).
210
+ *
211
+ * Resolution order at toJSON call time:
212
+ * 1. Per-enum `serializeAs` option (if set on enumeration())
213
+ * 2. Global default (set via setDefaultSerializationMode)
214
+ * 3. 'wrapped' (built-in default, preserves backward compatibility)
215
+ */
216
+ type SerializationMode = 'wrapped' | 'value';
196
217
  type EnumerationProps<TInput> = {
197
218
  input: TInput;
198
219
  propertyAutoFormatters?: PropertyAutoFormatter[];
220
+ serializeAs?: SerializationMode;
199
221
  };
200
222
  type Enumeration<TEnum> = TEnum extends Record<string, infer V> ? V extends {
201
223
  __smart_enum_brand: true;
@@ -292,4 +314,4 @@ declare function reviveSmartEnums<R>(input: unknown, registry: Record<string, An
292
314
  */
293
315
  declare const reviveEnumField: <TItem>(value: unknown, smartEnum: AnyEnumLike<TItem>, strict?: boolean) => TItem | undefined;
294
316
 
295
- export { type AnyEnumLike as A, type DatabaseFormat as D, type Enumeration as E, type FieldEnumMapping as F, type Logger as L, type PathEnumMapping as P, type RevivedSmartEnums as R, type SmartApiHelperConfig as S, isSmartEnum as a, reviveEnumField as b, type LogLevel as c, type SmartEnumMappingsConfig as d, enumeration as e, type SerializedSmartEnums as f, type SmartEnumItemSerialized as g, type EnumLikeBase as h, isSmartEnumItem as i, type SmartEnumLike as j, type ReviveRowOptions as k, type RevivePayloadOptions as l, type StandardEnumItemBase as m, type StandardEnumItem as n, type SmartEnumMemberUnion as o, type SmartEnumSubsetView as p, reviveSmartEnums as r, serializeSmartEnums as s };
317
+ export { type AnyEnumLike as A, type DatabaseFormat as D, type Enumeration as E, type FieldEnumMapping as F, type Logger as L, type PathEnumMapping as P, type RevivedSmartEnums as R, type SerializationMode as S, isSmartEnum as a, reviveEnumField as b, type SmartApiHelperConfig as c, type LogLevel as d, enumeration as e, type SmartEnumMappingsConfig as f, type SerializedSmartEnums as g, type SmartEnumItemSerialized as h, isSmartEnumItem as i, type EnumLikeBase as j, type SmartEnumLike as k, type ReviveRowOptions as l, type RevivePayloadOptions as m, type StandardEnumItemBase as n, type StandardEnumItem as o, type SmartEnumMemberUnion as p, type SmartEnumSubsetView as q, reviveSmartEnums as r, serializeSmartEnums as s };
@@ -62,6 +62,10 @@ var SMART_ENUM_ITEM = Symbol("smart-enum-item");
62
62
  var SMART_ENUM_ID = Symbol("smart-enum-id");
63
63
  var SMART_ENUM = Symbol("smart-enum");
64
64
 
65
+ // src/utilities/serializationMode.ts
66
+ var globalDefault;
67
+ var resolveSerializationMode = (perEnum) => perEnum ?? globalDefault ?? "wrapped";
68
+
65
69
  // src/enumerations.ts
66
70
  function normalizeInput(input) {
67
71
  if (Array.isArray(input)) {
@@ -71,7 +75,7 @@ function normalizeInput(input) {
71
75
  }
72
76
  return input;
73
77
  }
74
- var finalizeEnumItem = (item, enumType, enumInstanceId) => {
78
+ var finalizeEnumItem = (item, enumType, enumInstanceId, serializeAs) => {
75
79
  Object.defineProperty(item, SMART_ENUM_ITEM, {
76
80
  value: true,
77
81
  enumerable: false
@@ -89,7 +93,13 @@ var finalizeEnumItem = (item, enumType, enumInstanceId) => {
89
93
  enumerable: false
90
94
  });
91
95
  Object.defineProperty(item, "toJSON", {
92
- value: () => ({ __smart_enum_type: enumType, value: item.value }),
96
+ value: () => {
97
+ const mode = resolveSerializationMode(serializeAs);
98
+ if (mode === "value") {
99
+ return item.value;
100
+ }
101
+ return { __smart_enum_type: enumType, value: item.value };
102
+ },
93
103
  enumerable: false
94
104
  });
95
105
  Object.defineProperty(item, "toPostgres", {
@@ -108,7 +118,7 @@ var formatProperties = (k, formatters) => formatters.reduce(
108
118
  display: (0, import_case_anything.capitalCase)(k)
109
119
  }
110
120
  );
111
- function buildEnumFromObject(enumType, input, propertyAutoFormatters) {
121
+ function buildEnumFromObject(enumType, input, propertyAutoFormatters, serializeAs) {
112
122
  const formattersWithDefaults = [
113
123
  { key: "value", format: import_case_anything.constantCase },
114
124
  { key: "display", format: import_case_anything.capitalCase },
@@ -130,7 +140,8 @@ function buildEnumFromObject(enumType, input, propertyAutoFormatters) {
130
140
  const enumItem = finalizeEnumItem(
131
141
  enumItemBase,
132
142
  enumType,
133
- enumInstanceId
143
+ enumInstanceId,
144
+ serializeAs
134
145
  );
135
146
  Object.freeze(enumItem);
136
147
  rawEnumItems[typedKey] = enumItem;
@@ -156,7 +167,8 @@ function enumeration(enumType, props) {
156
167
  return buildEnumFromObject(
157
168
  enumType,
158
169
  normalized,
159
- props.propertyAutoFormatters
170
+ props.propertyAutoFormatters,
171
+ props.serializeAs
160
172
  );
161
173
  }
162
174
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/transport.ts","../src/enumerations.ts","../src/extensionMethods.ts","../src/types.ts","../src/utilities/typeGuards.ts","../src/utilities/logger.ts","../src/utilities/transformation.ts","../src/utilities/transport/transportRegistry.ts","../src/utilities/transport/reviveAfterTransport.ts","../src/utilities/transport/serializeForTransport.ts"],"sourcesContent":["/**\n * Smart Enums with Transport Utilities\n *\n * This entry point includes the core enumeration functionality plus utilities\n * for serializing/reviving enums for API transport (JSON over the wire).\n *\n * @example\n * ```typescript\n * import { enumeration, serializeForTransport, reviveAfterTransport } from '@reharik/smart-enum/transport';\n * ```\n */\n\n// Re-export core functionality\nexport { enumeration } from './enumerations.js';\nexport { isSmartEnumItem, isSmartEnum } from './utilities/typeGuards.js';\nexport {\n serializeSmartEnums,\n reviveSmartEnums,\n reviveEnumField,\n} from './utilities/transformation.js';\nexport {\n reviveAfterTransport,\n serializeForTransport,\n initializeSmartEnumMappings,\n getGlobalEnumRegistry,\n} from './utilities/transport/index.js';\n\n// Re-export core types plus transport-specific types\nexport type {\n Enumeration,\n AnyEnumLike,\n SerializedSmartEnums,\n RevivedSmartEnums,\n SmartEnumItemSerialized,\n LogLevel,\n SmartEnumMappingsConfig,\n StandardEnumItemBase,\n StandardEnumItem,\n} from './types.js';\n","import { capitalCase, constantCase } from 'case-anything';\n\nimport { addExtensionMethods } from './extensionMethods.js';\nimport {\n SMART_ENUM,\n SMART_ENUM_ID,\n SMART_ENUM_ITEM,\n type EnumFromNormalizedObject,\n type EnumItemFromNormalizedObject,\n type EnumMemberUnionFromNormalizedObject,\n type EnumerationProps,\n type FinalizableEnumItem,\n type FinalizedEnumFields,\n type NormalizedInputType,\n type ObjectEnumInput,\n type PropertyAutoFormatter,\n} from './types.js';\n\nexport type EnumItem<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends { __smart_enum_brand: true }\n ? TEnum[K]\n : never;\n}[keyof TEnum];\n\nfunction normalizeInput<TInput extends readonly string[] | ObjectEnumInput>(\n input: TInput,\n): NormalizedInputType<TInput> {\n if (Array.isArray(input)) {\n return Object.fromEntries(\n input.map(k => [k, {}]),\n ) as NormalizedInputType<TInput>;\n }\n\n return input as NormalizedInputType<TInput>;\n}\n\nconst finalizeEnumItem = <T extends { value: string }>(\n item: T,\n enumType: string,\n enumInstanceId: symbol,\n): T & FinalizedEnumFields => {\n Object.defineProperty(item, SMART_ENUM_ITEM, {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, SMART_ENUM_ID, {\n value: enumInstanceId,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_brand', {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_type', {\n value: enumType,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toJSON', {\n value: () => ({ __smart_enum_type: enumType, value: item.value }),\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toPostgres', {\n value: () => item.value,\n enumerable: false,\n });\n\n return item as T & FinalizedEnumFields;\n};\n\nconst formatProperties = (\n k: string,\n formatters: PropertyAutoFormatter[],\n): { value: string; display: string } & Record<string, string> =>\n formatters.reduce(\n (acc, formatter) => {\n acc[formatter.key] = formatter.format(k);\n return acc;\n },\n {\n value: constantCase(k),\n display: capitalCase(k),\n } as { value: string; display: string } & Record<string, string>,\n );\n\nfunction buildEnumFromObject<TObj extends ObjectEnumInput>(\n enumType: string,\n input: TObj,\n propertyAutoFormatters?: PropertyAutoFormatter[],\n): EnumFromNormalizedObject<TObj> {\n const formattersWithDefaults: PropertyAutoFormatter[] = [\n { key: 'value', format: constantCase },\n { key: 'display', format: capitalCase },\n ...(propertyAutoFormatters ?? []),\n ];\n\n type TItem = EnumMemberUnionFromNormalizedObject<TObj>;\n\n const rawEnumItems: Partial<{\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }> = {};\n\n const enumInstanceId = Symbol('smart-enum-instance');\n let index = 0;\n\n for (const key in input) {\n if (Object.prototype.hasOwnProperty.call(input, key)) {\n const typedKey = key;\n const value = input[typedKey];\n\n const enumItemBase = {\n index,\n key: typedKey,\n ...formatProperties(typedKey, formattersWithDefaults),\n ...value,\n } as FinalizableEnumItem & TObj[typeof typedKey];\n\n const enumItem = finalizeEnumItem(\n enumItemBase,\n enumType,\n enumInstanceId,\n ) as unknown as TItem;\n\n Object.freeze(enumItem);\n rawEnumItems[typedKey as keyof TObj] = enumItem;\n index++;\n }\n }\n\n const extensionMethods = addExtensionMethods<TItem>(\n Object.values(rawEnumItems) as TItem[],\n );\n\n const enumObject = {\n ...rawEnumItems,\n ...extensionMethods,\n } as EnumFromNormalizedObject<TObj>;\n\n Object.defineProperty(enumObject, SMART_ENUM, {\n value: true,\n enumerable: false,\n });\n\n Object.freeze(enumObject);\n\n return enumObject;\n}\n\nexport function enumeration<const TArr extends readonly string[]>(\n enumType: string,\n props: EnumerationProps<TArr>,\n): EnumFromNormalizedObject<NormalizedInputType<TArr>>;\n\nexport function enumeration<const TObj extends ObjectEnumInput>(\n enumType: string,\n props: EnumerationProps<TObj>,\n): EnumFromNormalizedObject<NormalizedInputType<TObj>>;\n\nexport function enumeration(\n enumType: string,\n props: EnumerationProps<readonly string[] | ObjectEnumInput>,\n) {\n const normalized = normalizeInput(props.input);\n return buildEnumFromObject(\n enumType,\n normalized,\n props.propertyAutoFormatters,\n );\n}\n","import type { CoreEnumMethods, StandardEnumItem } from './types.js';\nexport const addExtensionMethods = <TItem extends StandardEnumItem>(\n enumItems: readonly TItem[],\n): CoreEnumMethods<TItem> => {\n const findBy = <K extends keyof TItem>(field: K, target: TItem[K]) =>\n enumItems.find(item => item[field] === target);\n\n const requireBy = <K extends keyof TItem>(\n field: K,\n target: TItem[K],\n label: string,\n ) => {\n const item = findBy(field, target);\n if (!item) {\n throw new Error(`No enum ${label} found for '${String(target)}'`);\n }\n return item;\n };\n\n return {\n fromValue: value => requireBy('value', value as TItem['value'], 'value'),\n tryFromValue: value =>\n value ? findBy('value', value as TItem['value']) : undefined,\n\n fromKey: key => requireBy('key', key as TItem['key'], 'key'),\n tryFromKey: key => (key ? findBy('key', key as TItem['key']) : undefined),\n\n items: () => [...enumItems],\n values: () => enumItems.map(item => item.value),\n keys: () => enumItems.map(item => item.key),\n };\n};\n","/**\n * Type guard to check if a value is not null or undefined\n * @param value - The value to check\n * @returns True if the value is defined and not null\n */\nexport const notEmpty = <X>(\n value: X | null | undefined,\n): value is NonNullable<X> => {\n // eslint-disable-next-line unicorn/no-null\n return value != null;\n};\n\n// Public symbols used at runtime for detection/identity (not used in type keys)\nexport const SMART_ENUM_ITEM = Symbol('smart-enum-item');\nexport const SMART_ENUM_ID = Symbol('smart-enum-id');\nexport const SMART_ENUM = Symbol('smart-enum');\n\n/**\n * Options for filtering enum items in various methods\n */\nexport type EnumFilterOptions = {\n /** Include items with null/undefined values (default: false) */\n showEmpty?: boolean;\n /** Include deprecated items (default: false) */\n showDeprecated?: boolean;\n};\n\n// export type EnumInput = readonly string[] | ObjectEnumInput;\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Structural detection checks for\n * presence of `key` and `value`.\n */\nexport type SerializedSmartEnums<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<SerializedSmartEnums<U>>\n : T extends Array<infer U>\n ? SerializedSmartEnums<U>[]\n : T extends object\n ? { [K in keyof T]: SerializedSmartEnums<T[K]> }\n : T;\n\n/**\n * Revived shape: for keys present in mapping M, the string becomes the\n * corresponding enum item type (derived from the provided enum object);\n * other fields recurse.\n */\nexport type EnumItemFromEnum<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\n/**\n * Structural constraint for smart enum instances (registry entries, `reviveSmartEnums`, etc.).\n * `T` is the enum item type returned by `tryFromValue` / `tryFromKey` (default `unknown` when heterogeneous).\n */\nexport type AnyEnumLike<T = unknown> = {\n tryFromValue: (value?: string | null) => T | undefined;\n tryFromKey: (key?: string | null) => T | undefined;\n} & Record<string, unknown>;\n\nexport type RevivedSmartEnums<T, M extends Record<string, AnyEnumLike>> =\n T extends ReadonlyArray<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends Array<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends object\n ? {\n [K in keyof T]: K extends Extract<keyof M, string>\n ? Enumeration<M[K]>\n : RevivedSmartEnums<T[K], M>;\n }\n : T;\n\nexport type SmartEnumItemSerialized = {\n __smart_enum_type: string;\n value: string;\n};\n\n/** Example shape for transport tests (`reviveAfterTransport` registry). */\nexport type SmartApiHelperConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n};\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Used for database storage.\n */\nexport type DatabaseFormat<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DatabaseFormat<U>>\n : T extends Array<infer U>\n ? DatabaseFormat<U>[]\n : T extends object\n ? { [K in keyof T]: DatabaseFormat<T[K]> }\n : T;\n\n/**\n * Log levels for smart enum mappings\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Configuration for smart enum mappings initialization\n */\nexport type SmartEnumMappingsConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n logLevel?: LogLevel;\n logger?: import('./utilities/logger.js').Logger;\n};\n\ntype BuiltInOverrideKeys =\n | 'key'\n | 'value'\n | 'display'\n | 'deprecated'\n | 'index'\n | '__smart_enum_brand'\n | '__smart_enum_type';\n\n/**\n * Structural fields shared by every enum member (key, value, display, index, optional deprecated).\n * Does not include smart-enum branding or database helpers; see {@link StandardEnumItem}.\n */\nexport type StandardEnumItemBase = {\n readonly key: string;\n readonly value: string;\n readonly display: string;\n readonly index: number;\n readonly deprecated?: boolean;\n};\n\n/**\n * Branded item produced by `enumeration()`: {@link StandardEnumItemBase} plus runtime identity\n * (`__smart_enum_brand`, `__smart_enum_type`) and `toPostgres()`.\n */\nexport type StandardEnumItem = StandardEnumItemBase & {\n readonly __smart_enum_brand: true;\n readonly __smart_enum_type: string;\n readonly toPostgres: () => string;\n};\n\nexport type EnumInputItem = Partial<{\n key: string;\n value: string;\n display: string;\n deprecated: boolean;\n}> &\n Record<string, unknown>;\n\nexport type ObjectEnumInput = Record<string, EnumInputItem>;\n\nexport type EmptyEnumInputItem = Record<never, never>;\n\ntype Separator = '-' | '_' | ' ' | '.';\n\ntype IsUpperChar<C extends string> =\n C extends Uppercase<C> ? (C extends Lowercase<C> ? false : true) : false;\n\ntype IsLowerChar<C extends string> =\n C extends Lowercase<C> ? (C extends Uppercase<C> ? false : true) : false;\n\ntype PushUnderscore<S extends string> = S extends '' | `${string}_`\n ? S\n : `${S}_`;\n\ntype TrimUnderscore<S extends string> = S extends `_${infer R}`\n ? TrimUnderscore<R>\n : S extends `${infer R}_`\n ? TrimUnderscore<R>\n : S;\n\ntype CollapseUnderscores<S extends string> = S extends `${infer A}__${infer B}`\n ? CollapseUnderscores<`${A}_${B}`>\n : S;\n\ntype ConstantCaseInternal<\n S extends string,\n Prev extends string = '',\n Out extends string = '',\n> = S extends `${infer C}${infer Rest}`\n ? C extends Separator\n ? ConstantCaseInternal<Rest, C, PushUnderscore<Out>>\n : IsUpperChar<C> extends true\n ? IsLowerChar<Prev> extends true\n ? ConstantCaseInternal<Rest, C, `${PushUnderscore<Out>}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : CollapseUnderscores<TrimUnderscore<Out>>;\n\ntype ConstantCase<S extends string> = string extends S\n ? string\n : ConstantCaseInternal<S>;\n\n/** Segments of a `ConstantCase` string (underscore-separated ALL CAPS words). */\ntype SplitConstantCaseSegments<S extends string> =\n S extends `${infer A}_${infer B}`\n ? [A, ...SplitConstantCaseSegments<B>]\n : [S];\n\n/** First character upper, remainder lower (for ALL-CAPS words from `ConstantCase`). */\ntype TitleCaseAllCapsWord<W extends string> = W extends ''\n ? ''\n : W extends `${infer F}${infer R}`\n ? `${Uppercase<F>}${Lowercase<R>}`\n : W;\n\ntype JoinDisplaySegments<T extends readonly string[]> = T extends readonly [\n infer A extends string,\n ...infer Rest extends readonly string[],\n]\n ? Rest extends readonly []\n ? TitleCaseAllCapsWord<A>\n : `${TitleCaseAllCapsWord<A>} ${JoinDisplaySegments<Rest>}`\n : '';\n\n/**\n * Display string derived from the enum member key: `ConstantCase` → split → title-case words → join with spaces.\n * Matches default runtime `capitalCase(key)` for typical PascalCase / camelCase keys. Member keys that already\n * contain separators may differ from `capitalCase` at runtime; custom `propertyAutoFormatters` for `display`\n * are not reflected in this type.\n */\ntype DisplayCaseFromEnumKey<K extends string> = string extends K\n ? string\n : JoinDisplaySegments<SplitConstantCaseSegments<ConstantCase<K>>>;\n\nexport type ArrayToObjectType<T extends readonly string[]> = {\n [K in T[number]]: EmptyEnumInputItem & { readonly value?: ConstantCase<K> };\n};\n\nexport type NormalizedInputType<TInput> = TInput extends readonly string[]\n ? ArrayToObjectType<TInput>\n : TInput extends ObjectEnumInput\n ? TInput\n : never;\n\n/** Input-derived fields for one member key (excludes built-ins filled by `enumeration()`). */\nexport type EnumMemberExtra<\n TObj extends ObjectEnumInput,\n K extends keyof TObj,\n> = Omit<TObj[K], BuiltInOverrideKeys>;\n\nexport type EnumItemFromNormalizedObject<\n TObj extends ObjectEnumInput,\n K extends keyof TObj = keyof TObj,\n> = Omit<StandardEnumItem, 'key' | 'value' | 'display'> &\n EnumMemberExtra<TObj, K> & {\n readonly key: Extract<K, string>;\n readonly value: TObj[K] extends { value?: infer V }\n ? [Extract<V, string>] extends [never]\n ? ConstantCase<Extract<K, string>>\n : Extract<V, string>\n : ConstantCase<Extract<K, string>>;\n readonly display: TObj[K] extends { display?: infer D }\n ? [Extract<D, string>] extends [never]\n ? DisplayCaseFromEnumKey<Extract<K, string>>\n : Extract<D, string>\n : DisplayCaseFromEnumKey<Extract<K, string>>;\n };\n\nexport type EnumMemberUnionFromNormalizedObject<TObj extends ObjectEnumInput> =\n {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }[keyof TObj];\n\nexport type EnumFromNormalizedObject<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n} & CoreEnumMethods<EnumMemberUnionFromNormalizedObject<TObj>>;\n\nexport type UnionKeys<T> = T extends T ? keyof T : never;\n\n/*\nTo widen the type of the OptionalObject from literals to their actual types,\ne.g.\nshape?: \"round\" | \"square\" | \"long\";\nslices?: true;\nlayers?: 2;\n--turns into:--\nshape: string | undefined;\nslices: boolean| undefined;\nlayers: number| undefined;\n\nwe can use the following code:\ntype Widen<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T;\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? Widen<V> : undefined;\n};\n*/\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? V : undefined;\n};\n\ntype ExtraShapeUnion<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: Omit<TObj[K], BuiltInOverrideKeys>;\n}[keyof TObj];\n\nexport type InferredExtraFields<TObj extends ObjectEnumInput> =\n MergeUnionToObject<ExtraShapeUnion<TObj>>;\n\nexport type PropertyAutoFormatter = {\n /** The property name to generate */\n key: string;\n /** Function to transform the key into the property value */\n format: (k: string) => string;\n};\n\nexport type CoreEnumMethods<TItem extends StandardEnumItem> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n items(): readonly TItem[];\n /** Matches runtime: `items.map(i => i.value)` (see {@link EnumLikeBase}). */\n values(): readonly TItem['value'][];\n /** Matches runtime: `items.map(i => i.key)` (see {@link EnumLikeBase}). */\n keys(): readonly TItem['key'][];\n};\n\n/**\n * Structural shape of a smart-style enum object: lookup by value/key, list items/values/keys,\n * plus an index signature so registry and mapping types can treat instances as records.\n * Use {@link SmartEnumLike} when items are full {@link StandardEnumItem}s (the usual case).\n */\nexport type EnumLikeBase<\n TItem extends StandardEnumItemBase = StandardEnumItemBase,\n> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n items(): readonly TItem[];\n values(): readonly TItem['value'][];\n keys(): readonly TItem['key'][];\n} & Record<string, unknown>;\n\n/**\n * A {@link EnumLikeBase} whose items are branded {@link StandardEnumItem}s (typical `enumeration()` result).\n */\nexport type SmartEnumLike<TItem extends StandardEnumItem = StandardEnumItem> =\n EnumLikeBase<TItem>;\n\n/** Union of branded enum member values on an enum object `T`. */\nexport type SmartEnumMemberUnion<T extends Record<string, unknown>> = {\n [K in keyof T]: T[K] extends StandardEnumItem ? T[K] : never;\n}[keyof T];\n\n/** Keys on `TEnum` whose member matches `Record<P, V>` within `ItemUnion`. */\nexport type SmartEnumSubsetKeys<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = {\n [K in keyof TEnum]: TEnum[K] extends Extract<ItemUnion, Record<P, V>>\n ? K\n : never;\n}[keyof TEnum];\n\nexport type SmartEnumSubsetItemUnion<\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Extract<ItemUnion, Record<P, V>>;\n\nexport type SmartEnumSubsetView<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Pick<TEnum, SmartEnumSubsetKeys<TEnum, ItemUnion, P, V>> &\n CoreEnumMethods<SmartEnumSubsetItemUnion<ItemUnion, P, V>>;\n\nexport type FieldEnumMapping = Record<string, SmartEnumLike>;\n\nexport type ReviveRowOptions = {\n fieldEnumMapping: FieldEnumMapping;\n strict?: boolean;\n};\n\nexport type PathEnumMapping = Record<string, SmartEnumLike>;\n\nexport type RevivePayloadOptions = {\n pathEnumMapping: PathEnumMapping;\n strict?: boolean;\n};\n\nexport type EnumerationProps<TInput> = {\n input: TInput;\n propertyAutoFormatters?: PropertyAutoFormatter[];\n};\n\nexport type Enumeration<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\nexport type FinalizedEnumFields = Pick<\n StandardEnumItem,\n '__smart_enum_brand' | '__smart_enum_type'\n>;\nexport type FinalizableEnumItem = {\n key: string;\n value: string;\n display: string;\n index: number;\n deprecated?: boolean;\n};\n","import {\n SMART_ENUM_ITEM,\n SMART_ENUM,\n SmartEnumItemSerialized,\n} from '../types.js';\n\n/**\n * Runtime type guard to detect Smart Enum items created by this library.\n * Returns true if the value has the SMART_ENUM_ITEM symbol.\n *\n * @example\n * ```typescript\n * import { Status } from './status';\n * const item = Status.active;\n * isSmartEnumItem(item); // true\n * isSmartEnumItem({ key: 'active', value: 'ACTIVE' }); // false (plain object)\n * if (isSmartEnumItem(x)) {\n * console.log(x.value, x.__smart_enum_type); // narrowed to enum item\n * }\n * ```\n */\nexport const isSmartEnumItem = (\n x: unknown,\n): x is {\n key: string;\n value: string;\n index?: number;\n __smart_enum_type?: string;\n} => {\n return (\n !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM_ITEM) === true\n );\n};\n\n/**\n * Runtime type guard to detect a full Smart Enum object created by this library.\n * Returns true if the object has the SMART_ENUM property.\n *\n * @example\n * ```typescript\n * import { MyEnum } from './blah';\n * isSmartEnum(MyEnum) === true; // true\n * isSmartEnum(MyEnum.one) === false; // false (this is an item, not the enum)\n * ```\n */\nexport const isSmartEnum = (x: unknown): boolean => {\n return !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM) === true;\n};\n\n/**\n * Runtime type guard to detect a serialized Smart Enum item created by this library.\n * Returns true if the value has `__smart_enum_type` and `value` (wire/database shape).\n *\n * @example\n * ```typescript\n * const wire = { __smart_enum_type: 'Status', value: 'ACTIVE' };\n * isSerializedSmartEnumItem(wire); // true\n * isSerializedSmartEnumItem(Status.active); // false (live enum item)\n * if (isSerializedSmartEnumItem(x)) {\n * reviveItem(x.__smart_enum_type, x.value); // narrowed to SmartEnumItemSerialized\n * }\n * ```\n */\nexport const isSerializedSmartEnumItem = (\n x: unknown,\n): x is SmartEnumItemSerialized => {\n return (\n !!x &&\n typeof x === 'object' &&\n Reflect.has(x, '__smart_enum_type') &&\n Reflect.has(x, 'value')\n );\n};\n","/**\n * Logger interface for @reharik/smart-enum library\n *\n * This interface allows users to inject their own logging implementation\n * or use the default console logger.\n */\n\nexport type Logger = {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n};\n\n/**\n * Default console logger implementation\n */\nconst consoleLogger: Logger = {\n debug(message: string, ...args: unknown[]): void {\n console.debug(`[@reharik/smart-enum:debug] ${message}`, ...args);\n },\n\n info(message: string, ...args: unknown[]): void {\n console.info(`[@reharik/smart-enum:info] ${message}`, ...args);\n },\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`[@reharik/smart-enum:warn] ${message}`, ...args);\n },\n\n error(message: string, ...args: unknown[]): void {\n console.error(`[@reharik/smart-enum:error] ${message}`, ...args);\n },\n};\n\n/**\n * Global logger instance\n * Defaults to console logger\n */\nlet globalLogger: Logger = consoleLogger;\n\n/**\n * Sets the global logger instance\n *\n * @param logger - The logger implementation to use\n *\n * @example\n * ```typescript\n * import { setLogger } from '@reharik/smart-enum';\n *\n * // Use custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, args),\n * info: (msg, ...args) => myLogger.info(msg, args),\n * warn: (msg, ...args) => myLogger.warn(msg, args),\n * error: (msg, ...args) => myLogger.error(msg, args),\n * });\n * ```\n */\nexport function setLogger(logger: Logger): void {\n globalLogger = logger;\n}\n\n/**\n * Gets the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n return globalLogger;\n}\n\n// Internal convenience functions for library use\nexport function debug(message: string, ...args: unknown[]): void {\n globalLogger.debug(message, ...args);\n}\n\nexport function info(message: string, ...args: unknown[]): void {\n globalLogger.info(message, ...args);\n}\n\nexport function warn(message: string, ...args: unknown[]): void {\n globalLogger.warn(message, ...args);\n}\n\nexport function error(message: string, ...args: unknown[]): void {\n globalLogger.error(message, ...args);\n}\n","// serializeSmartEnums.ts\nexport { isSmartEnumItem, isSmartEnum } from './typeGuards.js';\nimport type { SerializedSmartEnums, AnyEnumLike } from '../types.js';\n\nimport { debug } from './logger.js';\nimport { isSerializedSmartEnumItem, isSmartEnumItem } from './typeGuards.js';\n\ntype PlainObject = Record<string, unknown>;\n\nconst isPlainObject = (x: unknown): x is PlainObject =>\n typeof x === 'object' &&\n x !== null &&\n Object.getPrototypeOf(x) === Object.prototype;\n\n/**\n * Recursively replaces Smart Enum items with self-describing objects\n * `{ __smart_enum_type, value }` for JSON transport or storage.\n *\n * @param input - Object or array that may contain enum items\n * @returns Same structure with enum items replaced by serialized shape\n *\n * @example\n * ```typescript\n * const dto = { id: '1', status: Status.active, color: Color.red };\n * const wire = serializeSmartEnums(dto);\n * // wire: { id: '1', status: { __smart_enum_type: 'Status', value: 'ACTIVE' }, color: { __smart_enum_type: 'Color', value: 'RED' } }\n * ```\n */\n// Overloads:\n// 1) Inferred\nexport function serializeSmartEnums<T>(input: T): SerializedSmartEnums<T>;\n// 2) Return-type only (constrained to objects/arrays)\nexport function serializeSmartEnums<\n S extends Readonly<PlainObject> | readonly unknown[],\n>(input: unknown): S;\n// Implementation\nexport function serializeSmartEnums(input: unknown): unknown {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n if (isSmartEnumItem(v)) {\n return {\n __smart_enum_type: v.__smart_enum_type,\n value: v.value,\n };\n }\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) {\n arr.push(walk(item));\n }\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n\n return walk(input);\n}\n\n/**\n * Recursively revives serialized enum objects back to Smart Enum items\n * using a registry of enum types. Expects payload to contain\n * `{ __smart_enum_type, value }` where the type exists in the registry.\n *\n * @param input - Serialized payload (e.g. from JSON)\n * @param registry - Map of enum type name to enum object (e.g. `{ Status, Color }`)\n * @returns Payload with serialized enums revived to enum items\n *\n * @example\n * ```typescript\n * const wire = { status: { __smart_enum_type: 'Status', value: 'ACTIVE' } };\n * const revived = reviveSmartEnums(wire, { Status, Color });\n * // revived.status === Status.active\n * ```\n */\nexport function reviveSmartEnums<R>(\n input: unknown,\n registry: Record<string, AnyEnumLike>,\n): R {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n // Handle self-describing enum objects with __smart_enum_type and value\n if (isSerializedSmartEnumItem(v)) {\n debug(`Found serialized smartEnum: ${v.__smart_enum_type}`);\n const enumInstance = registry[v.__smart_enum_type];\n if (enumInstance) {\n debug(`Found enumInstance in registry: ${v.__smart_enum_type}`);\n // Try to find the enum item by value first\n const enumItem = enumInstance.tryFromValue(v.value);\n if (enumItem) {\n debug(`Revived enumItem using value: ${v.value}`);\n return enumItem;\n }\n // If that fails, try to find by key (convert value to key format)\n const key = v.value.toLowerCase();\n const enumItemFromKey = enumInstance.tryFromKey(key);\n if (enumItemFromKey) {\n debug(`Revived enumItem using key: ${key}`);\n return enumItemFromKey;\n }\n }\n // If no matching enum type in registry, return the original serialized object\n return v;\n }\n\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) arr.push(walk(item));\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n return walk(input) as R;\n}\n\n/**\n * Maps a plain string (for example a column value from a database query) to the\n * corresponding Smart Enum item by calling `tryFromValue` on the given enum.\n *\n * Use this when you already know which enum type a field uses and the stored\n * value is the enum’s wire `value` string (same shape `tryFromValue` expects).\n *\n * @param value - Raw value; only strings are resolved—anything else returns `undefined`\n * @param smartEnum - Smart enum instance (`AnyEnumLike<TItem>`; same shape as registry entries)\n * @param strict - When `true`, throws if the string does not match any member; when `false`, returns `undefined`\n * @returns The matching enum item, or `undefined` if not found (non-string input always yields `undefined`)\n *\n * @example\n * ```typescript\n * const item = reviveEnumField(row.status, UserStatus);\n * const mustMatch = reviveEnumField(row.code, OrderStatus, true);\n * ```\n */\nexport const reviveEnumField = <TItem>(\n value: unknown,\n smartEnum: AnyEnumLike<TItem>,\n strict = false,\n): TItem | undefined => {\n if (typeof value !== 'string') return undefined;\n\n const revived = smartEnum.tryFromValue(value);\n if (revived !== undefined) return revived;\n\n if (strict) {\n throw new Error(`Unknown enum value: ${JSON.stringify(value)}`);\n }\n\n return undefined;\n};\n","import type {\n AnyEnumLike,\n LogLevel,\n SmartEnumMappingsConfig,\n} from '../../types.js';\nimport { info, setLogger, getLogger, type Logger } from '../logger.js';\n\nconst createLevelFilteredLogger = (logger: Logger, level: LogLevel): Logger => {\n const levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n const currentLevel = levels[level];\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.debug) {\n logger.debug(message, ...args);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.info) {\n logger.info(message, ...args);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.warn) {\n logger.warn(message, ...args);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.error) {\n logger.error(message, ...args);\n }\n },\n };\n};\n\nlet globalEnumRegistry: Record<string, AnyEnumLike> | undefined;\n\n/**\n * Wire-format registry for `reviveAfterTransport` / `reviveSmartEnums`.\n * Not used for database string revival.\n */\nexport const initializeSmartEnumMappings = (\n config: SmartEnumMappingsConfig,\n): void => {\n globalEnumRegistry = config.enumRegistry;\n\n const logLevel = config.logLevel ?? 'error';\n const logger = config.logger ?? getLogger();\n setLogger(createLevelFilteredLogger(logger, logLevel));\n\n info('Initialized smart enum mappings', {\n enumCount: Object.keys(config.enumRegistry).length,\n enumTypes: Object.keys(config.enumRegistry),\n logLevel,\n });\n};\n\nexport const getGlobalEnumRegistry = ():\n | Record<string, AnyEnumLike>\n | undefined => globalEnumRegistry;\n","import { reviveSmartEnums } from '../transformation.js';\n\nimport { getGlobalEnumRegistry } from './transportRegistry.js';\n\n/**\n * Revives smart enums after transport. Requires `initializeSmartEnumMappings`.\n */\nexport const reviveAfterTransport = <T>(payload: unknown): T => {\n const registry = getGlobalEnumRegistry();\n if (!registry) {\n return payload as T;\n }\n return reviveSmartEnums(payload, registry);\n};\n","import { serializeSmartEnums } from '../transformation.js';\nimport type { SerializedSmartEnums } from '../../types.js';\n\n/**\n * Serializes smart enums for transport (to client or API).\n * Wire payloads include `__smart_enum_type` for `re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IAC5C,WAAW,OAAO,KAAK,OAAO,YAAY;AAAA,IAC1C;AAAA,EACF,CAAC;AACH;AAEO,IAAM,wBAAwB,MAEpB;;;AC1DV,IAAM,uBAAuB,CAAI,YAAwB;AAC9D,QAAM,WAAW,sBAAsB;AACvC,MAAI,CAAC,UAAU;AACb,WAAO;AAAA,EACT;AACA,SAAO,iBAAiB,SAAS,QAAQ;AAC3C;;;ACNO,IAAM,wBAAwB,CAAI,YACvC,oBAAoB,OAAO;","names":[]}
1
+ {"version":3,"sources":["../src/transport.ts","../src/enumerations.ts","../src/extensionMethods.ts","../src/types.ts","../src/utilities/serializationMode.ts","../src/utilities/typeGuards.ts","../src/utilities/logger.ts","../src/utilities/transformation.ts","../src/utilities/transport/transportRegistry.ts","../src/utilities/transport/reviveAfterTransport.ts","../src/utilities/transport/serializeForTransport.ts"],"sourcesContent":["/**\n * Smart Enums with Transport Utilities\n *\n * This entry point includes the core enumeration functionality plus utilities\n * for serializing/reviving enums for API transport (JSON over the wire).\n *\n * @example\n * ```typescript\n * import { enumeration, serializeForTransport, reviveAfterTransport } from '@reharik/smart-enum/transport';\n * ```\n */\n\n// Re-export core functionality\nexport { enumeration } from './enumerations.js';\nexport { isSmartEnumItem, isSmartEnum } from './utilities/typeGuards.js';\nexport {\n serializeSmartEnums,\n reviveSmartEnums,\n reviveEnumField,\n} from './utilities/transformation.js';\nexport {\n reviveAfterTransport,\n serializeForTransport,\n initializeSmartEnumMappings,\n getGlobalEnumRegistry,\n} from './utilities/transport/index.js';\n\n// Re-export core types plus transport-specific types\nexport type {\n Enumeration,\n AnyEnumLike,\n SerializedSmartEnums,\n RevivedSmartEnums,\n SmartEnumItemSerialized,\n LogLevel,\n SmartEnumMappingsConfig,\n StandardEnumItemBase,\n StandardEnumItem,\n} from './types.js';\n","import { capitalCase, constantCase } from 'case-anything';\n\nimport { addExtensionMethods } from './extensionMethods.js';\nimport {\n SMART_ENUM,\n SMART_ENUM_ID,\n SMART_ENUM_ITEM,\n SerializationMode,\n type EnumFromNormalizedObject,\n type EnumItemFromNormalizedObject,\n type EnumMemberUnionFromNormalizedObject,\n type EnumerationProps,\n type FinalizableEnumItem,\n type FinalizedEnumFields,\n type NormalizedInputType,\n type ObjectEnumInput,\n type PropertyAutoFormatter,\n} from './types.js';\nimport { resolveSerializationMode } from './utilities/serializationMode.js';\n\nexport type EnumItem<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends { __smart_enum_brand: true }\n ? TEnum[K]\n : never;\n}[keyof TEnum];\n\nfunction normalizeInput<TInput extends readonly string[] | ObjectEnumInput>(\n input: TInput,\n): NormalizedInputType<TInput> {\n if (Array.isArray(input)) {\n return Object.fromEntries(\n input.map(k => [k, {}]),\n ) as NormalizedInputType<TInput>;\n }\n\n return input as NormalizedInputType<TInput>;\n}\n\nconst finalizeEnumItem = <T extends { value: string }>(\n item: T,\n enumType: string,\n enumInstanceId: symbol,\n serializeAs: SerializationMode | undefined,\n): T & FinalizedEnumFields => {\n Object.defineProperty(item, SMART_ENUM_ITEM, {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, SMART_ENUM_ID, {\n value: enumInstanceId,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_brand', {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_type', {\n value: enumType,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toJSON', {\n value: () => {\n const mode = resolveSerializationMode(serializeAs);\n if (mode === 'value') {\n return item.value;\n }\n return { __smart_enum_type: enumType, value: item.value };\n },\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toPostgres', {\n value: () => item.value,\n enumerable: false,\n });\n\n return item as T & FinalizedEnumFields;\n};\n\nconst formatProperties = (\n k: string,\n formatters: PropertyAutoFormatter[],\n): { value: string; display: string } & Record<string, string> =>\n formatters.reduce(\n (acc, formatter) => {\n acc[formatter.key] = formatter.format(k);\n return acc;\n },\n {\n value: constantCase(k),\n display: capitalCase(k),\n } as { value: string; display: string } & Record<string, string>,\n );\n\nfunction buildEnumFromObject<TObj extends ObjectEnumInput>(\n enumType: string,\n input: TObj,\n propertyAutoFormatters?: PropertyAutoFormatter[],\n serializeAs?: SerializationMode,\n): EnumFromNormalizedObject<TObj> {\n const formattersWithDefaults: PropertyAutoFormatter[] = [\n { key: 'value', format: constantCase },\n { key: 'display', format: capitalCase },\n ...(propertyAutoFormatters ?? []),\n ];\n\n type TItem = EnumMemberUnionFromNormalizedObject<TObj>;\n\n const rawEnumItems: Partial<{\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }> = {};\n\n const enumInstanceId = Symbol('smart-enum-instance');\n let index = 0;\n\n for (const key in input) {\n if (Object.prototype.hasOwnProperty.call(input, key)) {\n const typedKey = key;\n const value = input[typedKey];\n\n const enumItemBase = {\n index,\n key: typedKey,\n ...formatProperties(typedKey, formattersWithDefaults),\n ...value,\n } as FinalizableEnumItem & TObj[typeof typedKey];\n\n const enumItem = finalizeEnumItem(\n enumItemBase,\n enumType,\n enumInstanceId,\n serializeAs,\n ) as unknown as TItem;\n\n Object.freeze(enumItem);\n rawEnumItems[typedKey as keyof TObj] = enumItem;\n index++;\n }\n }\n\n const extensionMethods = addExtensionMethods<TItem>(\n Object.values(rawEnumItems) as TItem[],\n );\n\n const enumObject = {\n ...rawEnumItems,\n ...extensionMethods,\n } as EnumFromNormalizedObject<TObj>;\n\n Object.defineProperty(enumObject, SMART_ENUM, {\n value: true,\n enumerable: false,\n });\n\n Object.freeze(enumObject);\n\n return enumObject;\n}\n\nexport function enumeration<const TArr extends readonly string[]>(\n enumType: string,\n props: EnumerationProps<TArr>,\n): EnumFromNormalizedObject<NormalizedInputType<TArr>>;\n\nexport function enumeration<const TObj extends ObjectEnumInput>(\n enumType: string,\n props: EnumerationProps<TObj>,\n): EnumFromNormalizedObject<NormalizedInputType<TObj>>;\n\nexport function enumeration(\n enumType: string,\n props: EnumerationProps<readonly string[] | ObjectEnumInput>,\n) {\n const normalized = normalizeInput(props.input);\n return buildEnumFromObject(\n enumType,\n normalized,\n props.propertyAutoFormatters,\n props.serializeAs,\n );\n}\n","import type { CoreEnumMethods, StandardEnumItem } from './types.js';\nexport const addExtensionMethods = <TItem extends StandardEnumItem>(\n enumItems: readonly TItem[],\n): CoreEnumMethods<TItem> => {\n const findBy = <K extends keyof TItem>(field: K, target: TItem[K]) =>\n enumItems.find(item => item[field] === target);\n\n const requireBy = <K extends keyof TItem>(\n field: K,\n target: TItem[K],\n label: string,\n ) => {\n const item = findBy(field, target);\n if (!item) {\n throw new Error(`No enum ${label} found for '${String(target)}'`);\n }\n return item;\n };\n\n return {\n fromValue: value => requireBy('value', value as TItem['value'], 'value'),\n tryFromValue: value =>\n value ? findBy('value', value as TItem['value']) : undefined,\n\n fromKey: key => requireBy('key', key as TItem['key'], 'key'),\n tryFromKey: key => (key ? findBy('key', key as TItem['key']) : undefined),\n\n items: () => [...enumItems],\n values: () => enumItems.map(item => item.value),\n keys: () => enumItems.map(item => item.key),\n };\n};\n","/**\n * Type guard to check if a value is not null or undefined\n * @param value - The value to check\n * @returns True if the value is defined and not null\n */\nexport const notEmpty = <X>(\n value: X | null | undefined,\n): value is NonNullable<X> => {\n // eslint-disable-next-line unicorn/no-null\n return value != null;\n};\n\n// Public symbols used at runtime for detection/identity (not used in type keys)\nexport const SMART_ENUM_ITEM = Symbol('smart-enum-item');\nexport const SMART_ENUM_ID = Symbol('smart-enum-id');\nexport const SMART_ENUM = Symbol('smart-enum');\n\n/**\n * Options for filtering enum items in various methods\n */\nexport type EnumFilterOptions = {\n /** Include items with null/undefined values (default: false) */\n showEmpty?: boolean;\n /** Include deprecated items (default: false) */\n showDeprecated?: boolean;\n};\n\n// export type EnumInput = readonly string[] | ObjectEnumInput;\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Structural detection checks for\n * presence of `key` and `value`.\n */\nexport type SerializedSmartEnums<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<SerializedSmartEnums<U>>\n : T extends Array<infer U>\n ? SerializedSmartEnums<U>[]\n : T extends object\n ? { [K in keyof T]: SerializedSmartEnums<T[K]> }\n : T;\n\n/**\n * Revived shape: for keys present in mapping M, the string becomes the\n * corresponding enum item type (derived from the provided enum object);\n * other fields recurse.\n */\nexport type EnumItemFromEnum<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\n/**\n * Structural constraint for smart enum instances (registry entries, `reviveSmartEnums`, etc.).\n * `T` is the enum item type returned by `tryFromValue` / `tryFromKey` (default `unknown` when heterogeneous).\n */\nexport type AnyEnumLike<T = unknown> = {\n tryFromValue: (value?: string | null) => T | undefined;\n tryFromKey: (key?: string | null) => T | undefined;\n} & Record<string, unknown>;\n\nexport type RevivedSmartEnums<T, M extends Record<string, AnyEnumLike>> =\n T extends ReadonlyArray<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends Array<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends object\n ? {\n [K in keyof T]: K extends Extract<keyof M, string>\n ? Enumeration<M[K]>\n : RevivedSmartEnums<T[K], M>;\n }\n : T;\n\nexport type SmartEnumItemSerialized = {\n __smart_enum_type: string;\n value: string;\n};\n\n/** Example shape for transport tests (`reviveAfterTransport` registry). */\nexport type SmartApiHelperConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n};\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Used for database storage.\n */\nexport type DatabaseFormat<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DatabaseFormat<U>>\n : T extends Array<infer U>\n ? DatabaseFormat<U>[]\n : T extends object\n ? { [K in keyof T]: DatabaseFormat<T[K]> }\n : T;\n\n/**\n * Log levels for smart enum mappings\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Configuration for smart enum mappings initialization\n */\nexport type SmartEnumMappingsConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n logLevel?: LogLevel;\n logger?: import('./utilities/logger.js').Logger;\n};\n\ntype BuiltInOverrideKeys =\n | 'key'\n | 'value'\n | 'display'\n | 'deprecated'\n | 'index'\n | '__smart_enum_brand'\n | '__smart_enum_type';\n\n/**\n * Structural fields shared by every enum member (key, value, display, index, optional deprecated).\n * Does not include smart-enum branding or database helpers; see {@link StandardEnumItem}.\n */\nexport type StandardEnumItemBase = {\n readonly key: string;\n readonly value: string;\n readonly display: string;\n readonly index: number;\n readonly deprecated?: boolean;\n};\n\n/**\n * Branded item produced by `enumeration()`: {@link StandardEnumItemBase} plus runtime identity\n * (`__smart_enum_brand`, `__smart_enum_type`) and `toPostgres()`.\n */\nexport type StandardEnumItem = StandardEnumItemBase & {\n readonly __smart_enum_brand: true;\n readonly __smart_enum_type: string;\n readonly toPostgres: () => string;\n readonly toJSON: () => string | { __smart_enum_type: string; value: string };\n};\n\nexport type EnumInputItem = Partial<{\n key: string;\n value: string;\n display: string;\n deprecated: boolean;\n}> &\n Record<string, unknown>;\n\nexport type ObjectEnumInput = Record<string, EnumInputItem>;\n\nexport type EmptyEnumInputItem = Record<never, never>;\n\ntype Separator = '-' | '_' | ' ' | '.';\n\ntype IsUpperChar<C extends string> =\n C extends Uppercase<C> ? (C extends Lowercase<C> ? false : true) : false;\n\ntype IsLowerChar<C extends string> =\n C extends Lowercase<C> ? (C extends Uppercase<C> ? false : true) : false;\n\ntype PushUnderscore<S extends string> = S extends '' | `${string}_`\n ? S\n : `${S}_`;\n\ntype TrimUnderscore<S extends string> = S extends `_${infer R}`\n ? TrimUnderscore<R>\n : S extends `${infer R}_`\n ? TrimUnderscore<R>\n : S;\n\ntype CollapseUnderscores<S extends string> = S extends `${infer A}__${infer B}`\n ? CollapseUnderscores<`${A}_${B}`>\n : S;\n\ntype ConstantCaseInternal<\n S extends string,\n Prev extends string = '',\n Out extends string = '',\n> = S extends `${infer C}${infer Rest}`\n ? C extends Separator\n ? ConstantCaseInternal<Rest, C, PushUnderscore<Out>>\n : IsUpperChar<C> extends true\n ? IsLowerChar<Prev> extends true\n ? ConstantCaseInternal<Rest, C, `${PushUnderscore<Out>}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : CollapseUnderscores<TrimUnderscore<Out>>;\n\ntype ConstantCase<S extends string> = string extends S\n ? string\n : ConstantCaseInternal<S>;\n\n/** Segments of a `ConstantCase` string (underscore-separated ALL CAPS words). */\ntype SplitConstantCaseSegments<S extends string> =\n S extends `${infer A}_${infer B}`\n ? [A, ...SplitConstantCaseSegments<B>]\n : [S];\n\n/** First character upper, remainder lower (for ALL-CAPS words from `ConstantCase`). */\ntype TitleCaseAllCapsWord<W extends string> = W extends ''\n ? ''\n : W extends `${infer F}${infer R}`\n ? `${Uppercase<F>}${Lowercase<R>}`\n : W;\n\ntype JoinDisplaySegments<T extends readonly string[]> = T extends readonly [\n infer A extends string,\n ...infer Rest extends readonly string[],\n]\n ? Rest extends readonly []\n ? TitleCaseAllCapsWord<A>\n : `${TitleCaseAllCapsWord<A>} ${JoinDisplaySegments<Rest>}`\n : '';\n\n/**\n * Display string derived from the enum member key: `ConstantCase` → split → title-case words → join with spaces.\n * Matches default runtime `capitalCase(key)` for typical PascalCase / camelCase keys. Member keys that already\n * contain separators may differ from `capitalCase` at runtime; custom `propertyAutoFormatters` for `display`\n * are not reflected in this type.\n */\ntype DisplayCaseFromEnumKey<K extends string> = string extends K\n ? string\n : JoinDisplaySegments<SplitConstantCaseSegments<ConstantCase<K>>>;\n\nexport type ArrayToObjectType<T extends readonly string[]> = {\n [K in T[number]]: EmptyEnumInputItem & { readonly value?: ConstantCase<K> };\n};\n\nexport type NormalizedInputType<TInput> = TInput extends readonly string[]\n ? ArrayToObjectType<TInput>\n : TInput extends ObjectEnumInput\n ? TInput\n : never;\n\n/** Input-derived fields for one member key (excludes built-ins filled by `enumeration()`). */\nexport type EnumMemberExtra<\n TObj extends ObjectEnumInput,\n K extends keyof TObj,\n> = Omit<TObj[K], BuiltInOverrideKeys>;\n\nexport type EnumItemFromNormalizedObject<\n TObj extends ObjectEnumInput,\n K extends keyof TObj = keyof TObj,\n> = Omit<StandardEnumItem, 'key' | 'value' | 'display'> &\n EnumMemberExtra<TObj, K> & {\n readonly key: Extract<K, string>;\n readonly value: TObj[K] extends { value?: infer V }\n ? [Extract<V, string>] extends [never]\n ? ConstantCase<Extract<K, string>>\n : Extract<V, string>\n : ConstantCase<Extract<K, string>>;\n readonly display: TObj[K] extends { display?: infer D }\n ? [Extract<D, string>] extends [never]\n ? DisplayCaseFromEnumKey<Extract<K, string>>\n : Extract<D, string>\n : DisplayCaseFromEnumKey<Extract<K, string>>;\n };\n\nexport type EnumMemberUnionFromNormalizedObject<TObj extends ObjectEnumInput> =\n {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }[keyof TObj];\n\nexport type EnumFromNormalizedObject<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n} & CoreEnumMethods<EnumMemberUnionFromNormalizedObject<TObj>>;\n\nexport type UnionKeys<T> = T extends T ? keyof T : never;\n\n/*\nTo widen the type of the OptionalObject from literals to their actual types,\ne.g.\nshape?: \"round\" | \"square\" | \"long\";\nslices?: true;\nlayers?: 2;\n--turns into:--\nshape: string | undefined;\nslices: boolean| undefined;\nlayers: number| undefined;\n\nwe can use the following code:\ntype Widen<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T;\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? Widen<V> : undefined;\n};\n*/\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? V : undefined;\n};\n\ntype ExtraShapeUnion<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: Omit<TObj[K], BuiltInOverrideKeys>;\n}[keyof TObj];\n\nexport type InferredExtraFields<TObj extends ObjectEnumInput> =\n MergeUnionToObject<ExtraShapeUnion<TObj>>;\n\nexport type PropertyAutoFormatter = {\n /** The property name to generate */\n key: string;\n /** Function to transform the key into the property value */\n format: (k: string) => string;\n};\n\nexport type CoreEnumMethods<TItem extends StandardEnumItem> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n items(): readonly TItem[];\n /** Matches runtime: `items.map(i => i.value)` (see {@link EnumLikeBase}). */\n values(): readonly TItem['value'][];\n /** Matches runtime: `items.map(i => i.key)` (see {@link EnumLikeBase}). */\n keys(): readonly TItem['key'][];\n};\n\n/**\n * Structural shape of a smart-style enum object: lookup by value/key, list items/values/keys,\n * plus an index signature so registry and mapping types can treat instances as records.\n * Use {@link SmartEnumLike} when items are full {@link StandardEnumItem}s (the usual case).\n */\nexport type EnumLikeBase<\n TItem extends StandardEnumItemBase = StandardEnumItemBase,\n> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n items(): readonly TItem[];\n values(): readonly TItem['value'][];\n keys(): readonly TItem['key'][];\n} & Record<string, unknown>;\n\n/**\n * A {@link EnumLikeBase} whose items are branded {@link StandardEnumItem}s (typical `enumeration()` result).\n */\nexport type SmartEnumLike<TItem extends StandardEnumItem = StandardEnumItem> =\n EnumLikeBase<TItem>;\n\n/** Union of branded enum member values on an enum object `T`. */\nexport type SmartEnumMemberUnion<T extends Record<string, unknown>> = {\n [K in keyof T]: T[K] extends StandardEnumItem ? T[K] : never;\n}[keyof T];\n\n/** Keys on `TEnum` whose member matches `Record<P, V>` within `ItemUnion`. */\nexport type SmartEnumSubsetKeys<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = {\n [K in keyof TEnum]: TEnum[K] extends Extract<ItemUnion, Record<P, V>>\n ? K\n : never;\n}[keyof TEnum];\n\nexport type SmartEnumSubsetItemUnion<\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Extract<ItemUnion, Record<P, V>>;\n\nexport type SmartEnumSubsetView<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Pick<TEnum, SmartEnumSubsetKeys<TEnum, ItemUnion, P, V>> &\n CoreEnumMethods<SmartEnumSubsetItemUnion<ItemUnion, P, V>>;\n\nexport type FieldEnumMapping = Record<string, SmartEnumLike>;\n\nexport type ReviveRowOptions = {\n fieldEnumMapping: FieldEnumMapping;\n strict?: boolean;\n};\n\nexport type PathEnumMapping = Record<string, SmartEnumLike>;\n\nexport type RevivePayloadOptions = {\n pathEnumMapping: PathEnumMapping;\n strict?: boolean;\n};\n\n/**\n * Serialization mode controls how smart-enum items are serialized to JSON.\n *\n * - 'wrapped' (default): toJSON returns { __smart_enum_type, value }.\n * Use this when payloads need to be self-describing for revival on the\n * receiving end (e.g. REST APIs with explicit revive middleware).\n *\n * - 'value': toJSON returns just the wire value string.\n * Use this when the receiving end already knows the enum types from\n * schema context (e.g. GraphQL boundaries).\n *\n * Resolution order at toJSON call time:\n * 1. Per-enum `serializeAs` option (if set on enumeration())\n * 2. Global default (set via setDefaultSerializationMode)\n * 3. 'wrapped' (built-in default, preserves backward compatibility)\n */\nexport type SerializationMode = 'wrapped' | 'value';\n\nexport type EnumerationProps<TInput> = {\n input: TInput;\n propertyAutoFormatters?: PropertyAutoFormatter[];\n serializeAs?: SerializationMode;\n};\n\nexport type Enumeration<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\nexport type FinalizedEnumFields = Pick<\n StandardEnumItem,\n '__smart_enum_brand' | '__smart_enum_type' | 'toJSON'\n>;\nexport type FinalizableEnumItem = {\n key: string;\n value: string;\n display: string;\n index: number;\n deprecated?: boolean;\n};\n","import { SerializationMode } from '../types.js';\n\nlet globalDefault: SerializationMode | undefined;\n\n/**\n * Set the global default serialization mode for all smart-enum items\n * that don't have a per-enum serializeAs option.\n *\n * Call once at app startup, before any JSON.stringify happens on enum items.\n *\n * @example\n * setDefaultSerializationMode('value');\n */\nexport const setDefaultSerializationMode = (mode: SerializationMode): void => {\n globalDefault = mode;\n};\n\n/**\n * Reset the global default to its initial unset state.\n * Primarily useful for tests.\n */\nexport const resetDefaultSerializationMode = (): void => {\n globalDefault = undefined;\n};\n\n/**\n * Resolve the effective serialization mode for an enum item.\n * Per-enum option wins, then global, then 'wrapped'.\n */\nexport const resolveSerializationMode = (\n perEnum: SerializationMode | undefined,\n): SerializationMode => perEnum ?? globalDefault ?? 'wrapped';\n","import {\n SMART_ENUM_ITEM,\n SMART_ENUM,\n SmartEnumItemSerialized,\n} from '../types.js';\n\n/**\n * Runtime type guard to detect Smart Enum items created by this library.\n * Returns true if the value has the SMART_ENUM_ITEM symbol.\n *\n * @example\n * ```typescript\n * import { Status } from './status';\n * const item = Status.active;\n * isSmartEnumItem(item); // true\n * isSmartEnumItem({ key: 'active', value: 'ACTIVE' }); // false (plain object)\n * if (isSmartEnumItem(x)) {\n * console.log(x.value, x.__smart_enum_type); // narrowed to enum item\n * }\n * ```\n */\nexport const isSmartEnumItem = (\n x: unknown,\n): x is {\n key: string;\n value: string;\n index?: number;\n __smart_enum_type?: string;\n} => {\n return (\n !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM_ITEM) === true\n );\n};\n\n/**\n * Runtime type guard to detect a full Smart Enum object created by this library.\n * Returns true if the object has the SMART_ENUM property.\n *\n * @example\n * ```typescript\n * import { MyEnum } from './blah';\n * isSmartEnum(MyEnum) === true; // true\n * isSmartEnum(MyEnum.one) === false; // false (this is an item, not the enum)\n * ```\n */\nexport const isSmartEnum = (x: unknown): boolean => {\n return !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM) === true;\n};\n\n/**\n * Runtime type guard to detect a serialized Smart Enum item created by this library.\n * Returns true if the value has `__smart_enum_type` and `value` (wire/database shape).\n *\n * @example\n * ```typescript\n * const wire = { __smart_enum_type: 'Status', value: 'ACTIVE' };\n * isSerializedSmartEnumItem(wire); // true\n * isSerializedSmartEnumItem(Status.active); // false (live enum item)\n * if (isSerializedSmartEnumItem(x)) {\n * reviveItem(x.__smart_enum_type, x.value); // narrowed to SmartEnumItemSerialized\n * }\n * ```\n */\nexport const isSerializedSmartEnumItem = (\n x: unknown,\n): x is SmartEnumItemSerialized => {\n return (\n !!x &&\n typeof x === 'object' &&\n Reflect.has(x, '__smart_enum_type') &&\n Reflect.has(x, 'value')\n );\n};\n","/**\n * Logger interface for @reharik/smart-enum library\n *\n * This interface allows users to inject their own logging implementation\n * or use the default console logger.\n */\n\nexport type Logger = {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n};\n\n/**\n * Default console logger implementation\n */\nconst consoleLogger: Logger = {\n debug(message: string, ...args: unknown[]): void {\n console.debug(`[@reharik/smart-enum:debug] ${message}`, ...args);\n },\n\n info(message: string, ...args: unknown[]): void {\n console.info(`[@reharik/smart-enum:info] ${message}`, ...args);\n },\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`[@reharik/smart-enum:warn] ${message}`, ...args);\n },\n\n error(message: string, ...args: unknown[]): void {\n console.error(`[@reharik/smart-enum:error] ${message}`, ...args);\n },\n};\n\n/**\n * Global logger instance\n * Defaults to console logger\n */\nlet globalLogger: Logger = consoleLogger;\n\n/**\n * Sets the global logger instance\n *\n * @param logger - The logger implementation to use\n *\n * @example\n * ```typescript\n * import { setLogger } from '@reharik/smart-enum';\n *\n * // Use custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, args),\n * info: (msg, ...args) => myLogger.info(msg, args),\n * warn: (msg, ...args) => myLogger.warn(msg, args),\n * error: (msg, ...args) => myLogger.error(msg, args),\n * });\n * ```\n */\nexport function setLogger(logger: Logger): void {\n globalLogger = logger;\n}\n\n/**\n * Gets the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n return globalLogger;\n}\n\n// Internal convenience functions for library use\nexport function debug(message: string, ...args: unknown[]): void {\n globalLogger.debug(message, ...args);\n}\n\nexport function info(message: string, ...args: unknown[]): void {\n globalLogger.info(message, ...args);\n}\n\nexport function warn(message: string, ...args: unknown[]): void {\n globalLogger.warn(message, ...args);\n}\n\nexport function error(message: string, ...args: unknown[]): void {\n globalLogger.error(message, ...args);\n}\n","// serializeSmartEnums.ts\nexport { isSmartEnumItem, isSmartEnum } from './typeGuards.js';\nimport type { SerializedSmartEnums, AnyEnumLike } from '../types.js';\n\nimport { debug } from './logger.js';\nimport { isSerializedSmartEnumItem, isSmartEnumItem } from './typeGuards.js';\n\ntype PlainObject = Record<string, unknown>;\n\nconst isPlainObject = (x: unknown): x is PlainObject =>\n typeof x === 'object' &&\n x !== null &&\n Object.getPrototypeOf(x) === Object.prototype;\n\n/**\n * Recursively replaces Smart Enum items with self-describing objects\n * `{ __smart_enum_type, value }` for JSON transport or storage.\n *\n * @param input - Object or array that may contain enum items\n * @returns Same structure with enum items replaced by serialized shape\n *\n * @example\n * ```typescript\n * const dto = { id: '1', status: Status.active, color: Color.red };\n * const wire = serializeSmartEnums(dto);\n * // wire: { id: '1', status: { __smart_enum_type: 'Status', value: 'ACTIVE' }, color: { __smart_enum_type: 'Color', value: 'RED' } }\n * ```\n */\n// Overloads:\n// 1) Inferred\nexport function serializeSmartEnums<T>(input: T): SerializedSmartEnums<T>;\n// 2) Return-type only (constrained to objects/arrays)\nexport function serializeSmartEnums<\n S extends Readonly<PlainObject> | readonly unknown[],\n>(input: unknown): S;\n// Implementation\nexport function serializeSmartEnums(input: unknown): unknown {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n if (isSmartEnumItem(v)) {\n return {\n __smart_enum_type: v.__smart_enum_type,\n value: v.value,\n };\n }\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) {\n arr.push(walk(item));\n }\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n\n return walk(input);\n}\n\n/**\n * Recursively revives serialized enum objects back to Smart Enum items\n * using a registry of enum types. Expects payload to contain\n * `{ __smart_enum_type, value }` where the type exists in the registry.\n *\n * @param input - Serialized payload (e.g. from JSON)\n * @param registry - Map of enum type name to enum object (e.g. `{ Status, Color }`)\n * @returns Payload with serialized enums revived to enum items\n *\n * @example\n * ```typescript\n * const wire = { status: { __smart_enum_type: 'Status', value: 'ACTIVE' } };\n * const revived = reviveSmartEnums(wire, { Status, Color });\n * // revived.status === Status.active\n * ```\n */\nexport function reviveSmartEnums<R>(\n input: unknown,\n registry: Record<string, AnyEnumLike>,\n): R {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n // Handle self-describing enum objects with __smart_enum_type and value\n if (isSerializedSmartEnumItem(v)) {\n debug(`Found serialized smartEnum: ${v.__smart_enum_type}`);\n const enumInstance = registry[v.__smart_enum_type];\n if (enumInstance) {\n debug(`Found enumInstance in registry: ${v.__smart_enum_type}`);\n // Try to find the enum item by value first\n const enumItem = enumInstance.tryFromValue(v.value);\n if (enumItem) {\n debug(`Revived enumItem using value: ${v.value}`);\n return enumItem;\n }\n // If that fails, try to find by key (convert value to key format)\n const key = v.value.toLowerCase();\n const enumItemFromKey = enumInstance.tryFromKey(key);\n if (enumItemFromKey) {\n debug(`Revived enumItem using key: ${key}`);\n return enumItemFromKey;\n }\n }\n // If no matching enum type in registry, return the original serialized object\n return v;\n }\n\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) arr.push(walk(item));\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n return walk(input) as R;\n}\n\n/**\n * Maps a plain string (for example a column value from a database query) to the\n * corresponding Smart Enum item by calling `tryFromValue` on the given enum.\n *\n * Use this when you already know which enum type a field uses and the stored\n * value is the enum’s wire `value` string (same shape `tryFromValue` expects).\n *\n * @param value - Raw value; only strings are resolved—anything else returns `undefined`\n * @param smartEnum - Smart enum instance (`AnyEnumLike<TItem>`; same shape as registry entries)\n * @param strict - When `true`, throws if the string does not match any member; when `false`, returns `undefined`\n * @returns The matching enum item, or `undefined` if not found (non-string input always yields `undefined`)\n *\n * @example\n * ```typescript\n * const item = reviveEnumField(row.status, UserStatus);\n * const mustMatch = reviveEnumField(row.code, OrderStatus, true);\n * ```\n */\nexport const reviveEnumField = <TItem>(\n value: unknown,\n smartEnum: AnyEnumLike<TItem>,\n strict = false,\n): TItem | undefined => {\n if (typeof value !== 'string') return undefined;\n\n const revived = smartEnum.tryFromValue(value);\n if (revived !== undefined) return revived;\n\n if (strict) {\n throw new Error(`Unknown enum value: ${JSON.stringify(value)}`);\n }\n\n return undefined;\n};\n","import type {\n AnyEnumLike,\n LogLevel,\n SmartEnumMappingsConfig,\n} from '../../types.js';\nimport { info, setLogger, getLogger, type Logger } from '../logger.js';\n\nconst createLevelFilteredLogger = (logger: Logger, level: LogLevel): Logger => {\n const levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n };\n\n const currentLevel = levels[level];\n\n return {\n debug: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.debug) {\n logger.debug(message, ...args);\n }\n },\n info: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.info) {\n logger.info(message, ...args);\n }\n },\n warn: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.warn) {\n logger.warn(message, ...args);\n }\n },\n error: (message: string, ...args: unknown[]) => {\n if (currentLevel <= levels.error) {\n logger.error(message, ...args);\n }\n },\n };\n};\n\nlet globalEnumRegistry: Record<string, AnyEnumLike> | undefined;\n\n/**\n * Wire-format registry for `reviveAfterTransport` / `reviveSmartEnums`.\n * Not used for database string revival.\n */\nexport const initializeSmartEnumMappings = (\n config: SmartEnumMappingsConfig,\n): void => {\n globalEnumRegistry = config.enumRegistry;\n\n const logLevel = config.logLevel ?? 'error';\n const logger = config.logger ?? getLogger();\n setLogger(createLevelFilteredLogger(logger, logLevel));\n\n info('Initialized smart enum mappings', {\n enumCount: Object.keys(config.enumRegistry).length,\n enumTypes: Object.keys(config.enumRegistry),\n logLevel,\n });\n};\n\nexport const getGlobalEnumRegistry = ():\n | Record<string, AnyEnumLike>\n | undefined => globalEnumRegistry;\n","import { reviveSmartEnums } from '../transformation.js';\n\nimport { getGlobalEnumRegistry } from './transportRegistry.js';\n\n/**\n * Revives smart enums after transport. Requires `initializeSmartEnumMappings`.\n */\nexport const reviveAfterTransport = <T>(payload: unknown): T => {\n const registry = getGlobalEnumRegistry();\n if (!registry) {\n return payload as T;\n }\n return reviveSmartEnums(payload, registry);\n};\n","import { serializeSmartEnums } from '../transformation.js';\nimport type { SerializedSmartEnums } from '../../types.js';\n\n/**\n * Serializes smart enums for transport (to client or API).\n * Wire payloads include `__smart_enum_type` for `reviveAfterTransport`.\n */\nexport const serializeForTransport = <T>(payload: T): SerializedSmartEnums<T> =>\n serializeSmartEnums(payload);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,2BAA0C;;;ACCnC,IAAM,sBAAsB,CACjC,cAC2B;AAC3B,QAAM,SAA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CAAC;AACH;AAEO,IAAM,wBAAwB,MAEpB;;;AC1DV,IAAM,uBAAuB,CAAI,YAAwB;AAC9D,QAAM,WAAW,sBAAsB;AACvC,MAAI,CAAC,UAAU;AACb,WAAO;AAAA,EACT;AACA,SAAO,iBAAiB,SAAS,QAAQ;AAC3C;;;ACNO,IAAM,wBAAwB,CAAI,YACvC,oBAAoB,OAAO;","names":[]}
@@ -1,5 +1,5 @@
1
- import { f as SerializedSmartEnums, d as SmartEnumMappingsConfig, A as AnyEnumLike } from './transformation-CVR7F8nY.cjs';
2
- export { E as Enumeration, c as LogLevel, R as RevivedSmartEnums, g as SmartEnumItemSerialized, n as StandardEnumItem, m as StandardEnumItemBase, e as enumeration, a as isSmartEnum, i as isSmartEnumItem, b as reviveEnumField, r as reviveSmartEnums, s as serializeSmartEnums } from './transformation-CVR7F8nY.cjs';
1
+ import { g as SerializedSmartEnums, f as SmartEnumMappingsConfig, A as AnyEnumLike } from './transformation-BMIA2TEH.cjs';
2
+ export { E as Enumeration, d as LogLevel, R as RevivedSmartEnums, h as SmartEnumItemSerialized, o as StandardEnumItem, n as StandardEnumItemBase, e as enumeration, a as isSmartEnum, i as isSmartEnumItem, b as reviveEnumField, r as reviveSmartEnums, s as serializeSmartEnums } from './transformation-BMIA2TEH.cjs';
3
3
 
4
4
  /**
5
5
  * Revives smart enums after transport. Requires `initializeSmartEnumMappings`.
@@ -1,5 +1,5 @@
1
- import { f as SerializedSmartEnums, d as SmartEnumMappingsConfig, A as AnyEnumLike } from './transformation-CVR7F8nY.js';
2
- export { E as Enumeration, c as LogLevel, R as RevivedSmartEnums, g as SmartEnumItemSerialized, n as StandardEnumItem, m as StandardEnumItemBase, e as enumeration, a as isSmartEnum, i as isSmartEnumItem, b as reviveEnumField, r as reviveSmartEnums, s as serializeSmartEnums } from './transformation-CVR7F8nY.js';
1
+ import { g as SerializedSmartEnums, f as SmartEnumMappingsConfig, A as AnyEnumLike } from './transformation-BMIA2TEH.js';
2
+ export { E as Enumeration, d as LogLevel, R as RevivedSmartEnums, h as SmartEnumItemSerialized, o as StandardEnumItem, n as StandardEnumItemBase, e as enumeration, a as isSmartEnum, i as isSmartEnumItem, b as reviveEnumField, r as reviveSmartEnums, s as serializeSmartEnums } from './transformation-BMIA2TEH.js';
3
3
 
4
4
  /**
5
5
  * Revives smart enums after transport. Requires `initializeSmartEnumMappings`.
package/dist/transport.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  initializeSmartEnumMappings,
4
4
  reviveAfterTransport,
5
5
  serializeForTransport
6
- } from "./chunk-CZ6TMH26.js";
6
+ } from "./chunk-6ZOLTEJT.js";
7
7
  import {
8
8
  enumeration,
9
9
  isSmartEnum,
@@ -11,7 +11,7 @@ import {
11
11
  reviveEnumField,
12
12
  reviveSmartEnums,
13
13
  serializeSmartEnums
14
- } from "./chunk-SOZ6HB6K.js";
14
+ } from "./chunk-OOVDWS5T.js";
15
15
  export {
16
16
  enumeration,
17
17
  getGlobalEnumRegistry,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reharik/smart-enum",
3
- "version": "0.3.3",
3
+ "version": "0.4.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/enumerations.ts","../src/extensionMethods.ts","../src/types.ts","../src/utilities/typeGuards.ts","../src/utilities/logger.ts","../src/utilities/transformation.ts"],"sourcesContent":["import { capitalCase, constantCase } from 'case-anything';\n\nimport { addExtensionMethods } from './extensionMethods.js';\nimport {\n SMART_ENUM,\n SMART_ENUM_ID,\n SMART_ENUM_ITEM,\n type EnumFromNormalizedObject,\n type EnumItemFromNormalizedObject,\n type EnumMemberUnionFromNormalizedObject,\n type EnumerationProps,\n type FinalizableEnumItem,\n type FinalizedEnumFields,\n type NormalizedInputType,\n type ObjectEnumInput,\n type PropertyAutoFormatter,\n} from './types.js';\n\nexport type EnumItem<TEnum> = {\n [K in keyof TEnum]: TEnum[K] extends { __smart_enum_brand: true }\n ? TEnum[K]\n : never;\n}[keyof TEnum];\n\nfunction normalizeInput<TInput extends readonly string[] | ObjectEnumInput>(\n input: TInput,\n): NormalizedInputType<TInput> {\n if (Array.isArray(input)) {\n return Object.fromEntries(\n input.map(k => [k, {}]),\n ) as NormalizedInputType<TInput>;\n }\n\n return input as NormalizedInputType<TInput>;\n}\n\nconst finalizeEnumItem = <T extends { value: string }>(\n item: T,\n enumType: string,\n enumInstanceId: symbol,\n): T & FinalizedEnumFields => {\n Object.defineProperty(item, SMART_ENUM_ITEM, {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, SMART_ENUM_ID, {\n value: enumInstanceId,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_brand', {\n value: true,\n enumerable: false,\n });\n\n Object.defineProperty(item, '__smart_enum_type', {\n value: enumType,\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toJSON', {\n value: () => ({ __smart_enum_type: enumType, value: item.value }),\n enumerable: false,\n });\n\n Object.defineProperty(item, 'toPostgres', {\n value: () => item.value,\n enumerable: false,\n });\n\n return item as T & FinalizedEnumFields;\n};\n\nconst formatProperties = (\n k: string,\n formatters: PropertyAutoFormatter[],\n): { value: string; display: string } & Record<string, string> =>\n formatters.reduce(\n (acc, formatter) => {\n acc[formatter.key] = formatter.format(k);\n return acc;\n },\n {\n value: constantCase(k),\n display: capitalCase(k),\n } as { value: string; display: string } & Record<string, string>,\n );\n\nfunction buildEnumFromObject<TObj extends ObjectEnumInput>(\n enumType: string,\n input: TObj,\n propertyAutoFormatters?: PropertyAutoFormatter[],\n): EnumFromNormalizedObject<TObj> {\n const formattersWithDefaults: PropertyAutoFormatter[] = [\n { key: 'value', format: constantCase },\n { key: 'display', format: capitalCase },\n ...(propertyAutoFormatters ?? []),\n ];\n\n type TItem = EnumMemberUnionFromNormalizedObject<TObj>;\n\n const rawEnumItems: Partial<{\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }> = {};\n\n const enumInstanceId = Symbol('smart-enum-instance');\n let index = 0;\n\n for (const key in input) {\n if (Object.prototype.hasOwnProperty.call(input, key)) {\n const typedKey = key;\n const value = input[typedKey];\n\n const enumItemBase = {\n index,\n key: typedKey,\n ...formatProperties(typedKey, formattersWithDefaults),\n ...value,\n } as FinalizableEnumItem & TObj[typeof typedKey];\n\n const enumItem = finalizeEnumItem(\n enumItemBase,\n enumType,\n enumInstanceId,\n ) as unknown as TItem;\n\n Object.freeze(enumItem);\n rawEnumItems[typedKey as keyof TObj] = enumItem;\n index++;\n }\n }\n\n const extensionMethods = addExtensionMethods<TItem>(\n Object.values(rawEnumItems) as TItem[],\n );\n\n const enumObject = {\n ...rawEnumItems,\n ...extensionMethods,\n } as EnumFromNormalizedObject<TObj>;\n\n Object.defineProperty(enumObject, SMART_ENUM, {\n value: true,\n enumerable: false,\n });\n\n Object.freeze(enumObject);\n\n return enumObject;\n}\n\nexport function enumeration<const TArr extends readonly string[]>(\n enumType: string,\n props: EnumerationProps<TArr>,\n): EnumFromNormalizedObject<NormalizedInputType<TArr>>;\n\nexport function enumeration<const TObj extends ObjectEnumInput>(\n enumType: string,\n props: EnumerationProps<TObj>,\n): EnumFromNormalizedObject<NormalizedInputType<TObj>>;\n\nexport function enumeration(\n enumType: string,\n props: EnumerationProps<readonly string[] | ObjectEnumInput>,\n) {\n const normalized = normalizeInput(props.input);\n return buildEnumFromObject(\n enumType,\n normalized,\n props.propertyAutoFormatters,\n );\n}\n","import type { CoreEnumMethods, StandardEnumItem } from './types.js';\nexport const addExtensionMethods = <TItem extends StandardEnumItem>(\n enumItems: readonly TItem[],\n): CoreEnumMethods<TItem> => {\n const findBy = <K extends keyof TItem>(field: K, target: TItem[K]) =>\n enumItems.find(item => item[field] === target);\n\n const requireBy = <K extends keyof TItem>(\n field: K,\n target: TItem[K],\n label: string,\n ) => {\n const item = findBy(field, target);\n if (!item) {\n throw new Error(`No enum ${label} found for '${String(target)}'`);\n }\n return item;\n };\n\n return {\n fromValue: value => requireBy('value', value as TItem['value'], 'value'),\n tryFromValue: value =>\n value ? findBy('value', value as TItem['value']) : undefined,\n\n fromKey: key => requireBy('key', key as TItem['key'], 'key'),\n tryFromKey: key => (key ? findBy('key', key as TItem['key']) : undefined),\n\n items: () => [...enumItems],\n values: () => enumItems.map(item => item.value),\n keys: () => enumItems.map(item => item.key),\n };\n};\n","/**\n * Type guard to check if a value is not null or undefined\n * @param value - The value to check\n * @returns True if the value is defined and not null\n */\nexport const notEmpty = <X>(\n value: X | null | undefined,\n): value is NonNullable<X> => {\n // eslint-disable-next-line unicorn/no-null\n return value != null;\n};\n\n// Public symbols used at runtime for detection/identity (not used in type keys)\nexport const SMART_ENUM_ITEM = Symbol('smart-enum-item');\nexport const SMART_ENUM_ID = Symbol('smart-enum-id');\nexport const SMART_ENUM = Symbol('smart-enum');\n\n/**\n * Options for filtering enum items in various methods\n */\nexport type EnumFilterOptions = {\n /** Include items with null/undefined values (default: false) */\n showEmpty?: boolean;\n /** Include deprecated items (default: false) */\n showDeprecated?: boolean;\n};\n\n// export type EnumInput = readonly string[] | ObjectEnumInput;\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Structural detection checks for\n * presence of `key` and `value`.\n */\nexport type SerializedSmartEnums<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<SerializedSmartEnums<U>>\n : T extends Array<infer U>\n ? SerializedSmartEnums<U>[]\n : T extends object\n ? { [K in keyof T]: SerializedSmartEnums<T[K]> }\n : T;\n\n/**\n * Revived shape: for keys present in mapping M, the string becomes the\n * corresponding enum item type (derived from the provided enum object);\n * other fields recurse.\n */\nexport type EnumItemFromEnum<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\n/**\n * Structural constraint for smart enum instances (registry entries, `reviveSmartEnums`, etc.).\n * `T` is the enum item type returned by `tryFromValue` / `tryFromKey` (default `unknown` when heterogeneous).\n */\nexport type AnyEnumLike<T = unknown> = {\n tryFromValue: (value?: string | null) => T | undefined;\n tryFromKey: (key?: string | null) => T | undefined;\n} & Record<string, unknown>;\n\nexport type RevivedSmartEnums<T, M extends Record<string, AnyEnumLike>> =\n T extends ReadonlyArray<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends Array<infer U>\n ? RevivedSmartEnums<U, M>[]\n : T extends object\n ? {\n [K in keyof T]: K extends Extract<keyof M, string>\n ? Enumeration<M[K]>\n : RevivedSmartEnums<T[K], M>;\n }\n : T;\n\nexport type SmartEnumItemSerialized = {\n __smart_enum_type: string;\n value: string;\n};\n\n/** Example shape for transport tests (`reviveAfterTransport` registry). */\nexport type SmartApiHelperConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n};\n\n/**\n * Compile-time transformer: replaces Smart Enum items with string values,\n * recursively over arrays and objects. Used for database storage.\n */\nexport type DatabaseFormat<T> = T extends { value: string; key: unknown }\n ? string\n : T extends ReadonlyArray<infer U>\n ? ReadonlyArray<DatabaseFormat<U>>\n : T extends Array<infer U>\n ? DatabaseFormat<U>[]\n : T extends object\n ? { [K in keyof T]: DatabaseFormat<T[K]> }\n : T;\n\n/**\n * Log levels for smart enum mappings\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Configuration for smart enum mappings initialization\n */\nexport type SmartEnumMappingsConfig = {\n enumRegistry: Record<string, AnyEnumLike>;\n logLevel?: LogLevel;\n logger?: import('./utilities/logger.js').Logger;\n};\n\ntype BuiltInOverrideKeys =\n | 'key'\n | 'value'\n | 'display'\n | 'deprecated'\n | 'index'\n | '__smart_enum_brand'\n | '__smart_enum_type';\n\n/**\n * Structural fields shared by every enum member (key, value, display, index, optional deprecated).\n * Does not include smart-enum branding or database helpers; see {@link StandardEnumItem}.\n */\nexport type StandardEnumItemBase = {\n readonly key: string;\n readonly value: string;\n readonly display: string;\n readonly index: number;\n readonly deprecated?: boolean;\n};\n\n/**\n * Branded item produced by `enumeration()`: {@link StandardEnumItemBase} plus runtime identity\n * (`__smart_enum_brand`, `__smart_enum_type`) and `toPostgres()`.\n */\nexport type StandardEnumItem = StandardEnumItemBase & {\n readonly __smart_enum_brand: true;\n readonly __smart_enum_type: string;\n readonly toPostgres: () => string;\n};\n\nexport type EnumInputItem = Partial<{\n key: string;\n value: string;\n display: string;\n deprecated: boolean;\n}> &\n Record<string, unknown>;\n\nexport type ObjectEnumInput = Record<string, EnumInputItem>;\n\nexport type EmptyEnumInputItem = Record<never, never>;\n\ntype Separator = '-' | '_' | ' ' | '.';\n\ntype IsUpperChar<C extends string> =\n C extends Uppercase<C> ? (C extends Lowercase<C> ? false : true) : false;\n\ntype IsLowerChar<C extends string> =\n C extends Lowercase<C> ? (C extends Uppercase<C> ? false : true) : false;\n\ntype PushUnderscore<S extends string> = S extends '' | `${string}_`\n ? S\n : `${S}_`;\n\ntype TrimUnderscore<S extends string> = S extends `_${infer R}`\n ? TrimUnderscore<R>\n : S extends `${infer R}_`\n ? TrimUnderscore<R>\n : S;\n\ntype CollapseUnderscores<S extends string> = S extends `${infer A}__${infer B}`\n ? CollapseUnderscores<`${A}_${B}`>\n : S;\n\ntype ConstantCaseInternal<\n S extends string,\n Prev extends string = '',\n Out extends string = '',\n> = S extends `${infer C}${infer Rest}`\n ? C extends Separator\n ? ConstantCaseInternal<Rest, C, PushUnderscore<Out>>\n : IsUpperChar<C> extends true\n ? IsLowerChar<Prev> extends true\n ? ConstantCaseInternal<Rest, C, `${PushUnderscore<Out>}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : ConstantCaseInternal<Rest, C, `${Out}${Uppercase<C>}`>\n : CollapseUnderscores<TrimUnderscore<Out>>;\n\ntype ConstantCase<S extends string> = string extends S\n ? string\n : ConstantCaseInternal<S>;\n\n/** Segments of a `ConstantCase` string (underscore-separated ALL CAPS words). */\ntype SplitConstantCaseSegments<S extends string> =\n S extends `${infer A}_${infer B}`\n ? [A, ...SplitConstantCaseSegments<B>]\n : [S];\n\n/** First character upper, remainder lower (for ALL-CAPS words from `ConstantCase`). */\ntype TitleCaseAllCapsWord<W extends string> = W extends ''\n ? ''\n : W extends `${infer F}${infer R}`\n ? `${Uppercase<F>}${Lowercase<R>}`\n : W;\n\ntype JoinDisplaySegments<T extends readonly string[]> = T extends readonly [\n infer A extends string,\n ...infer Rest extends readonly string[],\n]\n ? Rest extends readonly []\n ? TitleCaseAllCapsWord<A>\n : `${TitleCaseAllCapsWord<A>} ${JoinDisplaySegments<Rest>}`\n : '';\n\n/**\n * Display string derived from the enum member key: `ConstantCase` → split → title-case words → join with spaces.\n * Matches default runtime `capitalCase(key)` for typical PascalCase / camelCase keys. Member keys that already\n * contain separators may differ from `capitalCase` at runtime; custom `propertyAutoFormatters` for `display`\n * are not reflected in this type.\n */\ntype DisplayCaseFromEnumKey<K extends string> = string extends K\n ? string\n : JoinDisplaySegments<SplitConstantCaseSegments<ConstantCase<K>>>;\n\nexport type ArrayToObjectType<T extends readonly string[]> = {\n [K in T[number]]: EmptyEnumInputItem & { readonly value?: ConstantCase<K> };\n};\n\nexport type NormalizedInputType<TInput> = TInput extends readonly string[]\n ? ArrayToObjectType<TInput>\n : TInput extends ObjectEnumInput\n ? TInput\n : never;\n\n/** Input-derived fields for one member key (excludes built-ins filled by `enumeration()`). */\nexport type EnumMemberExtra<\n TObj extends ObjectEnumInput,\n K extends keyof TObj,\n> = Omit<TObj[K], BuiltInOverrideKeys>;\n\nexport type EnumItemFromNormalizedObject<\n TObj extends ObjectEnumInput,\n K extends keyof TObj = keyof TObj,\n> = Omit<StandardEnumItem, 'key' | 'value' | 'display'> &\n EnumMemberExtra<TObj, K> & {\n readonly key: Extract<K, string>;\n readonly value: TObj[K] extends { value?: infer V }\n ? [Extract<V, string>] extends [never]\n ? ConstantCase<Extract<K, string>>\n : Extract<V, string>\n : ConstantCase<Extract<K, string>>;\n readonly display: TObj[K] extends { display?: infer D }\n ? [Extract<D, string>] extends [never]\n ? DisplayCaseFromEnumKey<Extract<K, string>>\n : Extract<D, string>\n : DisplayCaseFromEnumKey<Extract<K, string>>;\n };\n\nexport type EnumMemberUnionFromNormalizedObject<TObj extends ObjectEnumInput> =\n {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n }[keyof TObj];\n\nexport type EnumFromNormalizedObject<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: EnumItemFromNormalizedObject<TObj, K>;\n} & CoreEnumMethods<EnumMemberUnionFromNormalizedObject<TObj>>;\n\nexport type UnionKeys<T> = T extends T ? keyof T : never;\n\n/*\nTo widen the type of the OptionalObject from literals to their actual types,\ne.g.\nshape?: \"round\" | \"square\" | \"long\";\nslices?: true;\nlayers?: 2;\n--turns into:--\nshape: string | undefined;\nslices: boolean| undefined;\nlayers: number| undefined;\n\nwe can use the following code:\ntype Widen<T> = T extends string\n ? string\n : T extends number\n ? number\n : T extends boolean\n ? boolean\n : T;\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? Widen<V> : undefined;\n};\n*/\n\ntype MergeUnionToObject<T> = {\n [K in UnionKeys<T>]: T extends Record<K, infer V> ? V : undefined;\n};\n\ntype ExtraShapeUnion<TObj extends ObjectEnumInput> = {\n [K in keyof TObj]: Omit<TObj[K], BuiltInOverrideKeys>;\n}[keyof TObj];\n\nexport type InferredExtraFields<TObj extends ObjectEnumInput> =\n MergeUnionToObject<ExtraShapeUnion<TObj>>;\n\nexport type PropertyAutoFormatter = {\n /** The property name to generate */\n key: string;\n /** Function to transform the key into the property value */\n format: (k: string) => string;\n};\n\nexport type CoreEnumMethods<TItem extends StandardEnumItem> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n items(): readonly TItem[];\n /** Matches runtime: `items.map(i => i.value)` (see {@link EnumLikeBase}). */\n values(): readonly TItem['value'][];\n /** Matches runtime: `items.map(i => i.key)` (see {@link EnumLikeBase}). */\n keys(): readonly TItem['key'][];\n};\n\n/**\n * Structural shape of a smart-style enum object: lookup by value/key, list items/values/keys,\n * plus an index signature so registry and mapping types can treat instances as records.\n * Use {@link SmartEnumLike} when items are full {@link StandardEnumItem}s (the usual case).\n */\nexport type EnumLikeBase<\n TItem extends StandardEnumItemBase = StandardEnumItemBase,\n> = {\n fromValue(value: string): TItem;\n tryFromValue(value?: string | null): TItem | undefined;\n fromKey(key: string): TItem;\n tryFromKey(key?: string | null): TItem | undefined;\n items(): readonly TItem[];\n values(): readonly TItem['value'][];\n keys(): readonly TItem['key'][];\n} & Record<string, unknown>;\n\n/**\n * A {@link EnumLikeBase} whose items are branded {@link StandardEnumItem}s (typical `enumeration()` result).\n */\nexport type SmartEnumLike<TItem extends StandardEnumItem = StandardEnumItem> =\n EnumLikeBase<TItem>;\n\n/** Union of branded enum member values on an enum object `T`. */\nexport type SmartEnumMemberUnion<T extends Record<string, unknown>> = {\n [K in keyof T]: T[K] extends StandardEnumItem ? T[K] : never;\n}[keyof T];\n\n/** Keys on `TEnum` whose member matches `Record<P, V>` within `ItemUnion`. */\nexport type SmartEnumSubsetKeys<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = {\n [K in keyof TEnum]: TEnum[K] extends Extract<ItemUnion, Record<P, V>>\n ? K\n : never;\n}[keyof TEnum];\n\nexport type SmartEnumSubsetItemUnion<\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Extract<ItemUnion, Record<P, V>>;\n\nexport type SmartEnumSubsetView<\n TEnum extends Record<string, unknown>,\n ItemUnion extends StandardEnumItem,\n P extends keyof ItemUnion & string,\n V extends ItemUnion[P],\n> = Pick<TEnum, SmartEnumSubsetKeys<TEnum, ItemUnion, P, V>> &\n CoreEnumMethods<SmartEnumSubsetItemUnion<ItemUnion, P, V>>;\n\nexport type FieldEnumMapping = Record<string, SmartEnumLike>;\n\nexport type ReviveRowOptions = {\n fieldEnumMapping: FieldEnumMapping;\n strict?: boolean;\n};\n\nexport type PathEnumMapping = Record<string, SmartEnumLike>;\n\nexport type RevivePayloadOptions = {\n pathEnumMapping: PathEnumMapping;\n strict?: boolean;\n};\n\nexport type EnumerationProps<TInput> = {\n input: TInput;\n propertyAutoFormatters?: PropertyAutoFormatter[];\n};\n\nexport type Enumeration<TEnum> =\n TEnum extends Record<string, infer V>\n ? V extends { __smart_enum_brand: true }\n ? V\n : never\n : never;\n\nexport type FinalizedEnumFields = Pick<\n StandardEnumItem,\n '__smart_enum_brand' | '__smart_enum_type'\n>;\nexport type FinalizableEnumItem = {\n key: string;\n value: string;\n display: string;\n index: number;\n deprecated?: boolean;\n};\n","import {\n SMART_ENUM_ITEM,\n SMART_ENUM,\n SmartEnumItemSerialized,\n} from '../types.js';\n\n/**\n * Runtime type guard to detect Smart Enum items created by this library.\n * Returns true if the value has the SMART_ENUM_ITEM symbol.\n *\n * @example\n * ```typescript\n * import { Status } from './status';\n * const item = Status.active;\n * isSmartEnumItem(item); // true\n * isSmartEnumItem({ key: 'active', value: 'ACTIVE' }); // false (plain object)\n * if (isSmartEnumItem(x)) {\n * console.log(x.value, x.__smart_enum_type); // narrowed to enum item\n * }\n * ```\n */\nexport const isSmartEnumItem = (\n x: unknown,\n): x is {\n key: string;\n value: string;\n index?: number;\n __smart_enum_type?: string;\n} => {\n return (\n !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM_ITEM) === true\n );\n};\n\n/**\n * Runtime type guard to detect a full Smart Enum object created by this library.\n * Returns true if the object has the SMART_ENUM property.\n *\n * @example\n * ```typescript\n * import { MyEnum } from './blah';\n * isSmartEnum(MyEnum) === true; // true\n * isSmartEnum(MyEnum.one) === false; // false (this is an item, not the enum)\n * ```\n */\nexport const isSmartEnum = (x: unknown): boolean => {\n return !!x && typeof x === 'object' && Reflect.get(x, SMART_ENUM) === true;\n};\n\n/**\n * Runtime type guard to detect a serialized Smart Enum item created by this library.\n * Returns true if the value has `__smart_enum_type` and `value` (wire/database shape).\n *\n * @example\n * ```typescript\n * const wire = { __smart_enum_type: 'Status', value: 'ACTIVE' };\n * isSerializedSmartEnumItem(wire); // true\n * isSerializedSmartEnumItem(Status.active); // false (live enum item)\n * if (isSerializedSmartEnumItem(x)) {\n * reviveItem(x.__smart_enum_type, x.value); // narrowed to SmartEnumItemSerialized\n * }\n * ```\n */\nexport const isSerializedSmartEnumItem = (\n x: unknown,\n): x is SmartEnumItemSerialized => {\n return (\n !!x &&\n typeof x === 'object' &&\n Reflect.has(x, '__smart_enum_type') &&\n Reflect.has(x, 'value')\n );\n};\n","/**\n * Logger interface for @reharik/smart-enum library\n *\n * This interface allows users to inject their own logging implementation\n * or use the default console logger.\n */\n\nexport type Logger = {\n debug(message: string, ...args: unknown[]): void;\n info(message: string, ...args: unknown[]): void;\n warn(message: string, ...args: unknown[]): void;\n error(message: string, ...args: unknown[]): void;\n};\n\n/**\n * Default console logger implementation\n */\nconst consoleLogger: Logger = {\n debug(message: string, ...args: unknown[]): void {\n console.debug(`[@reharik/smart-enum:debug] ${message}`, ...args);\n },\n\n info(message: string, ...args: unknown[]): void {\n console.info(`[@reharik/smart-enum:info] ${message}`, ...args);\n },\n\n warn(message: string, ...args: unknown[]): void {\n console.warn(`[@reharik/smart-enum:warn] ${message}`, ...args);\n },\n\n error(message: string, ...args: unknown[]): void {\n console.error(`[@reharik/smart-enum:error] ${message}`, ...args);\n },\n};\n\n/**\n * Global logger instance\n * Defaults to console logger\n */\nlet globalLogger: Logger = consoleLogger;\n\n/**\n * Sets the global logger instance\n *\n * @param logger - The logger implementation to use\n *\n * @example\n * ```typescript\n * import { setLogger } from '@reharik/smart-enum';\n *\n * // Use custom logger\n * setLogger({\n * debug: (msg, ...args) => myLogger.debug(msg, args),\n * info: (msg, ...args) => myLogger.info(msg, args),\n * warn: (msg, ...args) => myLogger.warn(msg, args),\n * error: (msg, ...args) => myLogger.error(msg, args),\n * });\n * ```\n */\nexport function setLogger(logger: Logger): void {\n globalLogger = logger;\n}\n\n/**\n * Gets the current logger instance\n *\n * @returns The current logger instance\n */\nexport function getLogger(): Logger {\n return globalLogger;\n}\n\n// Internal convenience functions for library use\nexport function debug(message: string, ...args: unknown[]): void {\n globalLogger.debug(message, ...args);\n}\n\nexport function info(message: string, ...args: unknown[]): void {\n globalLogger.info(message, ...args);\n}\n\nexport function warn(message: string, ...args: unknown[]): void {\n globalLogger.warn(message, ...args);\n}\n\nexport function error(message: string, ...args: unknown[]): void {\n globalLogger.error(message, ...args);\n}\n","// serializeSmartEnums.ts\nexport { isSmartEnumItem, isSmartEnum } from './typeGuards.js';\nimport type { SerializedSmartEnums, AnyEnumLike } from '../types.js';\n\nimport { debug } from './logger.js';\nimport { isSerializedSmartEnumItem, isSmartEnumItem } from './typeGuards.js';\n\ntype PlainObject = Record<string, unknown>;\n\nconst isPlainObject = (x: unknown): x is PlainObject =>\n typeof x === 'object' &&\n x !== null &&\n Object.getPrototypeOf(x) === Object.prototype;\n\n/**\n * Recursively replaces Smart Enum items with self-describing objects\n * `{ __smart_enum_type, value }` for JSON transport or storage.\n *\n * @param input - Object or array that may contain enum items\n * @returns Same structure with enum items replaced by serialized shape\n *\n * @example\n * ```typescript\n * const dto = { id: '1', status: Status.active, color: Color.red };\n * const wire = serializeSmartEnums(dto);\n * // wire: { id: '1', status: { __smart_enum_type: 'Status', value: 'ACTIVE' }, color: { __smart_enum_type: 'Color', value: 'RED' } }\n * ```\n */\n// Overloads:\n// 1) Inferred\nexport function serializeSmartEnums<T>(input: T): SerializedSmartEnums<T>;\n// 2) Return-type only (constrained to objects/arrays)\nexport function serializeSmartEnums<\n S extends Readonly<PlainObject> | readonly unknown[],\n>(input: unknown): S;\n// Implementation\nexport function serializeSmartEnums(input: unknown): unknown {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n if (isSmartEnumItem(v)) {\n return {\n __smart_enum_type: v.__smart_enum_type,\n value: v.value,\n };\n }\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) {\n arr.push(walk(item));\n }\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n\n return walk(input);\n}\n\n/**\n * Recursively revives serialized enum objects back to Smart Enum items\n * using a registry of enum types. Expects payload to contain\n * `{ __smart_enum_type, value }` where the type exists in the registry.\n *\n * @param input - Serialized payload (e.g. from JSON)\n * @param registry - Map of enum type name to enum object (e.g. `{ Status, Color }`)\n * @returns Payload with serialized enums revived to enum items\n *\n * @example\n * ```typescript\n * const wire = { status: { __smart_enum_type: 'Status', value: 'ACTIVE' } };\n * const revived = reviveSmartEnums(wire, { Status, Color });\n * // revived.status === Status.active\n * ```\n */\nexport function reviveSmartEnums<R>(\n input: unknown,\n registry: Record<string, AnyEnumLike>,\n): R {\n const seen = new WeakMap<object, unknown>();\n\n const walk = (v: unknown): unknown => {\n // Handle self-describing enum objects with __smart_enum_type and value\n if (isSerializedSmartEnumItem(v)) {\n debug(`Found serialized smartEnum: ${v.__smart_enum_type}`);\n const enumInstance = registry[v.__smart_enum_type];\n if (enumInstance) {\n debug(`Found enumInstance in registry: ${v.__smart_enum_type}`);\n // Try to find the enum item by value first\n const enumItem = enumInstance.tryFromValue(v.value);\n if (enumItem) {\n debug(`Revived enumItem using value: ${v.value}`);\n return enumItem;\n }\n // If that fails, try to find by key (convert value to key format)\n const key = v.value.toLowerCase();\n const enumItemFromKey = enumInstance.tryFromKey(key);\n if (enumItemFromKey) {\n debug(`Revived enumItem using key: ${key}`);\n return enumItemFromKey;\n }\n }\n // If no matching enum type in registry, return the original serialized object\n return v;\n }\n\n if (typeof v === 'object' && v !== null && seen.has(v)) {\n return seen.get(v);\n }\n\n if (Array.isArray(v)) {\n const arr: unknown[] = [];\n seen.set(v, arr);\n for (const item of v) arr.push(walk(item));\n return arr;\n }\n if (isPlainObject(v)) {\n const out: PlainObject = {};\n seen.set(v, out);\n for (const [k, val] of Object.entries(v)) {\n out[k] = walk(val);\n }\n return out;\n }\n return v;\n };\n return walk(input) as R;\n}\n\n/**\n * Maps a plain string (for example a column value from a database query) to the\n * corresponding Smart Enum item by calling `tryFromValue` on the given enum.\n *\n * Use this when you already know which enum type a field uses and the stored\n * value is the enum’s wire `value` string (same shape `tryFromValue` expects).\n *\n * @param value - Raw value; only strings are resolved—anything else returns `undefined`\n * @param smartEnum - Smart enum instance (`AnyEnumLike<TItem>`; same shape as registry entries)\n * @param strict - When `true`, throws if the string does not match any member; when `false`, returns `undefined`\n * @returns The matching enum item, or `undefined` if not found (non-string input always yields `undefined`)\n *\n * @example\n * ```typescript\n * const item = reviveEnumField(row.status, UserStatus);\n * const mustMatch = reviveEnumField(row.code, OrderStatus, true);\n * ```\n */\nexport const reviveEnumField = <TItem>(\n value: unknown,\n smartEnum: AnyEnumLike<TItem>,\n strict = false,\n): TItem | undefined => {\n if (typeof value !== 'string') return undefined;\n\n const revived = smartEnum.tryFromValue(value);\n if (revived !== undefined) return revived;\n\n if (strict) {\n throw new Error(`Unknown enum value: ${JSON.stringify(value)}`);\n }\n\n return undefined;\n};\n"],"mappings":";AAAA,SAAS,aAAa,oBAAoB;;;ACCnC,IAAM,sBAAsB,CACjC,cAC2B;AAC3B,QAAM,SAAS,CAAwB,OAAU,WAC/C,UAAU,KAAK,UAAQ,KAAK,KAAK,MAAM,MAAM;AAE/C,QAAM,YAAY,CAChB,OACA,QACA,UACG;AACH,UAAM,OAAO,OAAO,OAAO,MAAM;AACjC,QAAI,CAAC,MAAM;AACT,YAAM,IAAI,MAAM,WAAW,KAAK,eAAe,OAAO,MAAM,CAAC,GAAG;AAAA,IAClE;AACA,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,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