@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
package/README.md CHANGED
@@ -1,380 +1,36 @@
1
1
  # @reharik/smart-enum
2
2
 
3
- Type-safe, feature-rich enumerations for TypeScript. Every enum member is a frozen object with a key, a wire value, a display string, an index, and whatever custom fields you need — plus lookup, iteration, serialization, and database revival built in.
4
-
5
- ## Why not just use TypeScript enums?
6
-
7
- TypeScript's built-in `enum` gives you a name-to-value mapping and nothing else. You can't iterate members, attach metadata, look up by value at runtime, or serialize/revive across a network boundary without writing boilerplate every time.
8
-
9
- The common workarounds each solve one piece:
10
-
11
- - **Plain objects** (`{ ACTIVE: 'active' }`) — no iteration, no type narrowing, no metadata, annoying text duplication.
12
- - **String unions** (`type Status = 'active' | 'inactive'`) — compile-time only. No runtime lookup, no `.display`, no `.items()`.
13
- - **Arrays** (`['active', 'inactive'] as const`) — iterable, but no keyed access or metadata.
14
- - **Constants** (const ME = "me") — scattered and hard to iterate
15
-
16
- Smart Enums give you all of it in one construct:
17
-
18
- ```typescript
19
- import { enumeration, type Enumeration } from '@reharik/smart-enum';
20
-
21
- const Status = enumeration('Status', {
22
- input: ['pending', 'active', 'completed'] as const,
23
- });
24
- type Status = Enumeration<typeof Status>;
25
-
26
- Status.active;
27
- // { key: 'active', value: 'ACTIVE', display: 'Active', index: 1 }
28
-
29
- Status.fromValue('ACTIVE'); // Status.active
30
- Status.tryFromValue('NOPE'); // undefined
31
- Status.items(); // all members as a frozen array
32
- Status.values(); // ['PENDING', 'ACTIVE', 'COMPLETED']
33
- Status.keys(); // ['pending', 'active', 'completed']
34
- ```
35
-
36
- Type safety works the way you'd expect — a function that takes `Status` won't accept a member from a different enum, even if the shapes look similar.
37
-
38
- ## Install
39
-
40
- ```bash
41
- npm install @reharik/smart-enum
42
- ```
43
-
44
- ## Creating enums
45
-
46
- ### From an array
47
-
48
- The simplest form. Keys are the array values, wire values are auto-derived as `CONSTANT_CASE`, display strings as `Title Case`.
49
-
50
- ```typescript
51
- const Color = enumeration('Color', {
52
- input: ['red', 'blue', 'green'] as const,
53
- });
54
- type Color = Enumeration<typeof Color>;
55
-
56
- Color.red.key; // 'red'
57
- Color.red.value; // 'RED'
58
- Color.red.display; // 'Red'
59
- Color.red.index; // 0
60
- ```
61
-
62
- > **`as const` is required** on array inputs. Without it, TypeScript widens the type to `string[]` and you lose literal inference on keys and values.
63
-
64
- ### From an object
65
-
66
- When you need custom values, display strings, or extra fields per member:
67
-
68
- ```typescript
69
- const Priority = enumeration('Priority', {
70
- input: {
71
- low: { display: 'Low Priority' },
72
- medium: { display: 'Medium Priority' },
73
- high: { value: 'P1', display: 'High Priority' },
74
- urgent: { value: 'P0', display: 'Urgent!!!' },
75
- } as const,
76
- });
77
- type Priority = Enumeration<typeof Priority>;
78
-
79
- Priority.high.value; // 'P1' (explicit)
80
- Priority.low.value; // 'LOW' (auto-derived from key)
81
- Priority.urgent.display; // 'Urgent!!!'
82
- ```
83
-
84
- If you omit `value`, it's derived from the key via `constantCase`. If you omit `display`, it's derived via `capitalCase`. You can override either or both per member.
85
-
86
- ### Custom fields
87
-
88
- Any extra properties you put on a member are preserved with full type inference:
89
-
90
- ```typescript
91
- const AppError = enumeration('AppError', {
92
- input: {
93
- notFound: { source: 'api', httpStatus: 404 },
94
- unauthorized: { source: 'auth', httpStatus: 401 },
95
- serverError: { source: 'api', httpStatus: 500 },
96
- } as const,
97
- });
98
-
99
- AppError.notFound.source; // 'api' (literal type)
100
- AppError.notFound.httpStatus; // 404 (literal type)
101
-
102
- // You can Extract by custom fields:
103
- type ApiErrors = Extract<Enumeration<typeof AppError>, { source: 'api' }>;
104
- ```
105
-
106
- ### Custom auto-formatters
107
-
108
- Override how `value`, `display`, or any auto-generated property is derived from the key:
109
-
110
- ```typescript
111
- const Routes = enumeration('Routes', {
112
- input: ['userProfile', 'adminDashboard'] as const,
113
- propertyAutoFormatters: [
114
- { key: 'value', format: k => `/${k}` },
115
- { key: 'slug', format: k => k.replace(/([A-Z])/g, '-$1').toLowerCase() },
116
- ],
117
- });
118
-
119
- Routes.userProfile.value; // '/userProfile'
120
- Routes.userProfile.slug; // 'user-profile'
121
- ```
122
-
123
- ## Lookup methods
124
-
125
- Every enum object has these methods. Return types are fully narrowed to the enum's member union.
126
-
127
- | Method | Description |
128
- | --------------------- | ----------------------------------------------------- |
129
- | `fromValue(value)` | Find by wire value. Throws if not found. |
130
- | `tryFromValue(value)` | Find by wire value. Returns `undefined` if not found. |
131
- | `fromKey(key)` | Find by key. Throws if not found. |
132
- | `tryFromKey(key)` | Find by key. Returns `undefined` if not found. |
133
- | `items()` | All members as a frozen array. |
134
- | `values()` | All wire values as an array. |
135
- | `keys()` | All keys as an array. |
136
-
137
- ## Subsetting by a custom field
138
-
139
- Filter an enum down to members matching a property value. The result is a new enum-like object with its own `fromValue`, `items`, etc., scoped to the subset:
140
-
141
- ```typescript
142
- import { getSubsetByProp, subsetByProp } from '@reharik/smart-enum';
143
-
144
- const apiErrors = getSubsetByProp(AppError, 'source', 'api' as const);
145
-
146
- apiErrors.notFound; // same object as AppError.notFound
147
- apiErrors.items(); // only api-source members
148
- apiErrors.fromValue('500'); // works, scoped to subset
149
- // apiErrors.unauthorized → not present (source is 'auth')
150
-
151
- // Curried form:
152
- const bySource = subsetByProp('source');
153
- const authErrors = bySource(AppError, 'auth' as const);
154
- ```
155
-
156
- ## Tree-shaking
157
-
158
- The package has multiple entry points so you only pay for what you import:
159
-
160
- ```typescript
161
- // Core only — enumeration + type guards + subset helpers (~149 bytes)
162
- import { enumeration } from '@reharik/smart-enum/core';
163
-
164
- // Core + transport serialization/revival (~406 bytes)
165
- import { serializeForTransport } from '@reharik/smart-enum/transport';
166
-
167
- // Core + database serialization/revival (~379 bytes)
168
- import { prepareForDatabase } from '@reharik/smart-enum/database';
169
-
170
- // Everything (~598 bytes)
171
- import {
172
- enumeration,
173
- serializeSmartEnums,
174
- prepareForDatabase,
175
- } from '@reharik/smart-enum';
176
- ```
177
-
178
- ## Serialization and transport
179
-
180
- Smart enum items serialize to self-describing `{ __smart_enum_type, value }` objects for JSON transport. On the receiving end, a registry maps them back to live enum instances.
181
-
182
- ```typescript
183
- import { serializeSmartEnums, reviveSmartEnums } from '@reharik/smart-enum';
184
-
185
- const dto = { id: '1', status: Status.active, color: Color.red };
186
-
187
- // Serialize
188
- const wire = serializeSmartEnums(dto);
189
- // { id: '1',
190
- // status: { __smart_enum_type: 'Status', value: 'ACTIVE' },
191
- // color: { __smart_enum_type: 'Color', value: 'RED' } }
192
-
193
- // Revive
194
- const revived = reviveSmartEnums(wire, { Status, Color });
195
- // revived.status === Status.active ✓
196
- ```
197
-
198
- ### Global transport registry
199
-
200
- For app-wide setup (e.g. Express middleware), register all enums once at startup:
201
-
202
- ```typescript
203
- import {
204
- initializeSmartEnumMappings,
205
- serializeForTransport,
206
- reviveAfterTransport,
207
- } from '@reharik/smart-enum/transport';
208
-
209
- // At startup
210
- initializeSmartEnumMappings({
211
- enumRegistry: { Status, Priority, Color },
212
- });
213
-
214
- // In a handler
215
- const wire = serializeForTransport(responseData);
216
- const revived = reviveAfterTransport(requestBody);
217
- ```
218
-
219
- ## Database utilities
220
-
221
- **Outbound:** `prepareForDatabase` recursively replaces enum items with their `.value` strings. Each item also has a `.toPostgres()` method for PostgreSQL drivers that honor it.
222
-
223
- **Inbound:** Database columns are plain strings — they don't carry type information. Revival requires you to declare which columns map to which enums.
224
-
225
- ```typescript
226
- import {
227
- prepareForDatabase,
228
- reviveRowFromDatabase,
229
- revivePayloadFromDatabase,
230
- } from '@reharik/smart-enum/database';
231
-
232
- // Write
233
- const dbRow = prepareForDatabase({ name: 'Alice', status: Status.active });
234
- // { name: 'Alice', status: 'ACTIVE' }
235
-
236
- // Read — flat row
237
- const revived = reviveRowFromDatabase(row, {
238
- fieldEnumMapping: { status: Status, priority: Priority },
239
- strict: true, // throw on unknown values instead of keeping raw string
240
- });
241
-
242
- // Read — nested payload (e.g. JSONB column)
243
- const doc = revivePayloadFromDatabase(payload, {
244
- pathEnumMapping: {
245
- 'user.status': Status,
246
- 'items[].kind': ItemKind,
247
- },
248
- });
249
- ```
250
-
251
- `strict: true` throws `EnumRevivalError` when a mapped string doesn't match any member. Without it, unrecognized values are left as-is.
252
-
253
- ## Type guards
254
-
255
- ```typescript
256
- import { isSmartEnumItem, isSmartEnum } from '@reharik/smart-enum';
257
-
258
- isSmartEnumItem(Status.active); // true
259
- isSmartEnumItem({ key: 'x' }); // false (plain object)
260
-
261
- isSmartEnum(Status); // true (the enum object)
262
- isSmartEnum(Status.active); // false (a member, not the enum)
263
- ```
3
+ This package is built from `packages/core`. Full documentation (transport, database, GraphQL, and more) lives in the [repository README](../../README.md).
264
4
 
265
5
  ## GraphQL integration
266
6
 
267
- ### Server-side: resolvers returning smart-enum instances
268
-
269
- Out of the box, if a GraphQL resolver returns a smart-enum item, the default `serialize` on `GraphQLEnumType` doesn't know how to extract the string value — it just passes the object through, which breaks the response.
270
-
271
- `patchSchemaEnumSerializers` walks your executable schema at startup and patches every `GraphQLEnumType.serialize` to call `.value` on smart-enum instances. After that, resolvers can return smart-enum items directly:
272
-
273
- ```typescript
274
- import { patchSchemaEnumSerializers } from '@reharik/smart-enum';
275
- import { makeExecutableSchema } from '@graphql-tools/schema';
276
-
277
- const schema = makeExecutableSchema({ typeDefs, resolvers });
278
-
279
- // Call once at startup, after schema construction
280
- patchSchemaEnumSerializers(schema);
281
-
282
- // Now resolvers can return smart-enum items directly:
283
- const resolvers = {
284
- Query: {
285
- order: () => ({
286
- id: '1',
287
- status: PaymentStatus.paid, // no .value needed
288
- type: OrderType.online,
289
- }),
290
- },
291
- };
292
- ```
293
-
294
- The patched `serialize` does `val?.value ?? val` — smart-enum items return their `.value` string, and raw strings pass through unchanged. This means you can adopt it incrementally without breaking existing resolvers that already return strings.
295
-
296
- ### Client-side: Apollo cache rehydration
297
-
298
- The [`@reharik/graphql-codegen-smart-enum`](https://www.npmjs.com/package/@reharik/graphql-codegen-smart-enum) package includes a second codegen plugin that generates Apollo `typePolicies` with `read` functions for every enum field. Spread the output into your `InMemoryCache` and components receive smart-enum instances from queries instead of raw strings:
7
+ ### Client-side: outgoing variables
299
8
 
300
- ```typescript
301
- import { InMemoryCache } from '@apollo/client';
302
- import { smartEnumTypePolicies } from './generated/graphql-smart-enum-type-policies';
303
-
304
- const cache = new InMemoryCache({
305
- typePolicies: {
306
- ...smartEnumTypePolicies,
307
- },
308
- });
9
+ If your Apollo Client uses a link that processes variables against the schema — most commonly [`apollo-link-scalars`](https://www.npmjs.com/package/apollo-link-scalars) — that link will call `serialize` on every variable value, including smart-enum instances, _before_ JSON.stringify runs. GraphQL's default `serialize` on `GraphQLEnumType` doesn't know how to handle smart-enum objects and throws:
309
10
 
310
- // In a component:
311
- const { data } = useQuery(GET_ORDER);
312
- data.order.status.display; // 'Paid' — not just 'PAID'
313
11
  ```
314
-
315
- See the [`type-policies` plugin README](https://www.npmjs.com/package/@reharik/graphql-codegen-smart-enum) for setup details.
316
-
317
- ## React
318
-
319
- ```tsx
320
- function StatusPicker() {
321
- const [selected, setSelected] = useState(Status.pending);
322
-
323
- return (
324
- <select
325
- value={selected.value}
326
- onChange={e => setSelected(Status.fromValue(e.target.value))}
327
- >
328
- {Status.items().map(item => (
329
- <option key={item.value} value={item.value}>
330
- {item.display}
331
- </option>
332
- ))}
333
- </select>
334
- );
335
- }
12
+ Enum "ReactionEmoji" cannot represent value: { __smart_enum_type: ..., value: ... }
336
13
  ```
337
14
 
338
- ## The `enumType` string
339
-
340
- The first argument to `enumeration()` is a string name used for serialization identity (`__smart_enum_type`) and `toJSON()`. It must be unique across your app and consistent between serialization and revival.
341
-
342
- For hand-authored enums, keep it matching the variable name by convention:
15
+ The same `patchSchemaEnumSerializers` that you use on the server also fixes this on the client. Patch your client schema before passing it to the link:
343
16
 
344
17
  ```typescript
345
- const Status = enumeration('Status', { input: ... });
346
- // ^^^^^^ ^^^^^^ ← keep these in sync
347
- ```
18
+ import { buildSchema } from 'graphql';
19
+ import { ApolloClient, ApolloLink, InMemoryCache } from '@apollo/client';
20
+ import { withScalars } from 'apollo-link-scalars';
21
+ import { patchSchemaEnumSerializers } from '@reharik/smart-enum/graphql';
22
+ import { enumRegistry } from '@packages/contracts';
23
+ import sdl from './generated/schema.graphql?raw';
348
24
 
349
- If you use the [`@reharik/graphql-codegen-smart-enum`](https://www.npmjs.com/package/@reharik/graphql-codegen-smart-enum) codegen plugin, this is handled automatically — the GraphQL enum type name becomes the `enumType` string.
25
+ const schema = buildSchema(sdl);
26
+ patchSchemaEnumSerializers(schema, enumRegistry);
350
27
 
351
- ## Logging
28
+ const scalarLink = withScalars({ schema, typesMap: { /* ... */ } });
352
29
 
353
- Transport initialization supports pluggable logging:
354
-
355
- ```typescript
356
- initializeSmartEnumMappings({
357
- enumRegistry: { Status, Priority },
358
- logLevel: 'debug', // 'debug' | 'info' | 'warn' | 'error'
359
- logger: {
360
- debug: (msg, ...args) => myLogger.debug(msg, ...args),
361
- info: (msg, ...args) => myLogger.info(msg, ...args),
362
- warn: (msg, ...args) => myLogger.warn(msg, ...args),
363
- error: (msg, ...args) => myLogger.error(msg, ...args),
364
- },
30
+ export const client = new ApolloClient({
31
+ link: ApolloLink.from([scalarLink, httpLink]),
32
+ cache: new InMemoryCache({ /* ... */ }),
365
33
  });
366
34
  ```
367
35
 
368
- Default is `console` at `'error'` level.
369
-
370
- ## Related packages
371
-
372
- | Package | Purpose |
373
- | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------- |
374
- | [`@reharik/smart-enum-knex`](https://www.npmjs.com/package/@reharik/smart-enum-knex) | Knex query-level enum revival via `postProcessResponse` |
375
- | [`@reharik/graphql-codegen-smart-enum`](https://www.npmjs.com/package/@reharik/graphql-codegen-smart-enum) | Generate smart-enum definitions from GraphQL schema enums |
376
- | [`@reharik/graphql-codegen-smart-enum/type-policies`](https://www.npmjs.com/package/@reharik/graphql-codegen-smart-enum) | Generate Apollo `typePolicies` for client-side enum rehydration |
377
-
378
- ## License
379
-
380
- MIT
36
+ If you're not using a schema-aware link, you don't need this — Apollo's default behavior calls `JSON.stringify` on variables directly, which goes through smart-enum's `toJSON` (with `serializeAs: 'value'`) and produces the correct wire format.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  isSmartEnumItem
3
- } from "./chunk-SOZ6HB6K.js";
3
+ } from "./chunk-OOVDWS5T.js";
4
4
 
5
5
  // src/db/prepareForDatabase.ts
6
6
  var isPlainObject = (x) => typeof x === "object" && x !== null && Object.getPrototypeOf(x) === Object.prototype;
@@ -181,4 +181,4 @@ export {
181
181
  reviveRowFromDatabase,
182
182
  revivePayloadFromDatabase
183
183
  };
184
- //# sourceMappingURL=chunk-TXDI7ASS.js.map
184
+ //# sourceMappingURL=chunk-6PARBLRO.js.map
@@ -4,7 +4,7 @@ import {
4
4
  reviveSmartEnums,
5
5
  serializeSmartEnums,
6
6
  setLogger
7
- } from "./chunk-SOZ6HB6K.js";
7
+ } from "./chunk-OOVDWS5T.js";
8
8
 
9
9
  // src/utilities/transport/transportRegistry.ts
10
10
  var createLevelFilteredLogger = (logger, level) => {
@@ -70,4 +70,4 @@ export {
70
70
  reviveAfterTransport,
71
71
  serializeForTransport
72
72
  };
73
- //# sourceMappingURL=chunk-CZ6TMH26.js.map
73
+ //# sourceMappingURL=chunk-6ZOLTEJT.js.map
@@ -1,3 +1,13 @@
1
+ // src/utilities/serializationMode.ts
2
+ var globalDefault;
3
+ var setDefaultSerializationMode = (mode) => {
4
+ globalDefault = mode;
5
+ };
6
+ var resetDefaultSerializationMode = () => {
7
+ globalDefault = void 0;
8
+ };
9
+ var resolveSerializationMode = (perEnum) => perEnum ?? globalDefault ?? "wrapped";
10
+
1
11
  // src/enumerations.ts
2
12
  import { capitalCase, constantCase } from "case-anything";
3
13
 
@@ -36,7 +46,7 @@ function normalizeInput(input) {
36
46
  }
37
47
  return input;
38
48
  }
39
- var finalizeEnumItem = (item, enumType, enumInstanceId) => {
49
+ var finalizeEnumItem = (item, enumType, enumInstanceId, serializeAs) => {
40
50
  Object.defineProperty(item, SMART_ENUM_ITEM, {
41
51
  value: true,
42
52
  enumerable: false
@@ -54,7 +64,13 @@ var finalizeEnumItem = (item, enumType, enumInstanceId) => {
54
64
  enumerable: false
55
65
  });
56
66
  Object.defineProperty(item, "toJSON", {
57
- value: () => ({ __smart_enum_type: enumType, value: item.value }),
67
+ value: () => {
68
+ const mode = resolveSerializationMode(serializeAs);
69
+ if (mode === "value") {
70
+ return item.value;
71
+ }
72
+ return { __smart_enum_type: enumType, value: item.value };
73
+ },
58
74
  enumerable: false
59
75
  });
60
76
  Object.defineProperty(item, "toPostgres", {
@@ -73,7 +89,7 @@ var formatProperties = (k, formatters) => formatters.reduce(
73
89
  display: capitalCase(k)
74
90
  }
75
91
  );
76
- function buildEnumFromObject(enumType, input, propertyAutoFormatters) {
92
+ function buildEnumFromObject(enumType, input, propertyAutoFormatters, serializeAs) {
77
93
  const formattersWithDefaults = [
78
94
  { key: "value", format: constantCase },
79
95
  { key: "display", format: capitalCase },
@@ -95,7 +111,8 @@ function buildEnumFromObject(enumType, input, propertyAutoFormatters) {
95
111
  const enumItem = finalizeEnumItem(
96
112
  enumItemBase,
97
113
  enumType,
98
- enumInstanceId
114
+ enumInstanceId,
115
+ serializeAs
99
116
  );
100
117
  Object.freeze(enumItem);
101
118
  rawEnumItems[typedKey] = enumItem;
@@ -121,7 +138,8 @@ function enumeration(enumType, props) {
121
138
  return buildEnumFromObject(
122
139
  enumType,
123
140
  normalized,
124
- props.propertyAutoFormatters
141
+ props.propertyAutoFormatters,
142
+ props.serializeAs
125
143
  );
126
144
  }
127
145
 
@@ -254,6 +272,8 @@ var reviveEnumField = (value, smartEnum, strict = false) => {
254
272
 
255
273
  export {
256
274
  addExtensionMethods,
275
+ setDefaultSerializationMode,
276
+ resetDefaultSerializationMode,
257
277
  enumeration,
258
278
  isSmartEnumItem,
259
279
  isSmartEnum,
@@ -264,4 +284,4 @@ export {
264
284
  reviveSmartEnums,
265
285
  reviveEnumField
266
286
  };
267
- //# sourceMappingURL=chunk-SOZ6HB6K.js.map
287
+ //# sourceMappingURL=chunk-OOVDWS5T.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utilities/serializationMode.ts","../src/enumerations.ts","../src/extensionMethods.ts","../src/types.ts","../src/utilities/typeGuards.ts","../src/utilities/logger.ts","../src/utilities/transformation.ts"],"sourcesContent":["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 { 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 {\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":";AAEA,IAAI;AAWG,IAAM,8BAA8B,CAAC,SAAkC;AAC5E,kBAAgB;AAClB;AAMO,IAAM,gCAAgC,MAAY;AACvD,kBAAgB;AAClB;AAMO,IAAM,2BAA2B,CACtC,YACsB,WAAW,iBAAiB;;;AC/BpD,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,WAAW,WAAS,UAAU,SAAS,OAAyB,OAAO;AAAA,IACvE,cAAc,WACZ,QAAQ,OAAO,SAAS,KAAuB,IAAI;AAAA,IAErD,SAAS,SAAO,UAAU,OAAO,KAAqB,KAAK;AAAA,IAC3D,YAAY,SAAQ,MAAM,OAAO,OAAO,GAAmB,IAAI;AAAA,IAE/D,OAAO,MAAM,CAAC,GAAG,SAAS;AAAA,IAC1B,QAAQ,MAAM,UAAU,IAAI,UAAQ,KAAK,KAAK;AAAA,IAC9C,MAAM,MAAM,UAAU,IAAI,UAAQ,KAAK,GAAG;AAAA,EAC5C;AACF;;;AClBO,IAAM,kBAAkB,OAAO,iBAAiB;AAChD,IAAM,gBAAgB,OAAO,eAAe;AAC5C,IAAM,aAAa,OAAO,YAAY;;;AFW7C,SAAS,eACP,OAC6B;AAC7B,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,WAAO,OAAO;AAAA,MACZ,M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,YAAM,MAAmB,CAAC;AAC1B,WAAK,IAAI,GAAG,GAAG;AACf,iBAAW,CAAC,GAAG,GAAG,KAAK,OAAO,QAAQ,CAAC,GAAG;AACxC,YAAI,CAAC,IAAI,KAAK,GAAG;AAAA,MACnB;AACA,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT;AACA,SAAO,KAAK,KAAK;AACnB;AAoBO,IAAM,kBAAkB,CAC7B,OACA,WACA,SAAS,UACa;AACtB,MAAI,OAAO,UAAU,SAAU,QAAO;AAEtC,QAAM,UAAU,UAAU,aAAa,KAAK;AAC5C,MAAI,YAAY,OAAW,QAAO;AAElC,MAAI,QAAQ;AACV,UAAM,IAAI,MAAM,uBAAuB,KAAK,UAAU,KAAK,CAAC,EAAE;AAAA,EAChE;AAEA,SAAO;AACT;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  addExtensionMethods,
3
3
  isSmartEnumItem
4
- } from "./chunk-SOZ6HB6K.js";
4
+ } from "./chunk-OOVDWS5T.js";
5
5
 
6
6
  // src/utilities/getSubsetByProp.ts
7
7
  var RESERVED_ENUM_MEMBER_KEYS = /* @__PURE__ */ new Set([
@@ -51,4 +51,4 @@ export {
51
51
  getSubsetByProp,
52
52
  subsetByProp
53
53
  };
54
- //# sourceMappingURL=chunk-3RPLSRWV.js.map
54
+ //# sourceMappingURL=chunk-RHESWOIM.js.map