@buka/nestjs-kit 4.3.5 → 4.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.
package/dist/index.mjs CHANGED
@@ -4,7 +4,7 @@ import { BigIntType, Config, Cursor, EntityManager, EntityMetadata, EntitySchema
4
4
  import { Embeddable, Embedded, Enum as Enum$1, ManyToMany, ManyToOne, OneToMany, OneToOne, PrimaryKey, Property as Property$1 } from "@mikro-orm/decorators/legacy";
5
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";
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";
@@ -16,7 +16,7 @@ import { Migrator } from "@mikro-orm/migrations";
16
16
  import * as fs from "node:fs";
17
17
  import { KeqRequest, RequestException } from "keq";
18
18
  import { setBaseUrl } from "@keq-request/url";
19
- import { validateStatusCode } from "@keq-request/exception";
19
+ import { createExceptionByStatusCode, validateStatusCode } from "@keq-request/exception";
20
20
  import { createCipheriv, createDecipheriv, createHash, randomBytes } from "crypto";
21
21
  import bcrypt from "bcryptjs";
22
22
  import { Base32, Base32 as Base32$1, ErrorCategory, ErrorCategory as ErrorCategory$1, ErrorCode, ErrorCode as ErrorCode$1 } from "@buka/error-codes";
@@ -1414,6 +1414,16 @@ function isString(value) {
1414
1414
  }
1415
1415
  //#endregion
1416
1416
  //#region src/utils/internals/nestjs-swagger.ts
1417
+ /**
1418
+ * 模拟 @nestjs/swagger 的 DECORATORS 常量。
1419
+ *
1420
+ * `@nestjs/swagger` 的类型声明(`index.d.ts`)未导出 `DECORATORS`,
1421
+ * 仅在运行时可用。为避免 `ts(2305)` 错误,直接内联其常量值。
1422
+ */
1423
+ const DECORATORS = {
1424
+ API_MODEL_PROPERTIES: "swagger/apiModelProperties",
1425
+ API_MODEL_PROPERTIES_ARRAY: "swagger/apiModelPropertiesArray"
1426
+ };
1417
1427
  const METADATA_FACTORY_NAME = "_OPENAPI_METADATA_FACTORY";
1418
1428
  function getModelProperties(prototype) {
1419
1429
  return (Reflect.getMetadata(DECORATORS.API_MODEL_PROPERTIES_ARRAY, prototype) || []).filter(isString).filter((key) => key.charAt(0) === ":" && !isFunction(prototype[key])).map((key) => key.slice(1));
@@ -2686,6 +2696,11 @@ __decorate([
2686
2696
  function EntityDto(classRef) {
2687
2697
  if (!ModelRegister.isModel(classRef)) throw new TypeError("EntityDto only accepts a class annotated with @Model().");
2688
2698
  class EntityDtoClass {}
2699
+ /**
2700
+ * 收集从源实体复制的 Swagger 属性元数据,
2701
+ * 用于构建 `_OPENAPI_METADATA_FACTORY`。
2702
+ */
2703
+ const swaggerProps = {};
2689
2704
  for (const propertyKey of ModelRegister.getModelPropertyKeys(classRef)) {
2690
2705
  if (ModelRegister.getProperty(classRef, propertyKey)?.lazy) continue;
2691
2706
  ModelRegister.copyProperty(classRef, EntityDtoClass, propertyKey);
@@ -2695,7 +2710,26 @@ function EntityDto(classRef) {
2695
2710
  if (Reflect.hasMetadata(metadataKey, EntityDtoClass.prototype, propertyKey)) continue;
2696
2711
  Reflect.defineMetadata(metadataKey, value, EntityDtoClass.prototype, propertyKey);
2697
2712
  }
2713
+ /**
2714
+ * 收集已复制的 `@ApiProperty` 元数据,后续通过
2715
+ * `_OPENAPI_METADATA_FACTORY` 暴露给 `@nestjs/swagger`,
2716
+ * 使 applyMetadataFactory() 遍历原型链时能发现这些属性。
2717
+ */
2718
+ if (typeof propertyKey === "string") {
2719
+ const swaggerMeta = Reflect.getMetadata(DECORATORS.API_MODEL_PROPERTIES, EntityDtoClass.prototype, propertyKey);
2720
+ if (swaggerMeta) swaggerProps[propertyKey] = swaggerMeta;
2721
+ }
2698
2722
  }
2723
+ /**
2724
+ * 设置 `_OPENAPI_METADATA_FACTORY` 静态方法。
2725
+ *
2726
+ * `@nestjs/swagger` 插件在编译时无法识别 `EntityDto`,
2727
+ * 只对子类(如 `CourseBriefDto`)中直接声明的属性生成 factory。
2728
+ * 当 `applyMetadataFactory()` 遍历原型链时,
2729
+ * 它会在 `EntityDtoClass` 上找到此 factory,
2730
+ * 并将源实体属性应用到子类的 prototype 上。
2731
+ */
2732
+ if (Object.keys(swaggerProps).length > 0) EntityDtoClass[METADATA_FACTORY_NAME] = () => swaggerProps;
2699
2733
  return EntityDtoClass;
2700
2734
  }
2701
2735
  //#endregion
@@ -9982,6 +10016,58 @@ ObjectStorageModule = __decorate([Global(), Module({
9982
10016
  exports: [ObjectStorageService]
9983
10017
  })], ObjectStorageModule);
9984
10018
  //#endregion
9985
- export { AuthException, BUKA_MODULE_OPTIONS_TOKEN, Base32, BlindIndex, BlindIndexModule, BlindIndexService, BlindIndexV1Hasher, BukaConfigurableModuleClass, BukaExceptions, BukaModule, BukaPageQueryValidationPipe, 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 };
10019
+ //#region src/modules/keq/buka-request.exception.ts
10020
+ var BukaRequestException = class extends RequestException {
10021
+ code;
10022
+ errorCode;
10023
+ details;
10024
+ constructor(statusCode, message, options) {
10025
+ super(statusCode, message, {
10026
+ response: options.response,
10027
+ fatal: options.fatal
10028
+ });
10029
+ this.code = options.code;
10030
+ this.errorCode = ErrorCode$1.fromString(options.code);
10031
+ this.details = options.details ?? [];
10032
+ }
10033
+ };
10034
+ //#endregion
10035
+ //#region src/modules/keq/throw-on-response-error.middleware.ts
10036
+ const logger = new Logger$1("KeqMiddleware:throwOnResponseError");
10037
+ function throwOnResponseError(options) {
10038
+ const { errorDispatchers, debug } = options ?? {};
10039
+ const middleware = async (ctx, next) => {
10040
+ await next();
10041
+ if (!ctx.response || ctx.response.status >= 200 && ctx.response.status < 400) return;
10042
+ const response = ctx.response;
10043
+ if (!response.headers.get("content-type")?.includes("application/json")) throw createExceptionByStatusCode(response);
10044
+ const body = await response.json();
10045
+ if (body !== null && typeof body === "object" && "error" in body) try {
10046
+ const { error } = body;
10047
+ const exceptionOptions = {
10048
+ code: error.code,
10049
+ details: error.details,
10050
+ response,
10051
+ fatal: [
10052
+ 401,
10053
+ 403,
10054
+ 404
10055
+ ].includes(response.status)
10056
+ };
10057
+ if (errorDispatchers && error.code in errorDispatchers) {
10058
+ const ExceptionClass = errorDispatchers[error.code];
10059
+ throw new ExceptionClass(response.status, error.message, exceptionOptions);
10060
+ }
10061
+ throw new BukaRequestException(response.status, error.message, exceptionOptions);
10062
+ } catch (caught) {
10063
+ if (debug) logger.debug("解析响应错误体失败,降级为通用异常", caught instanceof Error ? caught.stack : caught);
10064
+ }
10065
+ throw createExceptionByStatusCode(response);
10066
+ };
10067
+ middleware.__keqMiddlewareName__ = "throwOnResponseError";
10068
+ return middleware;
10069
+ }
10070
+ //#endregion
10071
+ 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 };
9986
10072
 
9987
10073
  //# sourceMappingURL=index.mjs.map