@rtpaulino/entity 0.28.3 → 0.28.5
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.
- package/README.md +7 -4
- package/dist/lib/entity-definition.d.ts +13 -1
- package/dist/lib/entity-definition.d.ts.map +1 -1
- package/dist/lib/entity-definition.js +12 -1
- package/dist/lib/entity-definition.js.map +1 -1
- package/dist/lib/entity-utils.d.ts.map +1 -1
- package/dist/lib/entity-utils.js +15 -10
- package/dist/lib/entity-utils.js.map +1 -1
- package/dist/lib/primitive-deserializers.d.ts +2 -2
- package/dist/lib/primitive-deserializers.d.ts.map +1 -1
- package/dist/lib/primitive-deserializers.js +23 -2
- package/dist/lib/primitive-deserializers.js.map +1 -1
- package/dist/lib/property.d.ts +19 -0
- package/dist/lib/property.d.ts.map +1 -1
- package/dist/lib/property.js +24 -0
- package/dist/lib/property.js.map +1 -1
- package/dist/lib/test-entities.js.map +1 -1
- package/dist/lib/types.d.ts +14 -3
- package/dist/lib/types.d.ts.map +1 -1
- package/dist/lib/types.js.map +1 -1
- package/dist/lib/validation-utils.d.ts +12 -0
- package/dist/lib/validation-utils.d.ts.map +1 -1
- package/dist/lib/validation-utils.js +15 -0
- package/dist/lib/validation-utils.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ A TypeScript entity framework with decorators for metadata-driven serialization
|
|
|
7
7
|
- **Type-safe decorators** for entity properties
|
|
8
8
|
- **Serialization** via `EntityUtils.toJSON()`
|
|
9
9
|
- **Deserialization** via `EntityUtils.parse()`
|
|
10
|
-
- **Helper decorators** for common types (String, Number, Boolean, Date, BigInt, Entity, Array)
|
|
10
|
+
- **Helper decorators** for common types (String, Number, Boolean, Date, BigInt, Buffer, Entity, Array)
|
|
11
11
|
- **Nested entities** with automatic recursive handling
|
|
12
12
|
- **Optional properties** with null/undefined support
|
|
13
13
|
- **Sparse arrays** for arrays with null/undefined elements
|
|
@@ -84,6 +84,9 @@ class Example {
|
|
|
84
84
|
|
|
85
85
|
@BigIntProperty()
|
|
86
86
|
largeNumber!: bigint;
|
|
87
|
+
|
|
88
|
+
@BufferProperty()
|
|
89
|
+
payload!: Buffer; // serialized as a base64 string
|
|
87
90
|
}
|
|
88
91
|
```
|
|
89
92
|
|
|
@@ -203,7 +206,7 @@ class BadExample {
|
|
|
203
206
|
}
|
|
204
207
|
|
|
205
208
|
// This will throw:
|
|
206
|
-
// "Property 'value' has unknown type constructor. Supported types are: String, Number, Boolean, Date, BigInt, and @Entity() classes."
|
|
209
|
+
// "Property 'value' has unknown type constructor. Supported types are: String, Number, Boolean, Date, BigInt, Buffer, and @Entity() classes."
|
|
207
210
|
```
|
|
208
211
|
|
|
209
212
|
## Advanced Patterns
|
|
@@ -254,7 +257,7 @@ Serializes an entity to a plain JavaScript object.
|
|
|
254
257
|
|
|
255
258
|
- Throws error for properties with unknown types (unless `passthrough: true`)
|
|
256
259
|
- Handles nested entities recursively
|
|
257
|
-
- Converts Date to ISO string, BigInt to string
|
|
260
|
+
- Converts Date to ISO string, BigInt to string, Buffer to base64 string
|
|
258
261
|
- Preserves null/undefined for optional properties
|
|
259
262
|
|
|
260
263
|
### `EntityUtils.parse<T>(entityClass, plainObject)`
|
|
@@ -265,7 +268,7 @@ Deserializes a plain object to an entity instance.
|
|
|
265
268
|
- Validates property types match metadata
|
|
266
269
|
- Throws error for unknown types (unless `passthrough: true`)
|
|
267
270
|
- Handles nested entities recursively
|
|
268
|
-
- Converts ISO strings back to Date, strings back to BigInt
|
|
271
|
+
- Converts ISO strings back to Date, strings back to BigInt, base64 strings back to Buffer
|
|
269
272
|
|
|
270
273
|
### Property Options
|
|
271
274
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PropertyOptions, type AnyCtor } from './types.js';
|
|
2
2
|
import { EntityOptions } from './entity.js';
|
|
3
3
|
import { Problem } from './problem.js';
|
|
4
|
-
import { stringPropertyOptions, enumPropertyOptions, numberPropertyOptions, intPropertyOptions, booleanPropertyOptions, datePropertyOptions, bigIntPropertyOptions, entityPropertyOptions, arrayPropertyOptions, passthroughPropertyOptions, discriminatedEntityPropertyOptions, stringifiablePropertyOptions } from './property.js';
|
|
4
|
+
import { stringPropertyOptions, enumPropertyOptions, numberPropertyOptions, intPropertyOptions, booleanPropertyOptions, datePropertyOptions, bigIntPropertyOptions, bufferPropertyOptions, entityPropertyOptions, arrayPropertyOptions, passthroughPropertyOptions, discriminatedEntityPropertyOptions, stringifiablePropertyOptions } from './property.js';
|
|
5
5
|
import { zodPropertyOptions } from './zod-property.js';
|
|
6
6
|
/**
|
|
7
7
|
* Configuration for defining an entity schema
|
|
@@ -229,6 +229,18 @@ export declare const EntityProps: {
|
|
|
229
229
|
* })
|
|
230
230
|
*/
|
|
231
231
|
BigInt: typeof bigIntPropertyOptions;
|
|
232
|
+
/**
|
|
233
|
+
* Buffer property (serialized as base64)
|
|
234
|
+
* @example
|
|
235
|
+
* EntitySchema.define({
|
|
236
|
+
* name: 'Document',
|
|
237
|
+
* properties: {
|
|
238
|
+
* content: EntityProps.Buffer(),
|
|
239
|
+
* thumbnail: EntityProps.Buffer({ optional: true }),
|
|
240
|
+
* }
|
|
241
|
+
* })
|
|
242
|
+
*/
|
|
243
|
+
Buffer: typeof bufferPropertyOptions;
|
|
232
244
|
/**
|
|
233
245
|
* Entity property (nested entity)
|
|
234
246
|
* @example
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity-definition.d.ts","sourceRoot":"","sources":["../../src/lib/entity-definition.ts"],"names":[],"mappings":"AACA,OAAO,EAML,eAAe,EACf,KAAK,OAAO,EACb,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EACL,qBAAqB,EACrB,mBAAmB,EACnB,qBAAqB,EACrB,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,EACnB,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AG,OAAO,CAAC,CAAC,CAAC,CAAC;CACpC;
|
|
1
|
+
{"version":3,"file":"entity-definition.d.ts","sourceRoot":"","sources":["../../src/lib/entity-definition.ts"],"names":[],"mappings":"AACA,OAAO,EAML,eAAe,EACf,KAAK,OAAO,EACb,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EACL,qBAAqB,EACrB,mBAAmB,EACnB,qBAAqB,EACrB,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,EACnB,qBAAqB,EACrB,qBAAqB,EACrB,qBAAqB,EACrB,oBAAoB,EACpB,0BAA0B,EAC1B,kCAAkC,EAClC,4BAA4B,EAC7B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD;;GAEG;AACH,MAAM,WAAW,kBAAkB,CAAC,CAAC,GAAG,GAAG;IACzC;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,OAAO,CAAC,EAAE,IAAI,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IACtC;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,CAAC;IAC5C;;;OAGG;IACH,UAAU,CAAC,EAAE,KAAK,CAAC,CAAC,QAAQ,EAAE,CAAC,KAAK,OAAO,EAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;IACpE;;;;OAIG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB,CAAC,CAAC;IACpC;;OAEG;IACH,QAAQ,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IAEjC;;OAEG;IACH,KAAK,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAEj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ATA_KEY } from './types.js';
|
|
2
2
|
import { EntityRegistry } from './entity-registry.js';
|
|
3
3
|
import { EntityUtils } from './entity-utils.js';
|
|
4
|
-
import { stringPropertyOptions, enumPropertyOptions, numberPropertyOptions, intPropertyOptions, booleanPropertyOptions, datePropertyOptions, bigIntPropertyOptions, entityPropertyOptions, arrayPropertyOptions, passthroughPropertyOptions, discriminatedEntityPropertyOptions, stringifiablePropertyOptions } from './property.js';
|
|
4
|
+
import { stringPropertyOptions, enumPropertyOptions, numberPropertyOptions, intPropertyOptions, booleanPropertyOptions, datePropertyOptions, bigIntPropertyOptions, bufferPropertyOptions, entityPropertyOptions, arrayPropertyOptions, passthroughPropertyOptions, discriminatedEntityPropertyOptions, stringifiablePropertyOptions } from './property.js';
|
|
5
5
|
import { zodPropertyOptions } from './zod-property.js';
|
|
6
6
|
/**
|
|
7
7
|
* Define entity metadata on an existing class programmatically
|
|
@@ -213,6 +213,17 @@ import { zodPropertyOptions } from './zod-property.js';
|
|
|
213
213
|
* })
|
|
214
214
|
*/ BigInt: bigIntPropertyOptions,
|
|
215
215
|
/**
|
|
216
|
+
* Buffer property (serialized as base64)
|
|
217
|
+
* @example
|
|
218
|
+
* EntitySchema.define({
|
|
219
|
+
* name: 'Document',
|
|
220
|
+
* properties: {
|
|
221
|
+
* content: EntityProps.Buffer(),
|
|
222
|
+
* thumbnail: EntityProps.Buffer({ optional: true }),
|
|
223
|
+
* }
|
|
224
|
+
* })
|
|
225
|
+
*/ Buffer: bufferPropertyOptions,
|
|
226
|
+
/**
|
|
216
227
|
* Entity property (nested entity)
|
|
217
228
|
* @example
|
|
218
229
|
* const AddressSchema = EntitySchema.define({ ... });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/lib/entity-definition.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n ENTITY_METADATA_KEY,\n ENTITY_OPTIONS_METADATA_KEY,\n ENTITY_VALIDATOR_METADATA_KEY,\n PROPERTY_METADATA_KEY,\n PROPERTY_OPTIONS_METADATA_KEY,\n PropertyOptions,\n type AnyCtor,\n} from './types.js';\nimport { EntityOptions } from './entity.js';\nimport { EntityRegistry } from './entity-registry.js';\nimport { EntityUtils } from './entity-utils.js';\nimport { Problem } from './problem.js';\nimport {\n stringPropertyOptions,\n enumPropertyOptions,\n numberPropertyOptions,\n intPropertyOptions,\n booleanPropertyOptions,\n datePropertyOptions,\n bigIntPropertyOptions,\n entityPropertyOptions,\n arrayPropertyOptions,\n passthroughPropertyOptions,\n discriminatedEntityPropertyOptions,\n stringifiablePropertyOptions,\n} from './property.js';\nimport { zodPropertyOptions } from './zod-property.js';\n\n/**\n * Configuration for defining an entity schema\n */\nexport interface EntitySchemaConfig<T = any> {\n /**\n * Name for the entity (required for schema-based entities)\n */\n name: string;\n /**\n * Entity options (collection, stringifiable, etc.)\n */\n options?: Omit<EntityOptions, 'name'>;\n /**\n * Property definitions - key is property name, value is property options\n */\n properties: Record<string, PropertyOptions>;\n /**\n * Validator functions that will be attached to the entity class\n * Each function receives the entity instance and returns problems\n */\n validators?: Array<(instance: T) => Problem[] | Promise<Problem[]>>;\n /**\n * Whether to register this entity in the EntityRegistry.\n * For dynamic schemas, defaults to false to prevent memory leaks.\n * Set to true if you need discriminated entity deserialization.\n */\n register?: boolean;\n}\n\n/**\n * Wrapper object returned by EntitySchema.define() with EntityUtils methods\n */\nexport interface EntitySchemaWrapper<T> {\n /**\n * The generated entity class\n */\n readonly entityClass: AnyCtor<T>;\n\n /**\n * Parse data into an entity instance\n */\n parse(data: unknown): Promise<T>;\n\n /**\n * Parse data into an entity instance without throwing\n */\n safeParse(\n data: unknown,\n ): Promise<\n | { success: true; data: T; problems: Problem[] }\n | { success: false; data: undefined; problems: Problem[] }\n >;\n\n /**\n * Parse only present properties without throwing\n */\n parsePartial(data: unknown): Promise<Partial<T>>;\n\n /**\n * Parse only present properties without throwing\n */\n safeParsePartial(\n data: unknown,\n ): Promise<\n | { success: true; data: Partial<T>; problems: Problem[] }\n | { success: false; data: undefined; problems: Problem[] }\n >;\n\n /**\n * Serialize entity instance to plain object\n */\n serialize(instance: T): unknown;\n\n /**\n * Update entity instance with new data\n */\n update(instance: T, data: unknown): Promise<T>;\n\n /**\n * Update entity instance with new data without throwing\n */\n safeUpdate(\n instance: T,\n data: unknown,\n ): Promise<\n | { success: true; data: T; problems: Problem[] }\n | { success: false; data: T; problems: Problem[] }\n >;\n\n /**\n * Validate entity instance\n */\n validate(instance: T): Promise<Problem[]>;\n\n /**\n * Check if two instances are equal\n */\n equals(a: T, b: T): boolean;\n\n /**\n * Get differences between two instances\n */\n diff(a: T, b: T): Record<string, { from: unknown; to: unknown }>;\n\n /**\n * Get changed values as partial object\n */\n getChanges(a: T, b: T): Partial<T>;\n}\n\n/**\n * Define entity metadata on an existing class programmatically\n * This sets the same metadata that @Entity() and @Property() decorators would set\n *\n * @param entityClass - The class to define as an entity\n * @param config - Configuration with properties, options, and validators\n * @internal\n */\nfunction defineEntity<T>(\n entityClass: AnyCtor<T>,\n config: EntitySchemaConfig<T>,\n): void {\n const entityName = config.name;\n\n // 1. Mark as entity\n Reflect.defineMetadata(ENTITY_METADATA_KEY, true, entityClass);\n\n // 2. Set entity options with resolved name\n const entityOptions: EntityOptions = {\n ...config.options,\n name: entityName,\n };\n Reflect.defineMetadata(\n ENTITY_OPTIONS_METADATA_KEY,\n entityOptions,\n entityClass,\n );\n\n // 3. Register in EntityRegistry if enabled\n if (config.register) {\n EntityRegistry.register(entityName, entityClass);\n }\n\n // 4. Set property keys\n const propertyKeys = Object.keys(config.properties);\n Reflect.defineMetadata(\n PROPERTY_METADATA_KEY,\n propertyKeys,\n entityClass.prototype,\n );\n\n // 5. Set property options\n Reflect.defineMetadata(\n PROPERTY_OPTIONS_METADATA_KEY,\n config.properties,\n entityClass.prototype,\n );\n\n // 6. Set up validators if provided\n if (config.validators && config.validators.length > 0) {\n const validatorMethodNames: string[] = [];\n\n config.validators.forEach((validatorFn, index) => {\n const methodName = `__dynamicValidator${index}`;\n validatorMethodNames.push(methodName);\n\n // Attach validator as instance method that uses 'this'\n (entityClass.prototype as any)[methodName] = function ():\n | Problem[]\n | Promise<Problem[]> {\n return validatorFn(this);\n };\n });\n\n Reflect.defineMetadata(\n ENTITY_VALIDATOR_METADATA_KEY,\n validatorMethodNames,\n entityClass.prototype,\n );\n }\n}\n\n/**\n * Factory for creating schema-based entities without pre-defining a class\n */\nexport class EntitySchema {\n /**\n * Define a new entity schema and return a wrapper with EntityUtils methods\n *\n * @param config - Schema configuration with name, properties, options, and validators\n * @returns Wrapper object with parse, serialize, validate, etc. methods\n *\n * @example\n * ```typescript\n * const UserSchema = EntitySchema.define({\n * name: 'User',\n * properties: {\n * name: { type: () => String },\n * age: { type: () => Number, optional: true },\n * tags: { type: () => String, array: true },\n * },\n * validators: [\n * (user) => user.name.length < 2 ? [{ path: 'name', message: 'Too short' }] : []\n * ]\n * });\n *\n * const user = await UserSchema.parse({ name: 'John', age: 30, tags: ['admin'] });\n * const serialized = UserSchema.serialize(user);\n * const isValid = (await UserSchema.validate(user)).length === 0;\n * ```\n */\n static define<T extends object = any>(\n config: EntitySchemaConfig<T>,\n ): EntitySchemaWrapper<T> {\n // Generate anonymous entity class\n const entityClass = class {\n constructor(data: any) {\n Object.assign(this, data);\n }\n } as unknown as AnyCtor<T>;\n\n // Define entity metadata\n defineEntity(entityClass, {\n name: config.name,\n options: config.options,\n properties: config.properties,\n validators: config.validators,\n register: config.register ?? false, // Default to false for dynamic schemas to prevent memory leaks\n });\n\n // Create wrapper with EntityUtils methods\n const wrapper: EntitySchemaWrapper<T> = {\n entityClass,\n\n async parse(data: unknown): Promise<T> {\n return EntityUtils.parse(entityClass as any, data) as Promise<T>;\n },\n\n async safeParse(data: unknown) {\n return EntityUtils.safeParse(entityClass as any, data) as Promise<\n | { success: true; data: T; problems: Problem[] }\n | { success: false; data: undefined; problems: Problem[] }\n >;\n },\n\n async parsePartial(data: unknown): Promise<Partial<T>> {\n return EntityUtils.partialParse(entityClass as any, data) as Promise<\n Partial<T>\n >;\n },\n\n async safeParsePartial(data: unknown) {\n return EntityUtils.safePartialParse(\n entityClass as any,\n data,\n ) as unknown as Promise<\n | { success: true; data: Partial<T>; problems: Problem[] }\n | { success: false; data: undefined; problems: Problem[] }\n >;\n },\n\n serialize(instance: T): unknown {\n return EntityUtils.toJSON(instance as any);\n },\n\n async update(instance: T, data: unknown): Promise<T> {\n return EntityUtils.update(instance as any, data as any) as Promise<T>;\n },\n\n async safeUpdate(instance: T, data: unknown) {\n return EntityUtils.safeUpdate(instance as any, data as any) as Promise<\n | { success: true; data: T; problems: Problem[] }\n | { success: false; data: T; problems: Problem[] }\n >;\n },\n\n async validate(instance: T): Promise<Problem[]> {\n return EntityUtils.validate(instance as any);\n },\n\n equals(a: T, b: T): boolean {\n return EntityUtils.equals(a as any, b as any);\n },\n\n diff(a: T, b: T): Record<string, { from: unknown; to: unknown }> {\n const diffs = EntityUtils.diff(a as any, b as any);\n const result: Record<string, { from: unknown; to: unknown }> = {};\n for (const diff of diffs) {\n result[diff.property] = { from: diff.oldValue, to: diff.newValue };\n }\n return result;\n },\n\n getChanges(a: T, b: T): Partial<T> {\n return EntityUtils.changes(a as any, b as any) as Partial<T>;\n },\n };\n\n return wrapper;\n }\n}\n\n/**\n * Property definition helpers for EntitySchema\n * These mirror the decorator-based property helpers but return PropertyOptions objects\n */\nexport const EntityProps = {\n /**\n * String property with optional validation\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * name: EntityProps.String({ minLength: 2, maxLength: 50 }),\n * email: EntityProps.String({ pattern: /^.+@.+\\..+$/ }),\n * }\n * })\n */\n String: stringPropertyOptions,\n\n /**\n * Enum property (validates string against enum values)\n * @example\n * enum Status { Active = 'active', Inactive = 'inactive' }\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * status: EntityProps.Enum(Status),\n * }\n * })\n */\n Enum: enumPropertyOptions,\n\n /**\n * Number property with optional min/max validation\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * age: EntityProps.Number({ min: 0, max: 150 }),\n * score: EntityProps.Number({ optional: true }),\n * }\n * })\n */\n Number: numberPropertyOptions,\n\n /**\n * Integer property (number that must be an integer)\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * age: EntityProps.Int({ min: 0 }),\n * }\n * })\n */\n Int: intPropertyOptions,\n\n /**\n * Boolean property\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * isActive: EntityProps.Boolean(),\n * emailVerified: EntityProps.Boolean({ optional: true }),\n * }\n * })\n */\n Boolean: booleanPropertyOptions,\n\n /**\n * Date property\n * @example\n * EntitySchema.define({\n * name: 'Event',\n * properties: {\n * createdAt: EntityProps.Date(),\n * scheduledFor: EntityProps.Date({ optional: true }),\n * }\n * })\n */\n Date: datePropertyOptions,\n\n /**\n * BigInt property\n * @example\n * EntitySchema.define({\n * name: 'Transaction',\n * properties: {\n * amount: EntityProps.BigInt(),\n * }\n * })\n */\n BigInt: bigIntPropertyOptions,\n\n /**\n * Entity property (nested entity)\n * @example\n * const AddressSchema = EntitySchema.define({ ... });\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * address: EntityProps.Entity(() => AddressSchema.entityClass),\n * }\n * })\n */\n Entity: entityPropertyOptions,\n\n /**\n * Array property\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * tags: EntityProps.Array(() => String),\n * addresses: EntityProps.Array(() => AddressSchema.entityClass),\n * }\n * })\n */\n Array: arrayPropertyOptions,\n\n /**\n * Passthrough property (no deserialization/validation)\n * @example\n * EntitySchema.define({\n * name: 'Config',\n * properties: {\n * metadata: EntityProps.Passthrough(),\n * }\n * })\n */\n Passthrough: passthroughPropertyOptions,\n\n /**\n * Zod schema property (validates using Zod schema)\n * @example\n * import { z } from 'zod';\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * data: EntityProps.Zod(z.object({\n * name: z.string().min(3),\n * age: z.number().int().min(0)\n * })),\n * }\n * })\n */\n Zod: zodPropertyOptions,\n\n /**\n * Discriminated entity property (for polymorphic entities with discriminator)\n * @example\n * EntitySchema.define({\n * name: 'Shape',\n * properties: {\n * shape: EntityProps.DiscriminatedEntity({ discriminatorProperty: 'type' }),\n * }\n * })\n */\n DiscriminatedEntity: discriminatedEntityPropertyOptions,\n\n /**\n * Stringifiable property (for types with toString() and static parse())\n * @example\n * class CustomId {\n * constructor(public value: string) {}\n * toString() { return this.value; }\n * static parse(str: string) { return new CustomId(str); }\n * }\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * id: EntityProps.Stringifiable(() => CustomId),\n * }\n * })\n */\n Stringifiable: stringifiablePropertyOptions,\n};\n"],"names":["ENTITY_METADATA_KEY","ENTITY_OPTIONS_METADATA_KEY","ENTITY_VALIDATOR_METADATA_KEY","PROPERTY_METADATA_KEY","PROPERTY_OPTIONS_METADATA_KEY","EntityRegistry","EntityUtils","stringPropertyOptions","enumPropertyOptions","numberPropertyOptions","intPropertyOptions","booleanPropertyOptions","datePropertyOptions","bigIntPropertyOptions","entityPropertyOptions","arrayPropertyOptions","passthroughPropertyOptions","discriminatedEntityPropertyOptions","stringifiablePropertyOptions","zodPropertyOptions","defineEntity","entityClass","config","entityName","name","Reflect","defineMetadata","entityOptions","options","register","propertyKeys","Object","keys","properties","prototype","validators","length","validatorMethodNames","forEach","validatorFn","index","methodName","push","EntitySchema","define","data","assign","wrapper","parse","safeParse","parsePartial","partialParse","safeParsePartial","safePartialParse","serialize","instance","toJSON","update","safeUpdate","validate","equals","a","b","diff","diffs","result","property","from","oldValue","to","newValue","getChanges","changes","EntityProps","String","Enum","Number","Int","Boolean","Date","BigInt","Entity","Array","Passthrough","Zod","DiscriminatedEntity","Stringifiable"],"mappings":"AAAA,qDAAqD,GACrD,SACEA,mBAAmB,EACnBC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,qBAAqB,EACrBC,6BAA6B,QAGxB,aAAa;AAEpB,SAASC,cAAc,QAAQ,uBAAuB;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AEAC,MAAKF,CAAI,EAAEC,CAAI;gBACb,MAAME,QAAQ1D,YAAYyD,IAAI,CAACF,GAAUC;gBACzC,MAAMG,SAAyD,CAAC;gBAChE,KAAK,MAAMF,QAAQC,MAAO;oBACxBC,MAAM,CAACF,KAAKG,QAAQ,CAAC,GAAG;wBAAEC,MAAMJ,KAAKK,QAAQ;wBAAEC,IAAIN,KAAKO,QAAQ;oBAAC;gBACnE;gBACA,OAAOL;YACT;YAEAM,YAAWV,CAAI,EAAEC,CAAI;gBACnB,OAAOxD,YAAYkE,OAAO,CAACX,GAAUC;YACvC;QACF;QAEA,OAAOf;IACT;AACF;AAEA;;;CAGC,GACD,OAAO,MAAM0B,cAAc;IACzB;;;;;;;;;;GAUC,GACDC,QAAQnE;IAER;;;;;;;;;;GAUC,GACDoE,MAAMnE;IAEN;;;;;;;;;;GAUC,GACDoE,QAAQnE;IAER;;;;;;;;;GASC,GACDoE,KAAKnE;IAEL;;;;;;;;;;GAUC,GACDoE,SAASnE;IAET;;;;;;;;;;GAUC,GACDoE,MAAMnE;IAEN;;;;;;;;;GASC,GACDoE,QAAQnE;IAER;;;;;;;;;;GAUC,GACDoE,QAAQnE;IAER;;;;;;;;;;GAUC,GACDoE,OAAOnE;IAEP;;;;;;;;;GASC,GACDoE,aAAanE;IAEb;;;;;;;;;;;;;GAaC,GACDoE,KAAKjE;IAEL;;;;;;;;;GASC,GACDkE,qBAAqBpE;IAErB;;;;;;;;;;;;;;GAcC,GACDqE,eAAepE;AACjB,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/lib/entity-definition.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport {\n ENTITY_METADATA_KEY,\n ENTITY_OPTIONS_METADATA_KEY,\n ENTITY_VALIDATOR_METADATA_KEY,\n PROPERTY_METADATA_KEY,\n PROPERTY_OPTIONS_METADATA_KEY,\n PropertyOptions,\n type AnyCtor,\n} from './types.js';\nimport { EntityOptions } from './entity.js';\nimport { EntityRegistry } from './entity-registry.js';\nimport { EntityUtils } from './entity-utils.js';\nimport { Problem } from './problem.js';\nimport {\n stringPropertyOptions,\n enumPropertyOptions,\n numberPropertyOptions,\n intPropertyOptions,\n booleanPropertyOptions,\n datePropertyOptions,\n bigIntPropertyOptions,\n bufferPropertyOptions,\n entityPropertyOptions,\n arrayPropertyOptions,\n passthroughPropertyOptions,\n discriminatedEntityPropertyOptions,\n stringifiablePropertyOptions,\n} from './property.js';\nimport { zodPropertyOptions } from './zod-property.js';\n\n/**\n * Configuration for defining an entity schema\n */\nexport interface EntitySchemaConfig<T = any> {\n /**\n * Name for the entity (required for schema-based entities)\n */\n name: string;\n /**\n * Entity options (collection, stringifiable, etc.)\n */\n options?: Omit<EntityOptions, 'name'>;\n /**\n * Property definitions - key is property name, value is property options\n */\n properties: Record<string, PropertyOptions>;\n /**\n * Validator functions that will be attached to the entity class\n * Each function receives the entity instance and returns problems\n */\n validators?: Array<(instance: T) => Problem[] | Promise<Problem[]>>;\n /**\n * Whether to register this entity in the EntityRegistry.\n * For dynamic schemas, defaults to false to prevent memory leaks.\n * Set to true if you need discriminated entity deserialization.\n */\n register?: boolean;\n}\n\n/**\n * Wrapper object returned by EntitySchema.define() with EntityUtils methods\n */\nexport interface EntitySchemaWrapper<T> {\n /**\n * The generated entity class\n */\n readonly entityClass: AnyCtor<T>;\n\n /**\n * Parse data into an entity instance\n */\n parse(data: unknown): Promise<T>;\n\n /**\n * Parse data into an entity instance without throwing\n */\n safeParse(\n data: unknown,\n ): Promise<\n | { success: true; data: T; problems: Problem[] }\n | { success: false; data: undefined; problems: Problem[] }\n >;\n\n /**\n * Parse only present properties without throwing\n */\n parsePartial(data: unknown): Promise<Partial<T>>;\n\n /**\n * Parse only present properties without throwing\n */\n safeParsePartial(\n data: unknown,\n ): Promise<\n | { success: true; data: Partial<T>; problems: Problem[] }\n | { success: false; data: undefined; problems: Problem[] }\n >;\n\n /**\n * Serialize entity instance to plain object\n */\n serialize(instance: T): unknown;\n\n /**\n * Update entity instance with new data\n */\n update(instance: T, data: unknown): Promise<T>;\n\n /**\n * Update entity instance with new data without throwing\n */\n safeUpdate(\n instance: T,\n data: unknown,\n ): Promise<\n | { success: true; data: T; problems: Problem[] }\n | { success: false; data: T; problems: Problem[] }\n >;\n\n /**\n * Validate entity instance\n */\n validate(instance: T): Promise<Problem[]>;\n\n /**\n * Check if two instances are equal\n */\n equals(a: T, b: T): boolean;\n\n /**\n * Get differences between two instances\n */\n diff(a: T, b: T): Record<string, { from: unknown; to: unknown }>;\n\n /**\n * Get changed values as partial object\n */\n getChanges(a: T, b: T): Partial<T>;\n}\n\n/**\n * Define entity metadata on an existing class programmatically\n * This sets the same metadata that @Entity() and @Property() decorators would set\n *\n * @param entityClass - The class to define as an entity\n * @param config - Configuration with properties, options, and validators\n * @internal\n */\nfunction defineEntity<T>(\n entityClass: AnyCtor<T>,\n config: EntitySchemaConfig<T>,\n): void {\n const entityName = config.name;\n\n // 1. Mark as entity\n Reflect.defineMetadata(ENTITY_METADATA_KEY, true, entityClass);\n\n // 2. Set entity options with resolved name\n const entityOptions: EntityOptions = {\n ...config.options,\n name: entityName,\n };\n Reflect.defineMetadata(\n ENTITY_OPTIONS_METADATA_KEY,\n entityOptions,\n entityClass,\n );\n\n // 3. Register in EntityRegistry if enabled\n if (config.register) {\n EntityRegistry.register(entityName, entityClass);\n }\n\n // 4. Set property keys\n const propertyKeys = Object.keys(config.properties);\n Reflect.defineMetadata(\n PROPERTY_METADATA_KEY,\n propertyKeys,\n entityClass.prototype,\n );\n\n // 5. Set property options\n Reflect.defineMetadata(\n PROPERTY_OPTIONS_METADATA_KEY,\n config.properties,\n entityClass.prototype,\n );\n\n // 6. Set up validators if provided\n if (config.validators && config.validators.length > 0) {\n const validatorMethodNames: string[] = [];\n\n config.validators.forEach((validatorFn, index) => {\n const methodName = `__dynamicValidator${index}`;\n validatorMethodNames.push(methodName);\n\n // Attach validator as instance method that uses 'this'\n (entityClass.prototype as any)[methodName] = function ():\n Problem[] | Promise<Problem[]> {\n return validatorFn(this);\n };\n });\n\n Reflect.defineMetadata(\n ENTITY_VALIDATOR_METADATA_KEY,\n validatorMethodNames,\n entityClass.prototype,\n );\n }\n}\n\n/**\n * Factory for creating schema-based entities without pre-defining a class\n */\nexport class EntitySchema {\n /**\n * Define a new entity schema and return a wrapper with EntityUtils methods\n *\n * @param config - Schema configuration with name, properties, options, and validators\n * @returns Wrapper object with parse, serialize, validate, etc. methods\n *\n * @example\n * ```typescript\n * const UserSchema = EntitySchema.define({\n * name: 'User',\n * properties: {\n * name: { type: () => String },\n * age: { type: () => Number, optional: true },\n * tags: { type: () => String, array: true },\n * },\n * validators: [\n * (user) => user.name.length < 2 ? [{ path: 'name', message: 'Too short' }] : []\n * ]\n * });\n *\n * const user = await UserSchema.parse({ name: 'John', age: 30, tags: ['admin'] });\n * const serialized = UserSchema.serialize(user);\n * const isValid = (await UserSchema.validate(user)).length === 0;\n * ```\n */\n static define<T extends object = any>(\n config: EntitySchemaConfig<T>,\n ): EntitySchemaWrapper<T> {\n // Generate anonymous entity class\n const entityClass = class {\n constructor(data: any) {\n Object.assign(this, data);\n }\n } as unknown as AnyCtor<T>;\n\n // Define entity metadata\n defineEntity(entityClass, {\n name: config.name,\n options: config.options,\n properties: config.properties,\n validators: config.validators,\n register: config.register ?? false, // Default to false for dynamic schemas to prevent memory leaks\n });\n\n // Create wrapper with EntityUtils methods\n const wrapper: EntitySchemaWrapper<T> = {\n entityClass,\n\n async parse(data: unknown): Promise<T> {\n return EntityUtils.parse(entityClass as any, data) as Promise<T>;\n },\n\n async safeParse(data: unknown) {\n return EntityUtils.safeParse(entityClass as any, data) as Promise<\n | { success: true; data: T; problems: Problem[] }\n | { success: false; data: undefined; problems: Problem[] }\n >;\n },\n\n async parsePartial(data: unknown): Promise<Partial<T>> {\n return EntityUtils.partialParse(entityClass as any, data) as Promise<\n Partial<T>\n >;\n },\n\n async safeParsePartial(data: unknown) {\n return EntityUtils.safePartialParse(\n entityClass as any,\n data,\n ) as unknown as Promise<\n | { success: true; data: Partial<T>; problems: Problem[] }\n | { success: false; data: undefined; problems: Problem[] }\n >;\n },\n\n serialize(instance: T): unknown {\n return EntityUtils.toJSON(instance as any);\n },\n\n async update(instance: T, data: unknown): Promise<T> {\n return EntityUtils.update(instance as any, data as any) as Promise<T>;\n },\n\n async safeUpdate(instance: T, data: unknown) {\n return EntityUtils.safeUpdate(instance as any, data as any) as Promise<\n | { success: true; data: T; problems: Problem[] }\n | { success: false; data: T; problems: Problem[] }\n >;\n },\n\n async validate(instance: T): Promise<Problem[]> {\n return EntityUtils.validate(instance as any);\n },\n\n equals(a: T, b: T): boolean {\n return EntityUtils.equals(a as any, b as any);\n },\n\n diff(a: T, b: T): Record<string, { from: unknown; to: unknown }> {\n const diffs = EntityUtils.diff(a as any, b as any);\n const result: Record<string, { from: unknown; to: unknown }> = {};\n for (const diff of diffs) {\n result[diff.property] = { from: diff.oldValue, to: diff.newValue };\n }\n return result;\n },\n\n getChanges(a: T, b: T): Partial<T> {\n return EntityUtils.changes(a as any, b as any) as Partial<T>;\n },\n };\n\n return wrapper;\n }\n}\n\n/**\n * Property definition helpers for EntitySchema\n * These mirror the decorator-based property helpers but return PropertyOptions objects\n */\nexport const EntityProps = {\n /**\n * String property with optional validation\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * name: EntityProps.String({ minLength: 2, maxLength: 50 }),\n * email: EntityProps.String({ pattern: /^.+@.+\\..+$/ }),\n * }\n * })\n */\n String: stringPropertyOptions,\n\n /**\n * Enum property (validates string against enum values)\n * @example\n * enum Status { Active = 'active', Inactive = 'inactive' }\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * status: EntityProps.Enum(Status),\n * }\n * })\n */\n Enum: enumPropertyOptions,\n\n /**\n * Number property with optional min/max validation\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * age: EntityProps.Number({ min: 0, max: 150 }),\n * score: EntityProps.Number({ optional: true }),\n * }\n * })\n */\n Number: numberPropertyOptions,\n\n /**\n * Integer property (number that must be an integer)\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * age: EntityProps.Int({ min: 0 }),\n * }\n * })\n */\n Int: intPropertyOptions,\n\n /**\n * Boolean property\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * isActive: EntityProps.Boolean(),\n * emailVerified: EntityProps.Boolean({ optional: true }),\n * }\n * })\n */\n Boolean: booleanPropertyOptions,\n\n /**\n * Date property\n * @example\n * EntitySchema.define({\n * name: 'Event',\n * properties: {\n * createdAt: EntityProps.Date(),\n * scheduledFor: EntityProps.Date({ optional: true }),\n * }\n * })\n */\n Date: datePropertyOptions,\n\n /**\n * BigInt property\n * @example\n * EntitySchema.define({\n * name: 'Transaction',\n * properties: {\n * amount: EntityProps.BigInt(),\n * }\n * })\n */\n BigInt: bigIntPropertyOptions,\n\n /**\n * Buffer property (serialized as base64)\n * @example\n * EntitySchema.define({\n * name: 'Document',\n * properties: {\n * content: EntityProps.Buffer(),\n * thumbnail: EntityProps.Buffer({ optional: true }),\n * }\n * })\n */\n Buffer: bufferPropertyOptions,\n\n /**\n * Entity property (nested entity)\n * @example\n * const AddressSchema = EntitySchema.define({ ... });\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * address: EntityProps.Entity(() => AddressSchema.entityClass),\n * }\n * })\n */\n Entity: entityPropertyOptions,\n\n /**\n * Array property\n * @example\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * tags: EntityProps.Array(() => String),\n * addresses: EntityProps.Array(() => AddressSchema.entityClass),\n * }\n * })\n */\n Array: arrayPropertyOptions,\n\n /**\n * Passthrough property (no deserialization/validation)\n * @example\n * EntitySchema.define({\n * name: 'Config',\n * properties: {\n * metadata: EntityProps.Passthrough(),\n * }\n * })\n */\n Passthrough: passthroughPropertyOptions,\n\n /**\n * Zod schema property (validates using Zod schema)\n * @example\n * import { z } from 'zod';\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * data: EntityProps.Zod(z.object({\n * name: z.string().min(3),\n * age: z.number().int().min(0)\n * })),\n * }\n * })\n */\n Zod: zodPropertyOptions,\n\n /**\n * Discriminated entity property (for polymorphic entities with discriminator)\n * @example\n * EntitySchema.define({\n * name: 'Shape',\n * properties: {\n * shape: EntityProps.DiscriminatedEntity({ discriminatorProperty: 'type' }),\n * }\n * })\n */\n DiscriminatedEntity: discriminatedEntityPropertyOptions,\n\n /**\n * Stringifiable property (for types with toString() and static parse())\n * @example\n * class CustomId {\n * constructor(public value: string) {}\n * toString() { return this.value; }\n * static parse(str: string) { return new CustomId(str); }\n * }\n * EntitySchema.define({\n * name: 'User',\n * properties: {\n * id: EntityProps.Stringifiable(() => CustomId),\n * }\n * })\n */\n Stringifiable: stringifiablePropertyOptions,\n};\n"],"names":["ENTITY_METADATA_KEY","ENTITY_OPTIONS_METADATA_KEY","ENTITY_VALIDATOR_METADATA_KEY","PROPERTY_METADATA_KEY","PROPERTY_OPTIONS_METADATA_KEY","EntityRegistry","EntityUtils","stringPropertyOptions","enumPropertyOptions","numberPropertyOptions","intPropertyOptions","booleanPropertyOptions","datePropertyOptions","bigIntPropertyOptions","bufferPropertyOptions","entityPropertyOptions","arrayPropertyOptions","passthroughPropertyOptions","discriminatedEntityPropertyOptions","stringifiablePropertyOptions","zodPropertyOptions","defineEntity","entityClass","config","entityName","name","Reflect","defineMetadata","entityOptions","options","register","propertyKeys","Object","keys","properties","prototype","validators","length","validatorMethodNames","forEach","validatorFn","index","methodName","push","EntitySchema","define","data","assign","wrapper","parse","safeParse","parsePartial","partialParse","safeParsePartial","safePartialParse","serialize","instance","toJSON","update","safeUpdate","validate","equals","a","b","diff","diffs","result","property","from","oldValue","to","newValue","getChanges","changes","EntityProps","String","Enum","Number","Int","Boolean","Date","BigInt","Buffer","Entity","Array","Passthrough","Zod","DiscriminatedEntity","Stringifiable"],"mappings":"AAAA,qDAAqD,GACrD,SACEA,mBAAmB,EACnBC,2BAA2B,EAC3BC,6BAA6B,EAC7BC,q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C9B;YAEAK,QAAOC,CAAI,EAAEC,CAAI;gBACf,OAAOzD,YAAYuD,MAAM,CAACC,GAAUC;YACtC;YAEAC,MAAKF,CAAI,EAAEC,CAAI;gBACb,MAAME,QAAQ3D,YAAY0D,IAAI,CAACF,GAAUC;gBACzC,MAAMG,SAAyD,CAAC;gBAChE,KAAK,MAAMF,QAAQC,MAAO;oBACxBC,MAAM,CAACF,KAAKG,QAAQ,CAAC,GAAG;wBAAEC,MAAMJ,KAAKK,QAAQ;wBAAEC,IAAIN,KAAKO,QAAQ;oBAAC;gBACnE;gBACA,OAAOL;YACT;YAEAM,YAAWV,CAAI,EAAEC,CAAI;gBACnB,OAAOzD,YAAYmE,OAAO,CAACX,GAAUC;YACvC;QACF;QAEA,OAAOf;IACT;AACF;AAEA;;;CAGC,GACD,OAAO,MAAM0B,cAAc;IACzB;;;;;;;;;;GAUC,GACDC,QAAQpE;IAER;;;;;;;;;;GAUC,GACDqE,MAAMpE;IAEN;;;;;;;;;;GAUC,GACDqE,QAAQpE;IAER;;;;;;;;;GASC,GACDqE,KAAKpE;IAEL;;;;;;;;;;GAUC,GACDqE,SAASpE;IAET;;;;;;;;;;GAUC,GACDqE,MAAMpE;IAEN;;;;;;;;;GASC,GACDqE,QAAQpE;IAER;;;;;;;;;;GAUC,GACDqE,QAAQpE;IAER;;;;;;;;;;GAUC,GACDqE,QAAQpE;IAER;;;;;;;;;;GAUC,GACDqE,OAAOpE;IAEP;;;;;;;;;GASC,GACDqE,aAAapE;IAEb;;;;;;;;;;;;;GAaC,GACDqE,KAAKlE;IAEL;;;;;;;;;GASC,GACDmE,qBAAqBrE;IAErB;;;;;;;;;;;;;;GAcC,GACDsE,eAAerE;AACjB,EAAE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"entity-utils.d.ts","sourceRoot":"","sources":["../../src/lib/entity-utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAIL,YAAY,EAIZ,eAAe,EAEf,mBAAmB,EACpB,M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AAO,EAAE,CAAC;IAuBxE;;;;;;;;;;;;;;;;;OAiBG;IACH,MAAM,CAAC,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,OAAO,EAAE;IAI5D;;;;;;;;;;;;;;;OAeG;IACH,MAAM,CAAC,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,IAAI;IAQ5E;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,OAAO;IAI1D;;;;;;;;;;;;;;;OAeG;IACH,MAAM,CAAC,WAAW,CAAC,CAAC,SAAS,MAAM,EACjC,QAAQ,EAAE,CAAC,EACX,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,GAC5C,IAAI;IAQP;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,mBAAmB;CA6BnC"}
|
package/dist/lib/entity-utils.js
CHANGED
|
@@ -4,7 +4,7 @@ import { EntityDI } from './entity-di.js';
|
|
|
4
4
|
import { isEqualWith } from 'lodash-es';
|
|
5
5
|
import { ValidationError } from './validation-error.js';
|
|
6
6
|
import { Problem } from './problem.js';
|
|
7
|
-
import { prependArrayIndex, prependPropertyPath, createValidationError } from './validation-utils.js';
|
|
7
|
+
import { prependArrayIndex, prependPropertyPath, createValidationError, redactProblems, REDACTED_MESSAGE } from './validation-utils.js';
|
|
8
8
|
import { isPrimitiveConstructor, deserializePrimitive } from './primitive-deserializers.js';
|
|
9
9
|
import { ok } from 'assert';
|
|
10
10
|
import { EntityRegistry } from './entity-registry.js';
|
|
@@ -387,6 +387,9 @@ export class EntityUtils {
|
|
|
387
387
|
if (typeof value === 'bigint') {
|
|
388
388
|
return value.toString();
|
|
389
389
|
}
|
|
390
|
+
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
|
|
391
|
+
return value.toString('base64');
|
|
392
|
+
}
|
|
390
393
|
if (this.isEntity(value)) {
|
|
391
394
|
const serialized = this.toJSON(value);
|
|
392
395
|
// If this is a discriminated entity property, add the discriminator inline
|
|
@@ -495,18 +498,20 @@ export class EntityUtils {
|
|
|
495
498
|
strict
|
|
496
499
|
}, deserializeContext);
|
|
497
500
|
} catch (error) {
|
|
501
|
+
const isSensitive = propertyOptions.sensitive === true;
|
|
498
502
|
if (error instanceof ValidationError) {
|
|
499
503
|
const isWrapperProperty = wrapperPropertyName === key;
|
|
504
|
+
const errorProblems = isSensitive ? redactProblems(error.problems) : error.problems;
|
|
500
505
|
if (isWrapperProperty) {
|
|
501
|
-
hardProblems.push(...
|
|
506
|
+
hardProblems.push(...errorProblems);
|
|
502
507
|
} else {
|
|
503
|
-
const problems = prependPropertyPath(key,
|
|
508
|
+
const problems = prependPropertyPath(key, errorProblems);
|
|
504
509
|
hardProblems.push(...problems);
|
|
505
510
|
}
|
|
506
511
|
} else if (error instanceof Error) {
|
|
507
512
|
hardProblems.push(new Problem({
|
|
508
513
|
property: wrapperPropertyName === key ? '' : key,
|
|
509
|
-
message: error.message
|
|
514
|
+
message: isSensitive ? REDACTED_MESSAGE : error.message
|
|
510
515
|
}));
|
|
511
516
|
} else {
|
|
512
517
|
throw error;
|
|
@@ -946,7 +951,7 @@ export class EntityUtils {
|
|
|
946
951
|
if (this.isEntity(typeConstructor)) {
|
|
947
952
|
return await this.parse(typeConstructor, value, parseOptions);
|
|
948
953
|
}
|
|
949
|
-
throw createValidationError(`Has unknown type constructor. Supported types are: String, Number, Boolean, Date, BigInt, and @Entity() classes. Use passthrough: true to explicitly allow unknown types.`);
|
|
954
|
+
throw createValidationError(`Has unknown type constructor. Supported types are: String, Number, Boolean, Date, BigInt, Buffer, and @Entity() classes. Use passthrough: true to explicitly allow unknown types.`);
|
|
950
955
|
}
|
|
951
956
|
/**
|
|
952
957
|
* Deserializes a discriminated entity value by reading the discriminator and looking up the entity class
|
|
@@ -974,7 +979,7 @@ export class EntityUtils {
|
|
|
974
979
|
* Validates a property value by running validators and nested entity validation.
|
|
975
980
|
* Prepends the property path to all returned problems.
|
|
976
981
|
* @private
|
|
977
|
-
*/ static async validatePropertyValue(propertyPath, value, validators) {
|
|
982
|
+
*/ static async validatePropertyValue(propertyPath, value, validators, sensitive = false) {
|
|
978
983
|
const problems = [];
|
|
979
984
|
if (validators) {
|
|
980
985
|
for (const validator of validators){
|
|
@@ -982,7 +987,7 @@ export class EntityUtils {
|
|
|
982
987
|
value
|
|
983
988
|
});
|
|
984
989
|
if (validatorProblems.length > 0) {
|
|
985
|
-
const prepended = prependPropertyPath(propertyPath, validatorProblems);
|
|
990
|
+
const prepended = prependPropertyPath(propertyPath, sensitive ? redactProblems(validatorProblems) : validatorProblems);
|
|
986
991
|
problems.push(...prepended);
|
|
987
992
|
}
|
|
988
993
|
}
|
|
@@ -1014,7 +1019,7 @@ export class EntityUtils {
|
|
|
1014
1019
|
const isArray = options?.array === true;
|
|
1015
1020
|
const isPassthrough = options?.passthrough === true;
|
|
1016
1021
|
if (isPassthrough || !isArray) {
|
|
1017
|
-
const valueProblems = await this.validatePropertyValue(key, value, options.validators);
|
|
1022
|
+
const valueProblems = await this.validatePropertyValue(key, value, options.validators, options.sensitive === true);
|
|
1018
1023
|
problems.push(...valueProblems);
|
|
1019
1024
|
} else {
|
|
1020
1025
|
ok(Array.isArray(value), 'Value must be an array for array property');
|
|
@@ -1024,7 +1029,7 @@ export class EntityUtils {
|
|
|
1024
1029
|
value
|
|
1025
1030
|
});
|
|
1026
1031
|
if (validatorProblems.length > 0) {
|
|
1027
|
-
const prepended = prependPropertyPath(key, validatorProblems);
|
|
1032
|
+
const prepended = prependPropertyPath(key, options.sensitive === true ? redactProblems(validatorProblems) : validatorProblems);
|
|
1028
1033
|
problems.push(...prepended);
|
|
1029
1034
|
}
|
|
1030
1035
|
}
|
|
@@ -1034,7 +1039,7 @@ export class EntityUtils {
|
|
|
1034
1039
|
const element = value[i];
|
|
1035
1040
|
if (element !== null && element !== undefined) {
|
|
1036
1041
|
const elementPath = `${key}[${i}]`;
|
|
1037
|
-
const elementProblems = await this.validatePropertyValue(elementPath, element, validators);
|
|
1042
|
+
const elementProblems = await this.validatePropertyValue(elementPath, element, validators, options.sensitive === true);
|
|
1038
1043
|
problems.push(...elementProblems);
|
|
1039
1044
|
}
|
|
1040
1045
|
}
|