@buka/nestjs-kit 4.4.0 → 4.4.2

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/dist/index.mjs CHANGED
@@ -2,9 +2,9 @@ import { BadRequestException, Catch, ConfigurableModuleBuilder, Controller, Get,
2
2
  import { APP_FILTER, APP_PIPE } from "@nestjs/core";
3
3
  import { BigIntType, Config, Cursor, EntityManager, EntityMetadata, EntitySchema, FlushMode, HiddenProps, MetadataStorage, MikroORM, OptionalProps, PrimaryKeyProp, Reference, Utils, helper } from "@mikro-orm/core";
4
4
  import { Embeddable, Embedded, Enum as Enum$1, ManyToMany, ManyToOne, OneToMany, OneToOne, PrimaryKey, Property as Property$1 } from "@mikro-orm/decorators/legacy";
5
- import { ArrayMinSize, IS_OPTIONAL, IsArray, IsBoolean, IsCurrency, IsDefined, IsEnum, IsISO8601, IsIn, IsInt, IsNotEmpty, IsNumber, IsNumberString, IsObject, IsOptional, IsString, IsUUID, IsUrl, MaxLength, Min, MinLength, ValidateNested, getMetadataStorage, registerDecorator, validate, validateSync } from "class-validator";
5
+ import { ArrayMinSize, IS_OPTIONAL, IsArray, IsBoolean, IsCurrency, IsDefined, IsEnum, IsISO8601, IsIn, IsInt, IsNotEmpty, IsNumber, IsNumberString, IsObject, IsOptional, IsString, IsUUID, IsUrl, MaxLength, Min, MinLength, ValidateNested, getMetadataStorage, isEnum, registerDecorator, validate, validateSync } from "class-validator";
6
6
  import { validate as validate$1 } from "jsonschema";
7
- import { ApiExtraModels, ApiHideProperty, ApiOkResponse, ApiOperation, ApiProperty, ApiPropertyOptional, ApiQuery, ApiSchema, ApiTags, DECORATORS, OmitType as OmitType$1, PartialType as PartialType$1, PickType as PickType$1, getSchemaPath } from "@nestjs/swagger";
7
+ import { ApiExtraModels, ApiHideProperty, ApiOkResponse, ApiOperation, ApiProperty, ApiPropertyOptional, ApiQuery, ApiSchema, ApiTags, OmitType as OmitType$1, PartialType as PartialType$1, PickType as PickType$1, getSchemaPath } from "@nestjs/swagger";
8
8
  import { Transform, Type as Type$1, plainToInstance } from "class-transformer";
9
9
  import * as R from "ramda";
10
10
  import * as classTransformer from "class-transformer/cjs/storage.js";
@@ -263,6 +263,59 @@ function IsCrockfordBase32(validationOptions) {
263
263
  };
264
264
  }
265
265
  //#endregion
266
+ //#region src/modules/core/decorators/class-validator/is-enum-column.ts
267
+ const IS_ENUM_COLUMN = "isEnumColumn";
268
+ /**
269
+ * 枚举列验证器,验证单个值是否为合法的枚举值。
270
+ *
271
+ * 延迟解析 `items`(在验证阶段才调用工厂函数),避免装饰器阶段因循环引用报错。
272
+ * 同时兼容两种写法:枚举对象 `() => Status` 和值数组 `() => Object.values(Status)`。
273
+ *
274
+ * 验证逻辑委托给 class-validator 内置的 `isEnum` / `Array.includes`。
275
+ * 如需校验数组,配合 `IsArray()` 和 `{ each: true }` 使用。
276
+ *
277
+ * @param items - 枚举对象、值数组,或返回它们的工厂函数
278
+ * @param validationOptions - class-validator 的验证选项
279
+ *
280
+ * @example
281
+ * ```typescript
282
+ * // 单值校验
283
+ * class MyDto {
284
+ * @IsEnumColumn(() => Status)
285
+ * status: Status
286
+ * }
287
+ *
288
+ * // 数组校验
289
+ * class MyDto {
290
+ * @IsArray()
291
+ * @IsEnumColumn(() => Status, { each: true })
292
+ * statuses: Status[]
293
+ * }
294
+ * ```
295
+ */
296
+ function IsEnumColumn(items, validationOptions) {
297
+ return function(object, propertyName) {
298
+ registerDecorator({
299
+ name: IS_ENUM_COLUMN,
300
+ target: object.constructor,
301
+ propertyName,
302
+ constraints: [items],
303
+ options: validationOptions,
304
+ validator: {
305
+ validate(value) {
306
+ const rawValues = typeof items === "function" ? items() : items;
307
+ if (Array.isArray(rawValues)) return rawValues.includes(value);
308
+ return isEnum(value, rawValues);
309
+ },
310
+ defaultMessage() {
311
+ const rawValues = typeof items === "function" ? items() : items;
312
+ return `$property 必须是以下之一: ${(Array.isArray(rawValues) ? rawValues : Object.values(rawValues).filter((v) => isNaN(Number(v)))).join(", ")}`;
313
+ }
314
+ }
315
+ });
316
+ };
317
+ }
318
+ //#endregion
266
319
  //#region src/modules/core/decorators/class-validator/is-scalar.ts
267
320
  function isScalarClass(ctor) {
268
321
  return ctor === String || ctor === Number || ctor === Boolean;
@@ -1414,6 +1467,16 @@ function isString(value) {
1414
1467
  }
1415
1468
  //#endregion
1416
1469
  //#region src/utils/internals/nestjs-swagger.ts
1470
+ /**
1471
+ * 模拟 @nestjs/swagger 的 DECORATORS 常量。
1472
+ *
1473
+ * `@nestjs/swagger` 的类型声明(`index.d.ts`)未导出 `DECORATORS`,
1474
+ * 仅在运行时可用。为避免 `ts(2305)` 错误,直接内联其常量值。
1475
+ */
1476
+ const DECORATORS = {
1477
+ API_MODEL_PROPERTIES: "swagger/apiModelProperties",
1478
+ API_MODEL_PROPERTIES_ARRAY: "swagger/apiModelPropertiesArray"
1479
+ };
1417
1480
  const METADATA_FACTORY_NAME = "_OPENAPI_METADATA_FACTORY";
1418
1481
  function getModelProperties(prototype) {
1419
1482
  return (Reflect.getMetadata(DECORATORS.API_MODEL_PROPERTIES_ARRAY, prototype) || []).filter(isString).filter((key) => key.charAt(0) === ":" && !isFunction(prototype[key])).map((key) => key.slice(1));
@@ -2422,7 +2485,7 @@ function Timestamptz(options) {
2422
2485
  *
2423
2486
  * @Entity()
2424
2487
  * class User {
2425
- * @Enum({ items: () => Object.values(Status), enumName: 'Status', comment: '用户状态' })
2488
+ * @Enum({ items: () => Status, enumName: 'Status', comment: '用户状态' })
2426
2489
  * status: Status
2427
2490
  * }
2428
2491
  * ```
@@ -2431,19 +2494,44 @@ function Enum$2(options) {
2431
2494
  return (target, propertyKey) => {
2432
2495
  Enum$1(options)(target, propertyKey);
2433
2496
  const items = options.items;
2434
- const values = typeof items === "function" ? items() : items;
2435
- applyDecorators(Property({
2497
+ if (options.array) {
2498
+ IsArray()(target, propertyKey);
2499
+ IsEnumColumn(items, { each: true })(target, propertyKey);
2500
+ if (options.nullable) IsOptional()(target, propertyKey);
2501
+ else IsDefined()(target, propertyKey);
2502
+ if (!options.lazy) {
2503
+ const schema = {
2504
+ description: options.comment,
2505
+ enum: items,
2506
+ isArray: true,
2507
+ enumName: options.enumName,
2508
+ example: options.example,
2509
+ examples: options.examples,
2510
+ required: !options.nullable
2511
+ };
2512
+ if (options.nullable) ApiPropertyOptional(schema)(target, propertyKey);
2513
+ else ApiProperty(schema)(target, propertyKey);
2514
+ }
2515
+ ModelRegister.addProperty(target.constructor, propertyKey, {
2516
+ kind: "enum",
2517
+ optional: options.nullable ?? false,
2518
+ lazy: options.lazy ?? false,
2519
+ items,
2520
+ enumName: options.enumName,
2521
+ array: options.array
2522
+ });
2523
+ } else Property({
2436
2524
  optional: options.nullable,
2437
2525
  lazy: options.lazy,
2438
2526
  schema: {
2439
2527
  description: options.comment,
2440
- enum: values,
2528
+ enum: items,
2441
2529
  enumName: options.enumName,
2442
2530
  example: options.example,
2443
2531
  examples: options.examples,
2444
2532
  required: !options.nullable
2445
2533
  }
2446
- }))(target, propertyKey);
2534
+ })(target, propertyKey);
2447
2535
  };
2448
2536
  }
2449
2537
  //#endregion
@@ -2498,7 +2586,11 @@ function Jsonb(options) {
2498
2586
  Dictionary(decoratorOptions)(target, propertyKey);
2499
2587
  break;
2500
2588
  default:
2501
- Composite(decoratorOptions)(target, propertyKey);
2589
+ if (isScalarClass(type)) throw new TypeError(`Jsonb with kind='composite' requires a class reference (() => Class), but got scalar type: ${type.name}`);
2590
+ Composite({
2591
+ ...decoratorOptions,
2592
+ type
2593
+ })(target, propertyKey);
2502
2594
  break;
2503
2595
  }
2504
2596
  };
@@ -2686,6 +2778,11 @@ __decorate([
2686
2778
  function EntityDto(classRef) {
2687
2779
  if (!ModelRegister.isModel(classRef)) throw new TypeError("EntityDto only accepts a class annotated with @Model().");
2688
2780
  class EntityDtoClass {}
2781
+ /**
2782
+ * 收集从源实体复制的 Swagger 属性元数据,
2783
+ * 用于构建 `_OPENAPI_METADATA_FACTORY`。
2784
+ */
2785
+ const swaggerProps = {};
2689
2786
  for (const propertyKey of ModelRegister.getModelPropertyKeys(classRef)) {
2690
2787
  if (ModelRegister.getProperty(classRef, propertyKey)?.lazy) continue;
2691
2788
  ModelRegister.copyProperty(classRef, EntityDtoClass, propertyKey);
@@ -2695,7 +2792,26 @@ function EntityDto(classRef) {
2695
2792
  if (Reflect.hasMetadata(metadataKey, EntityDtoClass.prototype, propertyKey)) continue;
2696
2793
  Reflect.defineMetadata(metadataKey, value, EntityDtoClass.prototype, propertyKey);
2697
2794
  }
2795
+ /**
2796
+ * 收集已复制的 `@ApiProperty` 元数据,后续通过
2797
+ * `_OPENAPI_METADATA_FACTORY` 暴露给 `@nestjs/swagger`,
2798
+ * 使 applyMetadataFactory() 遍历原型链时能发现这些属性。
2799
+ */
2800
+ if (typeof propertyKey === "string") {
2801
+ const swaggerMeta = Reflect.getMetadata(DECORATORS.API_MODEL_PROPERTIES, EntityDtoClass.prototype, propertyKey);
2802
+ if (swaggerMeta) swaggerProps[propertyKey] = swaggerMeta;
2803
+ }
2698
2804
  }
2805
+ /**
2806
+ * 设置 `_OPENAPI_METADATA_FACTORY` 静态方法。
2807
+ *
2808
+ * `@nestjs/swagger` 插件在编译时无法识别 `EntityDto`,
2809
+ * 只对子类(如 `CourseBriefDto`)中直接声明的属性生成 factory。
2810
+ * 当 `applyMetadataFactory()` 遍历原型链时,
2811
+ * 它会在 `EntityDtoClass` 上找到此 factory,
2812
+ * 并将源实体属性应用到子类的 prototype 上。
2813
+ */
2814
+ if (Object.keys(swaggerProps).length > 0) EntityDtoClass[METADATA_FACTORY_NAME] = () => swaggerProps;
2699
2815
  return EntityDtoClass;
2700
2816
  }
2701
2817
  //#endregion
@@ -10034,6 +10150,6 @@ function throwOnResponseError(options) {
10034
10150
  return middleware;
10035
10151
  }
10036
10152
  //#endregion
10037
- export { AuthException, BUKA_MODULE_OPTIONS_TOKEN, Base32, BlindIndex, BlindIndexModule, BlindIndexService, BlindIndexV1Hasher, BukaConfigurableModuleClass, BukaExceptions, BukaModule, BukaPageQueryValidationPipe, BukaRequestException, BukaValidationPipe, BusinessException, Cardinality, Column, Composite, ConfigurableModuleClass, ConflictException, CursorPagination, DatabaseConfig, DegradeException, Dictionary, DiscreteEntity, EncryptedPayload, EntityDto, EntityRef, Enum, EnvelopeEncryptionModule, EnvelopeEncryptionService, ErrorCategory, ErrorCode, ErrorCodeController, ErrorCodeExceptionFilter, ErrorCodeDefinitionDto as ErrorCodeItemDto, ErrorCodeMetadataDto, ErrorCodePartsDto, ErrorCodeRegistry, ErrorResponseSchema, ExceptionDetailSchema, ExceptionModule, FeatureException, FilterQuery, FilterQueryOperators, FilterQueryOperatorsMetadataKey, FilterQueryTransformPipe, HAS_ANY_KEY, HasAnyKey, HttpException, IS_CROCKFORD_BASE32, IS_DOMAIN_URN, IS_SCALAR_DICTIONARY, IS_URN, InjectLogger, IsBrowserRequest, IsCrockfordBase32, IsDomainUrn, IsScalar, IsScalarDictionary, IsUrn, KeyEnvelope, LinearEntity, List, ListErrorCodesResponseDto, ListResponseBodyType, Logger, LoggerConfig, LoggerErrorInterceptor, LoggerModule, MATCH_JSON_SCHEMA, MODULE_OPTIONS_TOKEN, MatchJsonSchema, MatchesUrn, Model, ModelRegister, ModuleExceptions, NextCursorPageSchema, ObjectStorageModule, ObjectStorageModuleConfig, ObjectStorageService, OffsetPageSchema, OffsetPagination, OmitType, OpenBaoAppRoleAuthConfig, OpenBaoHttpClient, OpenBaoKubernetesAuthConfig, OpenBaoModule, OpenBaoModuleConfig, OpenBaoTokenAuthConfig, OpenBaoTokenManager, OpenBaoUserpassAuthConfig, OptionalPageQuery, OrderQueryType, PageQuery, ParseUUIDv7Pipe, PartialType, PendingException, PickType, PreviousCursorPageSchema, PrimaryKeyType, PrimaryKeyTypeClassMetadataPropertyKey, Property, RateLimitException, ResponseBodyType, SaltedHash, SaltedHashModule, SaltedHashService, SaltedHashV1Hasher, Slice, SwaggerPatcher, SystemException, ThirdPartyException, TimestampedEntity, Urn, VALIDATE_NESTED_DICTIONARY, ValidateNestedDictionary, ValidationException, getExceptionModuleId, getFilterQueryOperators, isScalarClass, serializeModel, setOpenBaoToken, stableStringify, throwOnResponseError };
10153
+ export { AuthException, BUKA_MODULE_OPTIONS_TOKEN, Base32, BlindIndex, BlindIndexModule, BlindIndexService, BlindIndexV1Hasher, BukaConfigurableModuleClass, BukaExceptions, BukaModule, BukaPageQueryValidationPipe, BukaRequestException, BukaValidationPipe, BusinessException, Cardinality, Column, Composite, ConfigurableModuleClass, ConflictException, CursorPagination, DatabaseConfig, DegradeException, Dictionary, DiscreteEntity, EncryptedPayload, EntityDto, EntityRef, Enum, EnvelopeEncryptionModule, EnvelopeEncryptionService, ErrorCategory, ErrorCode, ErrorCodeController, ErrorCodeExceptionFilter, ErrorCodeDefinitionDto as ErrorCodeItemDto, ErrorCodeMetadataDto, ErrorCodePartsDto, ErrorCodeRegistry, ErrorResponseSchema, ExceptionDetailSchema, ExceptionModule, FeatureException, FilterQuery, FilterQueryOperators, FilterQueryOperatorsMetadataKey, FilterQueryTransformPipe, HAS_ANY_KEY, HasAnyKey, HttpException, IS_CROCKFORD_BASE32, IS_DOMAIN_URN, IS_ENUM_COLUMN, IS_SCALAR_DICTIONARY, IS_URN, InjectLogger, IsBrowserRequest, IsCrockfordBase32, IsDomainUrn, IsEnumColumn, IsScalar, IsScalarDictionary, IsUrn, KeyEnvelope, LinearEntity, List, ListErrorCodesResponseDto, ListResponseBodyType, Logger, LoggerConfig, LoggerErrorInterceptor, LoggerModule, MATCH_JSON_SCHEMA, MODULE_OPTIONS_TOKEN, MatchJsonSchema, MatchesUrn, Model, ModelRegister, ModuleExceptions, NextCursorPageSchema, ObjectStorageModule, ObjectStorageModuleConfig, ObjectStorageService, OffsetPageSchema, OffsetPagination, OmitType, OpenBaoAppRoleAuthConfig, OpenBaoHttpClient, OpenBaoKubernetesAuthConfig, OpenBaoModule, OpenBaoModuleConfig, OpenBaoTokenAuthConfig, OpenBaoTokenManager, OpenBaoUserpassAuthConfig, OptionalPageQuery, OrderQueryType, PageQuery, ParseUUIDv7Pipe, PartialType, PendingException, PickType, PreviousCursorPageSchema, PrimaryKeyType, PrimaryKeyTypeClassMetadataPropertyKey, Property, RateLimitException, ResponseBodyType, SaltedHash, SaltedHashModule, SaltedHashService, SaltedHashV1Hasher, Slice, SwaggerPatcher, SystemException, ThirdPartyException, TimestampedEntity, Urn, VALIDATE_NESTED_DICTIONARY, ValidateNestedDictionary, ValidationException, getExceptionModuleId, getFilterQueryOperators, isScalarClass, serializeModel, setOpenBaoToken, stableStringify, throwOnResponseError };
10038
10154
 
10039
10155
  //# sourceMappingURL=index.mjs.map