@venizia/ignis-kernel 0.4.8-6 → 0.4.8-7

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.
@@ -1,5 +1,5 @@
1
1
  import { AuthorizationActions } from '../../auth/authorize/common/constants/index.js';
2
- import { SchemaTypes } from '../../models/common/constants.js';
2
+ import { AuditFields, SchemaTypes } from '../../models/common/constants.js';
3
3
  import { BindingNamespaces } from '../../../common/bindings.js';
4
4
  import { BindingKeys, MetadataRegistry } from '../../../helpers/inversion/index.js';
5
5
  import { BaseHelper, getError } from '@venizia/ignis-helpers/core';
@@ -59,6 +59,9 @@ export class ControllerFactory extends BaseHelper {
59
59
  });
60
60
  const entityClass = isClass(entity) ? entity : entity();
61
61
  const entityInstance = new entityClass();
62
+ const settings = MetadataRegistry.getInstance().getModelMetadata({
63
+ target: entityClass,
64
+ })?.settings;
62
65
  const routeDefinitions = RouteConfigResolver.defineControllerRouteConfigs({
63
66
  isStrict: isStrict.requestSchema ?? true,
64
67
  idType: entityInstance.getIdType(),
@@ -70,7 +73,7 @@ export class ControllerFactory extends BaseHelper {
70
73
  create: entityInstance.getSchema({ type: SchemaTypes.CREATE }),
71
74
  update: entityInstance.getSchema({ type: SchemaTypes.UPDATE }),
72
75
  },
73
- serverStampedKeys: entityInstance.getServerStampedKeys(),
76
+ serverStampedKeys: [...(settings?.properties?.stamped ?? AuditFields.SCHEME_SET)],
74
77
  });
75
78
  const controllerClass = class extends PersistableCrudController {
76
79
  // Any extra options: a repository whose options narrow `IExtraOptions` (a typed transaction) must fit.
@@ -1 +1 @@
1
- {"version":3,"file":"controller.js","sourceRoot":"","sources":["../../../../../src/base/controllers/factory/controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAG7D,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;A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AE,EAAE,CAAC,GAAG,cAAc,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC9E,MAAM,WAAW,GAAG,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,UAAU,IAAI,IAAI,KAAK,UAAU,CAAC,CAAC;QAEzF,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE;gBACP,yFAAyF,cAAc,cAAc,KAAK,iBAAiB,SAAS,EAAE;gBACtJ,6DAA6D;gBAC7D,wKAAwK;gBACxK,GAAG,CAAC,WAAW;oBACb,CAAC,CAAC;wBACE,8KAA8K;qBAC/K;oBACH,CAAC,CAAC,EAAE,CAAC;aACR,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { AuthorizationActions } from '@/base/auth/authorize/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { AbstractEntity } from '@/base/models';\nimport { SchemaTypes } from '@/base/models/common/constants';\nimport type { AbstractRepository } from '@/base/repositories';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { BindingNamespaces } from '@/common/bindings';\nimport { BindingKeys, MetadataRegistry } from '@/helpers/inversion';\nimport type { AnyType, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { isClass } from '@venizia/ignis-inversion';\nimport type { Env, Schema } from 'hono';\nimport type {\n ICrudControllerOptions,\n ICustomizableRoutes,\n TEntityDataObject,\n TEntityPersistObject,\n} from '../common';\nimport { PersistableCrudController } from './crud';\nimport { RouteConfigResolver } from './definition';\n\n/** Factory for generating typed CRUD controllers from entity definitions. */\nexport class ControllerFactory extends BaseHelper {\n /** The generated routes that change data: the ones that must never be answered by a `read` permission. */\n private static readonly WRITE_VERBS = [\n 'create',\n 'updateById',\n 'updateBy',\n 'deleteById',\n 'deleteBy',\n ] as const;\n\n constructor() {\n super({ scope: ControllerFactory.name });\n }\n\n /**\n * Injects `repositories.<repositoryName>` into constructor parameter 0 of a factory-generated\n * controller, so a subclass needs no constructor. Recorded as metadata rather than a parameter\n * decorator, which Bun drops in some configurations. A subclass that declares its own `@inject` at\n * index 0 wins, and a sibling subclass keeps the factory's key.\n */\n static registerRepositoryInjection(opts: {\n target: TClass<unknown>;\n factoryName: string;\n controllerName: string;\n repositoryName: string;\n }): void {\n const { target, factoryName, controllerName, repositoryName } = opts;\n\n if (!repositoryName) {\n throw getError({\n message: `[${factoryName}] Invalid repository name | controller: ${controllerName} | repository.name must name the repository binding`,\n });\n }\n\n MetadataRegistry.getInstance().setInjectMetadata({\n target,\n index: 0,\n metadata: {\n key: BindingKeys.build({ namespace: BindingNamespaces.REPOSITORY, key: repositoryName }),\n index: 0,\n isOptional: false,\n },\n });\n }\n\n static defineCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n Routes extends ICustomizableRoutes = ICustomizableRoutes,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n TPersistObject extends object = TEntityPersistObject<TEntity>,\n >(defOpts: ICrudControllerOptions<TEntity, Routes>) {\n const { controller, entity, authenticate, authorize, routes } = defOpts;\n\n const {\n name,\n basePath = 'unknown_path',\n isStrict = { path: true, requestSchema: true },\n } = controller;\n\n if (!basePath || basePath === 'unknown_path') {\n throw getError({\n message: `[defineCrudController] Invalid controller basePath | name: ${name} | basePath: ${basePath}`,\n });\n }\n\n ControllerFactory.assertWriteVerbsDeclareAuthorize({\n controllerName: name,\n authorize,\n routes,\n readonly: controller.readonly,\n enabledRoutes: controller.enabledRoutes,\n });\n\n const entityClass = isClass(entity) ? entity : entity();\n const entityInstance = new entityClass();\n\n const routeDefinitions = RouteConfigResolver.defineControllerRouteConfigs({\n isStrict: isStrict.requestSchema ?? true,\n idType: entityInstance.getIdType(),\n authenticate,\n authorize,\n routes,\n schema: {\n select: entityInstance.getSchema({ type: SchemaTypes.SELECT }),\n create: entityInstance.getSchema({ type: SchemaTypes.CREATE }),\n update: entityInstance.getSchema({ type: SchemaTypes.UPDATE }),\n },\n serverStampedKeys: entityInstance.getServerStampedKeys(),\n });\n\n const controllerClass = class extends PersistableCrudController<\n TEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n > {\n // Any extra options: a repository whose options narrow `IExtraOptions` (a typed transaction) must fit.\n constructor(repository: AbstractRepository<TDataObject, TPersistObject, AnyType>) {\n super({\n scope: name,\n path: basePath,\n isStrict: isStrict.path ?? true,\n repository,\n definitions: routeDefinitions,\n });\n }\n\n /** Registers each CRUD route whose handler tier supplies it, honoring enabledRoutes/readonly. */\n override binding(): ValueOrPromise<void> {\n const isEnabled = (routeKey: keyof ICustomizableRoutes) => {\n if (controller.enabledRoutes) {\n return controller.enabledRoutes.includes(routeKey);\n }\n\n return routes?.[routeKey]?.enabled !== false;\n };\n\n // Read routes - always registered (unless explicitly disabled)\n if (isEnabled('count')) {\n this.defineRoute({\n configs: routeDefinitions.COUNT,\n handler: async (context) => this.count({ context }),\n });\n }\n\n if (isEnabled('find')) {\n this.defineRoute({\n configs: routeDefinitions.FIND,\n handler: async (context) => this.find({ context }),\n });\n }\n\n if (isEnabled('findOne')) {\n this.defineRoute({\n configs: routeDefinitions.FIND_ONE,\n handler: async (context) => this.findOne({ context }),\n });\n }\n\n if (isEnabled('findById')) {\n this.defineRoute({\n configs: routeDefinitions.FIND_BY_ID,\n handler: async (context) => this.findById({ context }),\n });\n }\n\n // Write routes - skipped when readonly\n if (controller.readonly) {\n return;\n }\n\n if (isEnabled('create')) {\n this.defineRoute({\n configs: routeDefinitions.CREATE,\n handler: async (context) => this.create({ context }),\n });\n }\n\n if (isEnabled('updateById')) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY_ID,\n handler: async (context) => this.updateById({ context }),\n });\n }\n\n if (isEnabled('updateBy')) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY,\n handler: async (context) => this.updateBy({ context }),\n });\n }\n\n if (isEnabled('deleteById')) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY_ID,\n handler: async (context) => this.deleteById({ context }),\n });\n }\n\n if (isEnabled('deleteBy')) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY,\n handler: async (context) => this.deleteBy({ context }),\n });\n }\n }\n };\n\n Object.defineProperty(controllerClass, 'name', { value: name, configurable: true });\n ControllerFactory.registerRepositoryInjection({\n target: controllerClass,\n factoryName: 'defineCrudController',\n controllerName: name,\n repositoryName: defOpts.repository.name,\n });\n\n return controllerClass;\n }\n\n private static describeSpec(opts: { spec: IAuthorizationSpec }): string {\n const { spec } = opts;\n\n return `{ action: ${String(spec.action)}, resource: ${String(spec.resource)} }`;\n }\n\n /**\n * Refuses a CRUD controller whose enabled write verb would inherit a controller-level `authorize`\n * that is only a `read` permission: the verb would then answer to anyone who may read.\n *\n * A write verb is fine when it declares its own `authorize` (a spec, an array, or `{ skip: true }`),\n * skips authentication, is not enabled, or the controller is `readonly`. Only the literal action\n * `read` is detected; a custom action name is the application's own vocabulary. An array counts when\n * every spec in it is `read`, since the specs of one route must all pass.\n */\n static assertWriteVerbsDeclareAuthorize(opts: {\n controllerName: string;\n authorize: IAuthorizationSpec | IAuthorizationSpec[] | undefined;\n routes: ICustomizableRoutes | undefined;\n readonly: boolean | undefined;\n enabledRoutes: Array<keyof ICustomizableRoutes> | undefined;\n }): void {\n const { controllerName, authorize, routes, readonly, enabledRoutes } = opts;\n\n if (readonly || authorize == null) {\n return;\n }\n\n const specs = Array.isArray(authorize) ? authorize : [authorize];\n const isReadOnlyPermission =\n specs.length > 0 && specs.every((spec) => spec.action === AuthorizationActions.READ);\n\n if (!isReadOnlyPermission) {\n return;\n }\n\n const offending = ControllerFactory.WRITE_VERBS.filter((verb) => {\n const isEnabled = enabledRoutes\n ? enabledRoutes.includes(verb)\n : routes?.[verb]?.enabled !== false;\n\n if (!isEnabled) {\n return false;\n }\n\n const route = routes?.[verb];\n\n return route?.authenticate?.skip !== true && route?.authorize == null;\n });\n\n if (offending.length === 0) {\n return;\n }\n\n const inherited = specs.map((spec) => ControllerFactory.describeSpec({ spec })).join(', ');\n const verbs = offending.map((verb) => `${controllerName}.${verb}`).join(', ');\n const hasBulkVerb = offending.some((verb) => verb === 'updateBy' || verb === 'deleteBy');\n\n throw getError({\n message: [\n `[defineCrudController] Write routes would inherit a read-only authorize | controller: ${controllerName} | routes: ${verbs} | inherited: ${inherited}`,\n 'Anyone allowed to read could then create, update or delete.',\n `Fix: declare routes.<verb>.authorize for each of them (a spec, an array or { skip: true }), or set controller.readonly, or leave them out of controller.enabledRoutes.`,\n ...(hasBulkVerb\n ? [\n 'updateBy and deleteBy are bulk routes on the collection and are generated unless controller.enabledRoutes lists the routes you want, so dropping them there closes this too.',\n ]\n : []),\n ].join(' | '),\n });\n }\n}\n"]}
1
+ {"version":3,"file":"controller.js","sourceRoot":"","sources":["../../../../../src/base/controllers/factory/controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,wCAAwC,CAAC;AAG9E,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAG1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEpE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAQnD,OAAO,EAAE,yBAAyB,EAAE,MAAM,QAAQ,CAAC;AACnD,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAEnD,6EAA6E;AAC7E,MAAM,OAAO,iBAAkB,SAAQ,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I,EAAE,EAAE,CAAC,IAAI,KAAK,UAAU,IAAI,IAAI,KAAK,UAAU,CAAC,CAAC;QAEzF,MAAM,QAAQ,CAAC;YACb,OAAO,EAAE;gBACP,yFAAyF,cAAc,cAAc,KAAK,iBAAiB,SAAS,EAAE;gBACtJ,6DAA6D;gBAC7D,wKAAwK;gBACxK,GAAG,CAAC,WAAW;oBACb,CAAC,CAAC;wBACE,8KAA8K;qBAC/K;oBACH,CAAC,CAAC,EAAE,CAAC;aACR,CAAC,IAAI,CAAC,KAAK,CAAC;SACd,CAAC,CAAC;IACL,CAAC","sourcesContent":["import { AuthorizationActions } from '@/base/auth/authorize/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { AbstractEntity } from '@/base/models';\nimport { AuditFields, SchemaTypes } from '@/base/models/common/constants';\nimport type { AbstractRepository } from '@/base/repositories';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { BindingNamespaces } from '@/common/bindings';\nimport { BindingKeys, MetadataRegistry } from '@/helpers/inversion';\nimport type { AnyType, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { isClass } from '@venizia/ignis-inversion';\nimport type { Env, Schema } from 'hono';\nimport type {\n ICrudControllerOptions,\n ICustomizableRoutes,\n TEntityDataObject,\n TEntityPersistObject,\n} from '../common';\nimport { PersistableCrudController } from './crud';\nimport { RouteConfigResolver } from './definition';\n\n/** Factory for generating typed CRUD controllers from entity definitions. */\nexport class ControllerFactory extends BaseHelper {\n /** The generated routes that change data: the ones that must never be answered by a `read` permission. */\n private static readonly WRITE_VERBS = [\n 'create',\n 'updateById',\n 'updateBy',\n 'deleteById',\n 'deleteBy',\n ] as const;\n\n constructor() {\n super({ scope: ControllerFactory.name });\n }\n\n /**\n * Injects `repositories.<repositoryName>` into constructor parameter 0 of a factory-generated\n * controller, so a subclass needs no constructor. Recorded as metadata rather than a parameter\n * decorator, which Bun drops in some configurations. A subclass that declares its own `@inject` at\n * index 0 wins, and a sibling subclass keeps the factory's key.\n */\n static registerRepositoryInjection(opts: {\n target: TClass<unknown>;\n factoryName: string;\n controllerName: string;\n repositoryName: string;\n }): void {\n const { target, factoryName, controllerName, repositoryName } = opts;\n\n if (!repositoryName) {\n throw getError({\n message: `[${factoryName}] Invalid repository name | controller: ${controllerName} | repository.name must name the repository binding`,\n });\n }\n\n MetadataRegistry.getInstance().setInjectMetadata({\n target,\n index: 0,\n metadata: {\n key: BindingKeys.build({ namespace: BindingNamespaces.REPOSITORY, key: repositoryName }),\n index: 0,\n isOptional: false,\n },\n });\n }\n\n static defineCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\n Routes extends ICustomizableRoutes = ICustomizableRoutes,\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n TDataObject extends object = TEntityDataObject<TEntity>,\n TPersistObject extends object = TEntityPersistObject<TEntity>,\n >(defOpts: ICrudControllerOptions<TEntity, Routes>) {\n const { controller, entity, authenticate, authorize, routes } = defOpts;\n\n const {\n name,\n basePath = 'unknown_path',\n isStrict = { path: true, requestSchema: true },\n } = controller;\n\n if (!basePath || basePath === 'unknown_path') {\n throw getError({\n message: `[defineCrudController] Invalid controller basePath | name: ${name} | basePath: ${basePath}`,\n });\n }\n\n ControllerFactory.assertWriteVerbsDeclareAuthorize({\n controllerName: name,\n authorize,\n routes,\n readonly: controller.readonly,\n enabledRoutes: controller.enabledRoutes,\n });\n\n const entityClass = isClass(entity) ? entity : entity();\n const entityInstance = new entityClass();\n const settings = MetadataRegistry.getInstance().getModelMetadata({\n target: entityClass,\n })?.settings;\n\n const routeDefinitions = RouteConfigResolver.defineControllerRouteConfigs({\n isStrict: isStrict.requestSchema ?? true,\n idType: entityInstance.getIdType(),\n authenticate,\n authorize,\n routes,\n schema: {\n select: entityInstance.getSchema({ type: SchemaTypes.SELECT }),\n create: entityInstance.getSchema({ type: SchemaTypes.CREATE }),\n update: entityInstance.getSchema({ type: SchemaTypes.UPDATE }),\n },\n serverStampedKeys: [...(settings?.properties?.stamped ?? AuditFields.SCHEME_SET)],\n });\n\n const controllerClass = class extends PersistableCrudController<\n TEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n > {\n // Any extra options: a repository whose options narrow `IExtraOptions` (a typed transaction) must fit.\n constructor(repository: AbstractRepository<TDataObject, TPersistObject, AnyType>) {\n super({\n scope: name,\n path: basePath,\n isStrict: isStrict.path ?? true,\n repository,\n definitions: routeDefinitions,\n });\n }\n\n /** Registers each CRUD route whose handler tier supplies it, honoring enabledRoutes/readonly. */\n override binding(): ValueOrPromise<void> {\n const isEnabled = (routeKey: keyof ICustomizableRoutes) => {\n if (controller.enabledRoutes) {\n return controller.enabledRoutes.includes(routeKey);\n }\n\n return routes?.[routeKey]?.enabled !== false;\n };\n\n // Read routes - always registered (unless explicitly disabled)\n if (isEnabled('count')) {\n this.defineRoute({\n configs: routeDefinitions.COUNT,\n handler: async (context) => this.count({ context }),\n });\n }\n\n if (isEnabled('find')) {\n this.defineRoute({\n configs: routeDefinitions.FIND,\n handler: async (context) => this.find({ context }),\n });\n }\n\n if (isEnabled('findOne')) {\n this.defineRoute({\n configs: routeDefinitions.FIND_ONE,\n handler: async (context) => this.findOne({ context }),\n });\n }\n\n if (isEnabled('findById')) {\n this.defineRoute({\n configs: routeDefinitions.FIND_BY_ID,\n handler: async (context) => this.findById({ context }),\n });\n }\n\n // Write routes - skipped when readonly\n if (controller.readonly) {\n return;\n }\n\n if (isEnabled('create')) {\n this.defineRoute({\n configs: routeDefinitions.CREATE,\n handler: async (context) => this.create({ context }),\n });\n }\n\n if (isEnabled('updateById')) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY_ID,\n handler: async (context) => this.updateById({ context }),\n });\n }\n\n if (isEnabled('updateBy')) {\n this.defineRoute({\n configs: routeDefinitions.UPDATE_BY,\n handler: async (context) => this.updateBy({ context }),\n });\n }\n\n if (isEnabled('deleteById')) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY_ID,\n handler: async (context) => this.deleteById({ context }),\n });\n }\n\n if (isEnabled('deleteBy')) {\n this.defineRoute({\n configs: routeDefinitions.DELETE_BY,\n handler: async (context) => this.deleteBy({ context }),\n });\n }\n }\n };\n\n Object.defineProperty(controllerClass, 'name', { value: name, configurable: true });\n ControllerFactory.registerRepositoryInjection({\n target: controllerClass,\n factoryName: 'defineCrudController',\n controllerName: name,\n repositoryName: defOpts.repository.name,\n });\n\n return controllerClass;\n }\n\n private static describeSpec(opts: { spec: IAuthorizationSpec }): string {\n const { spec } = opts;\n\n return `{ action: ${String(spec.action)}, resource: ${String(spec.resource)} }`;\n }\n\n /**\n * Refuses a CRUD controller whose enabled write verb would inherit a controller-level `authorize`\n * that is only a `read` permission: the verb would then answer to anyone who may read.\n *\n * A write verb is fine when it declares its own `authorize` (a spec, an array, or `{ skip: true }`),\n * skips authentication, is not enabled, or the controller is `readonly`. Only the literal action\n * `read` is detected; a custom action name is the application's own vocabulary. An array counts when\n * every spec in it is `read`, since the specs of one route must all pass.\n */\n static assertWriteVerbsDeclareAuthorize(opts: {\n controllerName: string;\n authorize: IAuthorizationSpec | IAuthorizationSpec[] | undefined;\n routes: ICustomizableRoutes | undefined;\n readonly: boolean | undefined;\n enabledRoutes: Array<keyof ICustomizableRoutes> | undefined;\n }): void {\n const { controllerName, authorize, routes, readonly, enabledRoutes } = opts;\n\n if (readonly || authorize == null) {\n return;\n }\n\n const specs = Array.isArray(authorize) ? authorize : [authorize];\n const isReadOnlyPermission =\n specs.length > 0 && specs.every((spec) => spec.action === AuthorizationActions.READ);\n\n if (!isReadOnlyPermission) {\n return;\n }\n\n const offending = ControllerFactory.WRITE_VERBS.filter((verb) => {\n const isEnabled = enabledRoutes\n ? enabledRoutes.includes(verb)\n : routes?.[verb]?.enabled !== false;\n\n if (!isEnabled) {\n return false;\n }\n\n const route = routes?.[verb];\n\n return route?.authenticate?.skip !== true && route?.authorize == null;\n });\n\n if (offending.length === 0) {\n return;\n }\n\n const inherited = specs.map((spec) => ControllerFactory.describeSpec({ spec })).join(', ');\n const verbs = offending.map((verb) => `${controllerName}.${verb}`).join(', ');\n const hasBulkVerb = offending.some((verb) => verb === 'updateBy' || verb === 'deleteBy');\n\n throw getError({\n message: [\n `[defineCrudController] Write routes would inherit a read-only authorize | controller: ${controllerName} | routes: ${verbs} | inherited: ${inherited}`,\n 'Anyone allowed to read could then create, update or delete.',\n `Fix: declare routes.<verb>.authorize for each of them (a spec, an array or { skip: true }), or set controller.readonly, or leave them out of controller.enabledRoutes.`,\n ...(hasBulkVerb\n ? [\n 'updateBy and deleteBy are bulk routes on the collection and are generated unless controller.enabledRoutes lists the routes you want, so dropping them there closes this too.',\n ]\n : []),\n ].join(' | '),\n });\n }\n}\n"]}
@@ -199,7 +199,7 @@ export declare class RouteConfigResolver {
199
199
  headers: import("../index.js").TResponseHeaders;
200
200
  };
201
201
  };
202
- /** `serverStampedKeys` - what the entity reports from `getServerStampedKeys()`; the default body leaves them out. */
202
+ /** `serverStampedKeys` - the keys the default body leaves out. */
203
203
  static resolveCreateConfig<C extends ICustomizableRoutes['create'], SelectSchema extends TAnyObjectSchema, CreateSchema extends TAnyObjectSchema>(opts: {
204
204
  config: C;
205
205
  selectSchema: SelectSchema;
@@ -229,8 +229,8 @@ export declare class RouteConfigResolver {
229
229
  private static resolveDeleteByIdConfig;
230
230
  private static resolveDeleteByConfig;
231
231
  /**
232
- * Generates complete route configurations for a CRUD controller. `serverStampedKeys` - what the
233
- * entity reports from `getServerStampedKeys()`; the default write bodies leave them out.
232
+ * Generates complete route configurations for a CRUD controller. `serverStampedKeys` - the keys the default
233
+ * write bodies leave out.
234
234
  */
235
235
  static defineControllerRouteConfigs<Routes extends ICustomizableRoutes, SelectSchema extends TAnyObjectSchema, CreateSchema extends TAnyObjectSchema, UpdateSchema extends TAnyObjectSchema>(opts: {
236
236
  isStrict: boolean;
@@ -146,7 +146,7 @@ export class RouteConfigResolver {
146
146
  },
147
147
  };
148
148
  }
149
- /** `serverStampedKeys` - what the entity reports from `getServerStampedKeys()`; the default body leaves them out. */
149
+ /** `serverStampedKeys` - the keys the default body leaves out. */
150
150
  static resolveCreateConfig(opts) {
151
151
  const { config, selectSchema, createSchema, serverStampedKeys = [] } = opts;
152
152
  const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);
@@ -258,8 +258,8 @@ export class RouteConfigResolver {
258
258
  };
259
259
  }
260
260
  /**
261
- * Generates complete route configurations for a CRUD controller. `serverStampedKeys` - what the
262
- * entity reports from `getServerStampedKeys()`; the default write bodies leave them out.
261
+ * Generates complete route configurations for a CRUD controller. `serverStampedKeys` - the keys the default
262
+ * write bodies leave out.
263
263
  */
264
264
  static defineControllerRouteConfigs(opts) {
265
265
  const { isStrict, idType, authenticate: controllerAuth = {}, authorize: controllerAuthorize, schema: { select: selectSchema, create: createSchema, update: updateSchema }, serverStampedKeys = [], routes, } = opts;
@@ -1 +1 @@
1
- {"version":3,"file":"definition.js","sourceRoot":"","sources":["../../../../../src/base/controllers/factory/definition.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;AAEnF,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,SAAS,EACT,gBAAgB,GACjB,MAAM,WAAW,CAAC;AAWnB;;;;GAIG;AACH,MAAM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O,CAAC,IAAI;gCAC7B,QAAQ,EAAE,KAAK;6BAChB,CAAC;yBACH;wBACH,CAAC,CAAC,EAAE,CAAC;oBACP,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,OAAO;iBAClC;gBACD,SAAS,EAAE,gBAAgB,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC;aAC5D;SACO,CAAC;QAEX,OAAO,EAAE,CAAC;IACZ,CAAC;CACF","sourcesContent":["import type { TAuthMode, TAuthStrategy } from '@/base/auth/authenticate/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { TIdSchemaType } from '@/base/models/common';\nimport { OpenApiResponses, OpenApiSchemas } from '@/base/models/common';\nimport { CountSchema } from '@/base/repositories/common';\nimport { FilterQuerySchema, WhereSchema } from '@/base/repositories/query-schemas';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { z } from '@hono/zod-openapi';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { ICustomizableRoutes } from '../common';\nimport {\n commonResponseHeaders,\n defaultRequestHeaders,\n findResponseHeaders,\n RestPaths,\n trackableHeaders,\n} from '../common';\n\n/** Picks user-overridden response schema if present (and non-undefined), else the default. */\ntype TResolvedResponseSchema<C, D extends z.ZodType> = C extends {\n response: {\n schema: infer S extends z.ZodType;\n };\n}\n ? S\n : D;\n\n/**\n * Every method here is an unbound static, called from the exported aliases below without a\n * receiver - a method must call another via `RouteConfigResolver.other(...)`, never\n * `this.other(...)`, or `this` is `undefined` at the call site.\n */\nexport class RouteConfigResolver {\n /** Path params always reach the validator as strings, so a number-typed id must be coerced before `z.number()` sees it - `OpenApiSchemas.idParams` alone rejects `/accounts/7`. */\n private static idPathParamsSchema(opts: { idType: TIdSchemaType }) {\n const { idType } = opts;\n\n if (idType !== 'number') {\n return OpenApiSchemas.idParams({ idType });\n }\n\n return z.object({\n id: z.coerce.number().openapi({\n param: { name: 'id', in: 'path', description: 'The unique id of the resource' },\n examples: [1, 2, 3],\n }),\n });\n }\n\n /**\n * The default body of a write route: the entity schema without the keys the entity stamps, and on\n * an update without `id` - the path or `where` names the rows. Zod strips a left-out key a client\n * sends. With nothing to leave out the schema itself is the body, refinements and OpenAPI name kept.\n */\n private static toWriteBodySchema(opts: {\n schema: TAnyObjectSchema;\n route: keyof ICustomizableRoutes;\n serverStampedKeys: string[];\n }): TAnyObjectSchema {\n const { schema, route, serverStampedKeys } = opts;\n const droppedKeys = route === 'create' ? serverStampedKeys : [...serverStampedKeys, 'id'];\n // A `.transform()` pipe has no shape to read, so every key it might hold counts.\n const isObjectSchema = schema instanceof z.ZodObject;\n const omittedKeys = isObjectSchema\n ? droppedKeys.filter((key) => Object.hasOwn(schema.shape, key))\n : droppedKeys;\n\n if (omittedKeys.length === 0) {\n return schema;\n }\n\n if (!isObjectSchema || schema.def.checks?.length) {\n throw getError({\n message: `[RouteConfigResolver.defineControllerRouteConfigs] Cannot build the default ${route} body | keys to leave out: ${omittedKeys.join(', ')} | The schema is refined or transformed, so zod cannot remove them | Pass routes.${route}.request.body`,\n });\n }\n\n const mask: Record<string, true> = {};\n\n for (const key of omittedKeys) {\n mask[key] = true;\n }\n\n return schema.omit(mask);\n }\n\n /** Picks the caller's per-route `request.params` override, else the entity's id path-param schema. */\n private static resolveIdParams<\n C extends { request?: { params?: TAnyObjectSchema } } | undefined,\n >(opts: { config: C; idType: TIdSchemaType }) {\n const { config, idType } = opts;\n\n return config?.request?.params ?? RouteConfigResolver.idPathParamsSchema({ idType });\n }\n\n /** Creates conditional count response schema. */\n static conditionalCountResponse<T extends z.ZodType>(dataSchema: T) {\n return z.union([\n CountSchema.extend({ data: dataSchema }).openapi({\n description: 'Response with count (when x-request-count header is \"true\" or omitted)',\n }),\n dataSchema.openapi({\n description: 'Data only response (when x-request-count header is \"false\")',\n }),\n ]);\n }\n\n /** Resolves a route's response schema - user override or default. Holds the one cast every `resolve*Config` needs: generic `C` is only known by its wider structural constraint, so it cannot be proven at the value level to collapse to `TResolvedResponseSchema`. */\n private static resolveResponseSchema<\n C extends { response?: { schema?: z.ZodType } } | undefined,\n D extends z.ZodType,\n >(opts: { config: C; defaultSchema: D }): TResolvedResponseSchema<C, D> {\n const { config, defaultSchema } = opts;\n\n return (config?.response?.schema ?? defaultSchema) as TResolvedResponseSchema<C, D>;\n }\n\n static resolveCountConfig<C extends ICustomizableRoutes['count']>(opts: {\n config: C;\n isStrict: boolean;\n }) {\n const { config, isStrict } = opts;\n const defaultQuery = z\n .object({\n where: isStrict\n ? WhereSchema\n : z.optional(WhereSchema).openapi({ description: 'Filter conditions' }),\n })\n .openapi({ description: 'Count query params' });\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n headers: config?.request?.headers ?? trackableHeaders,\n },\n response: {\n description: 'Total count of matching records',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema: CountSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n static resolveFindConfig<\n C extends ICustomizableRoutes['find'],\n FindSchema extends TAnyObjectSchema,\n >(opts: { config: C; selectSchema: FindSchema }) {\n const { config, selectSchema } = opts;\n const defaultQuery = FilterQuerySchema;\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(z.array(selectSchema));\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Array of matching records (with optional count)',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? findResponseHeaders,\n },\n };\n }\n\n static resolveFindByIdConfig<\n C extends ICustomizableRoutes['findById'],\n FindByIdSchema extends TAnyObjectSchema,\n >(opts: { idType: TIdSchemaType; config: C; selectSchema: FindByIdSchema }) {\n const { config, selectSchema, idType } = opts;\n const defaultQuery = FilterQuerySchema.openapi({\n description: 'Filter with fields, order, include (where ignored)',\n });\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n params: RouteConfigResolver.resolveIdParams({ config, idType }),\n query: config?.request?.query ?? defaultQuery,\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Single record matching ID or null',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n static resolveFindOneConfig<\n C extends ICustomizableRoutes['findOne'],\n FindOneSchema extends TAnyObjectSchema,\n >(opts: { config: C; selectSchema: FindOneSchema }) {\n const { config, selectSchema } = opts;\n const defaultQuery = FilterQuerySchema.openapi({\n description: 'Filter with where, fields, order, include',\n });\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'First matching record or null',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n /** `serverStampedKeys` - what the entity reports from `getServerStampedKeys()`; the default body leaves them out. */\n static resolveCreateConfig<\n C extends ICustomizableRoutes['create'],\n SelectSchema extends TAnyObjectSchema,\n CreateSchema extends TAnyObjectSchema,\n >(opts: {\n config: C;\n selectSchema: SelectSchema;\n createSchema: CreateSchema;\n serverStampedKeys?: string[];\n }) {\n const { config, selectSchema, createSchema, serverStampedKeys = [] } = opts;\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n body:\n config?.request?.body ??\n RouteConfigResolver.toWriteBodySchema({\n schema: createSchema,\n route: 'create',\n serverStampedKeys,\n }),\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Created record with generated fields (id, createdAt, etc.)',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n private static resolveUpdateByIdConfig<\n C extends ICustomizableRoutes['updateById'],\n SelectSchema extends TAnyObjectSchema,\n UpdateSchema extends TAnyObjectSchema,\n >(opts: {\n idType: TIdSchemaType;\n config: C;\n selectSchema: SelectSchema;\n updateSchema: UpdateSchema;\n serverStampedKeys: string[];\n }) {\n const { config, selectSchema, updateSchema, idType, serverStampedKeys } = opts;\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n params: RouteConfigResolver.resolveIdParams({ config, idType }),\n body:\n config?.request?.body ??\n RouteConfigResolver.toWriteBodySchema({\n schema: updateSchema,\n route: 'updateById',\n serverStampedKeys,\n }),\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Updated record with all current fields',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n private static resolveUpdateByConfig<\n C extends ICustomizableRoutes['updateBy'],\n SelectSchema extends TAnyObjectSchema,\n UpdateSchema extends TAnyObjectSchema,\n >(opts: {\n config: C;\n selectSchema: SelectSchema;\n updateSchema: UpdateSchema;\n serverStampedKeys: string[];\n }) {\n const { config, selectSchema, updateSchema, serverStampedKeys } = opts;\n const defaultQuery = z.object({ where: WhereSchema.optional() }).openapi({\n description:\n 'Where condition selecting the records to update - here or in the body, not both',\n });\n\n // Built only without a custom body: a custom body must not trip the entity schema's checks.\n const buildDefaultBody = () => {\n const writableSchema = RouteConfigResolver.toWriteBodySchema({\n schema: updateSchema,\n route: 'updateBy',\n serverStampedKeys,\n });\n\n // A model with a real `where` column keeps it: the body reserves the name only when it is\n // free, and the handler then simply finds no `where` there.\n return 'where' in writableSchema.shape\n ? writableSchema\n : writableSchema.extend({ where: WhereSchema.optional() });\n };\n\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(z.array(selectSchema));\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n body: config?.request?.body ?? buildDefaultBody(),\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Array of updated records',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n private static resolveDeleteByIdConfig<\n C extends ICustomizableRoutes['deleteById'],\n SelectSchema extends TAnyObjectSchema,\n >(opts: { idType: TIdSchemaType; config: C; selectSchema: SelectSchema }) {\n const { config, selectSchema, idType } = opts;\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n params: RouteConfigResolver.resolveIdParams({ config, idType }),\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Deleted record data',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n private static resolveDeleteByConfig<\n C extends ICustomizableRoutes['deleteBy'],\n SelectSchema extends TAnyObjectSchema,\n >(opts: { config: C; selectSchema: SelectSchema }) {\n const { config, selectSchema } = opts;\n const defaultQuery = z.object({ where: WhereSchema.optional() }).openapi({\n description:\n 'Where condition selecting the records to delete - here or in the body, not both',\n });\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(z.array(selectSchema));\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n // No DEFAULT body schema. Declaring one makes `@hono/zod-openapi` gate the media type, and a\n // client that sends `content-type: application/json` with no body then gets 400 where it used\n // to get 200. The handler reads the body itself; name one here to get the Swagger editor.\n body: config?.request?.body,\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Array of deleted records',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n /**\n * Generates complete route configurations for a CRUD controller. `serverStampedKeys` - what the\n * entity reports from `getServerStampedKeys()`; the default write bodies leave them out.\n */\n static defineControllerRouteConfigs<\n Routes extends ICustomizableRoutes,\n SelectSchema extends TAnyObjectSchema,\n CreateSchema extends TAnyObjectSchema,\n UpdateSchema extends TAnyObjectSchema,\n >(opts: {\n isStrict: boolean;\n idType: TIdSchemaType;\n authenticate?: { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n authorize?: IAuthorizationSpec | IAuthorizationSpec[];\n schema: { select: SelectSchema; create: CreateSchema; update: UpdateSchema };\n serverStampedKeys?: string[];\n routes?: Routes;\n }) {\n const {\n isStrict,\n idType,\n authenticate: controllerAuth = {},\n authorize: controllerAuthorize,\n schema: { select: selectSchema, create: createSchema, update: updateSchema },\n serverStampedKeys = [],\n routes,\n } = opts;\n const { strategies: defaultStrategies = [], mode: defaultMode } = controllerAuth;\n\n // `Routes` is caller-bound but otherwise unconstrained here, so `{}` cannot be proven to satisfy it structurally even though every field ICustomizableRoutes declares is optional.\n const routesConfig = (routes ?? {}) as Routes;\n\n type TAuthenticateConfig = { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n\n /** Priority: endpoint authenticate > controller authenticate. */\n const resolveRouteAuth = (routeKey: keyof ICustomizableRoutes): TAuthenticateConfig => {\n const endpointConfig = routesConfig[routeKey];\n const authConfig = endpointConfig?.authenticate;\n\n if (authConfig == null) {\n return { strategies: defaultStrategies, mode: defaultMode };\n }\n\n if (authConfig.skip === true) {\n return { strategies: [] };\n }\n\n return {\n strategies: authConfig.strategies ?? defaultStrategies,\n mode: authConfig.mode ?? defaultMode,\n };\n };\n\n type TAuthorizeConfig = IAuthorizationSpec | IAuthorizationSpec[] | undefined;\n\n /** Priority: endpoint authenticate.skip > endpoint authorize.skip > endpoint authorize > controller authorize. */\n const resolveRouteAuthorize = (routeKey: keyof ICustomizableRoutes): TAuthorizeConfig => {\n const endpointConfig = routesConfig[routeKey];\n\n if (endpointConfig?.authenticate?.skip === true) {\n return undefined;\n }\n\n const authorize = endpointConfig?.authorize;\n\n if (authorize == null) {\n return controllerAuthorize;\n }\n\n if (Array.isArray(authorize)) {\n return authorize;\n }\n\n if ('skip' in authorize) {\n return undefined;\n }\n\n return authorize;\n };\n\n const count = RouteConfigResolver.resolveCountConfig({ config: routesConfig.count, isStrict });\n const find = RouteConfigResolver.resolveFindConfig({ config: routesConfig.find, selectSchema });\n const findById = RouteConfigResolver.resolveFindByIdConfig({\n config: routesConfig.findById,\n selectSchema,\n idType,\n });\n const findOne = RouteConfigResolver.resolveFindOneConfig({\n config: routesConfig.findOne,\n selectSchema,\n });\n const create = RouteConfigResolver.resolveCreateConfig({\n config: routesConfig.create,\n selectSchema,\n createSchema,\n serverStampedKeys,\n });\n const updateById = RouteConfigResolver.resolveUpdateByIdConfig({\n config: routesConfig.updateById,\n selectSchema,\n updateSchema,\n idType,\n serverStampedKeys,\n });\n const updateBy = RouteConfigResolver.resolveUpdateByConfig({\n config: routesConfig.updateBy,\n selectSchema,\n updateSchema,\n serverStampedKeys,\n });\n const deleteById = RouteConfigResolver.resolveDeleteByIdConfig({\n config: routesConfig.deleteById,\n selectSchema,\n idType,\n });\n const deleteBy = RouteConfigResolver.resolveDeleteByConfig({\n config: routesConfig.deleteBy,\n selectSchema,\n });\n\n const rs = {\n COUNT: {\n method: HTTP.Methods.GET,\n path: RestPaths.COUNT,\n description: 'Count records matching where condition',\n authenticate: resolveRouteAuth('count'),\n authorize: resolveRouteAuthorize('count'),\n request: count.request,\n responses: OpenApiResponses.jsonResponse(count.response),\n },\n\n FIND: {\n method: HTTP.Methods.GET,\n path: RestPaths.ROOT,\n description: 'Find records with filter, pagination, sorting, and relations',\n authenticate: resolveRouteAuth('find'),\n authorize: resolveRouteAuthorize('find'),\n request: find.request,\n responses: OpenApiResponses.jsonResponse(find.response),\n },\n\n FIND_BY_ID: {\n method: HTTP.Methods.GET,\n path: '/{id}',\n description: 'Find single record by ID',\n authenticate: resolveRouteAuth('findById'),\n authorize: resolveRouteAuthorize('findById'),\n request: findById.request,\n responses: OpenApiResponses.jsonResponse(findById.response),\n },\n\n FIND_ONE: {\n method: HTTP.Methods.GET,\n path: RestPaths.FIND_ONE,\n description: 'Find first record matching filter',\n authenticate: resolveRouteAuth('findOne'),\n authorize: resolveRouteAuthorize('findOne'),\n request: findOne.request,\n responses: OpenApiResponses.jsonResponse(findOne.response),\n },\n\n CREATE: {\n method: HTTP.Methods.POST,\n path: RestPaths.ROOT,\n description: 'Create new record',\n authenticate: resolveRouteAuth('create'),\n authorize: resolveRouteAuthorize('create'),\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Record data (required fields must be provided)',\n schema: create.request.body,\n }),\n headers: create.request.headers,\n },\n responses: OpenApiResponses.jsonResponse(create.response),\n },\n\n UPDATE_BY_ID: {\n method: HTTP.Methods.PATCH,\n path: '/{id}',\n description: 'Partial update record by ID',\n authenticate: resolveRouteAuth('updateById'),\n authorize: resolveRouteAuthorize('updateById'),\n request: {\n params: updateById.request.params,\n body: OpenApiResponses.jsonContent({\n description: 'Partial data (only changed fields)',\n schema: updateById.request.body,\n }),\n headers: updateById.request.headers,\n },\n responses: OpenApiResponses.jsonResponse(updateById.response),\n },\n\n UPDATE_BY: {\n method: HTTP.Methods.PATCH,\n path: RestPaths.ROOT,\n description: 'Bulk update records matching where condition',\n authenticate: resolveRouteAuth('updateBy'),\n authorize: resolveRouteAuthorize('updateBy'),\n request: {\n query: updateBy.request.query,\n body: OpenApiResponses.jsonContent({\n description: 'Partial data to apply to all matches',\n schema: updateBy.request.body,\n }),\n headers: updateBy.request.headers,\n },\n responses: OpenApiResponses.jsonResponse(updateBy.response),\n },\n\n DELETE_BY_ID: {\n method: HTTP.Methods.DELETE,\n path: '/{id}',\n description: 'Delete record by ID (irreversible)',\n authenticate: resolveRouteAuth('deleteById'),\n authorize: resolveRouteAuthorize('deleteById'),\n request: deleteById.request,\n responses: OpenApiResponses.jsonResponse(deleteById.response),\n },\n\n DELETE_BY: {\n method: HTTP.Methods.DELETE,\n path: RestPaths.ROOT,\n description: 'Bulk delete records matching where condition (irreversible)',\n authenticate: resolveRouteAuth('deleteBy'),\n authorize: resolveRouteAuthorize('deleteBy'),\n request: {\n query: deleteBy.request.query,\n ...(deleteBy.request.body\n ? {\n body: OpenApiResponses.jsonContent({\n description: 'Where condition, when it does not fit in the query',\n schema: deleteBy.request.body,\n required: false,\n }),\n }\n : {}),\n headers: deleteBy.request.headers,\n },\n responses: OpenApiResponses.jsonResponse(deleteBy.response),\n },\n } as const;\n\n return rs;\n }\n}\n"]}
1
+ {"version":3,"file":"definition.js","sourceRoot":"","sources":["../../../../../src/base/controllers/factory/definition.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,WAAW,EAAE,MAAM,mCAAmC,CAAC;AAEnF,OAAO,EAAE,CAAC,EAAE,MAAM,mBAAmB,CAAC;AACtC,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EACL,qBAAqB,EACrB,qBAAqB,EACrB,mBAAmB,EACnB,SAAS,EACT,gBAAgB,GACjB,MAAM,WAAW,CAAC;AAWnB;;;;GAIG;AACH,MAAM,OAAO,mBAAmB;IAC9B,mLAAmL;IAC3K,MAAM,CAAC,kBAAkB,CAAC,IAA+B;QAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAExB,IAAI,MAAM,KAAK,QAAQ,EAAE,CAAC;YACxB,OAAO,cAAc,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;QAC7C,CAAC;QAED,OAAO,CAAC,CAAC,MAAM,CAAC;YACd,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,OAAO,CAAC;gBAC5B,KAAK,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,+BAA+B,EAAE;gBAC/E,QAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,E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3B,IAAI,EAAE,OAAO;gBACb,WAAW,EAAE,oCAAoC;gBACjD,YAAY,EAAE,gBAAgB,CAAC,YAAY,CAAC;gBAC5C,SAAS,EAAE,qBAAqB,CAAC,YAAY,CAAC;gBAC9C,OAAO,EAAE,UAAU,CAAC,OAAO;gBAC3B,SAAS,EAAE,gBAAgB,CAAC,YAAY,CAAC,UAAU,CAAC,QAAQ,CAAC;aAC9D;YAED,SAAS,EAAE;gBACT,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,MAAM;gBAC3B,IAAI,EAAE,SAAS,CAAC,IAAI;gBACpB,WAAW,EAAE,6DAA6D;gBAC1E,YAAY,EAAE,gBAAgB,CAAC,UAAU,CAAC;gBAC1C,SAAS,EAAE,qBAAqB,CAAC,UAAU,CAAC;gBAC5C,OAAO,EAAE;oBACP,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,KAAK;oBAC7B,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI;wBACvB,CAAC,CAAC;4BACE,IAAI,EAAE,gBAAgB,CAAC,WAAW,CAAC;gCACjC,WAAW,EAAE,oDAAoD;gCACjE,MAAM,EAAE,QAAQ,CAAC,OAAO,CAAC,IAAI;gCAC7B,QAAQ,EAAE,KAAK;6BAChB,CAAC;yBACH;wBACH,CAAC,CAAC,EAAE,CAAC;oBACP,OAAO,EAAE,QAAQ,CAAC,OAAO,CAAC,OAAO;iBAClC;gBACD,SAAS,EAAE,gBAAgB,CAAC,YAAY,CAAC,QAAQ,CAAC,QAAQ,CAAC;aAC5D;SACO,CAAC;QAEX,OAAO,EAAE,CAAC;IACZ,CAAC;CACF","sourcesContent":["import type { TAuthMode, TAuthStrategy } from '@/base/auth/authenticate/common/constants';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport type { TIdSchemaType } from '@/base/models/common';\nimport { OpenApiResponses, OpenApiSchemas } from '@/base/models/common';\nimport { CountSchema } from '@/base/repositories/common';\nimport { FilterQuerySchema, WhereSchema } from '@/base/repositories/query-schemas';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { z } from '@hono/zod-openapi';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { ICustomizableRoutes } from '../common';\nimport {\n commonResponseHeaders,\n defaultRequestHeaders,\n findResponseHeaders,\n RestPaths,\n trackableHeaders,\n} from '../common';\n\n/** Picks user-overridden response schema if present (and non-undefined), else the default. */\ntype TResolvedResponseSchema<C, D extends z.ZodType> = C extends {\n response: {\n schema: infer S extends z.ZodType;\n };\n}\n ? S\n : D;\n\n/**\n * Every method here is an unbound static, called from the exported aliases below without a\n * receiver - a method must call another via `RouteConfigResolver.other(...)`, never\n * `this.other(...)`, or `this` is `undefined` at the call site.\n */\nexport class RouteConfigResolver {\n /** Path params always reach the validator as strings, so a number-typed id must be coerced before `z.number()` sees it - `OpenApiSchemas.idParams` alone rejects `/accounts/7`. */\n private static idPathParamsSchema(opts: { idType: TIdSchemaType }) {\n const { idType } = opts;\n\n if (idType !== 'number') {\n return OpenApiSchemas.idParams({ idType });\n }\n\n return z.object({\n id: z.coerce.number().openapi({\n param: { name: 'id', in: 'path', description: 'The unique id of the resource' },\n examples: [1, 2, 3],\n }),\n });\n }\n\n /**\n * The default body of a write route: the entity schema without the keys the entity stamps, and on\n * an update without `id` - the path or `where` names the rows. Zod strips a left-out key a client\n * sends. With nothing to leave out the schema itself is the body, refinements and OpenAPI name kept.\n */\n private static toWriteBodySchema(opts: {\n schema: TAnyObjectSchema;\n route: keyof ICustomizableRoutes;\n serverStampedKeys: string[];\n }): TAnyObjectSchema {\n const { schema, route, serverStampedKeys } = opts;\n const droppedKeys = route === 'create' ? serverStampedKeys : [...serverStampedKeys, 'id'];\n // A `.transform()` pipe has no shape to read, so every key it might hold counts.\n const isObjectSchema = schema instanceof z.ZodObject;\n const omittedKeys = isObjectSchema\n ? droppedKeys.filter((key) => Object.hasOwn(schema.shape, key))\n : droppedKeys;\n\n if (omittedKeys.length === 0) {\n return schema;\n }\n\n if (!isObjectSchema || schema.def.checks?.length) {\n throw getError({\n message: `[RouteConfigResolver.defineControllerRouteConfigs] Cannot build the default ${route} body | keys to leave out: ${omittedKeys.join(', ')} | The schema is refined or transformed, so zod cannot remove them | Pass routes.${route}.request.body`,\n });\n }\n\n const mask: Record<string, true> = {};\n\n for (const key of omittedKeys) {\n mask[key] = true;\n }\n\n return schema.omit(mask);\n }\n\n /** Picks the caller's per-route `request.params` override, else the entity's id path-param schema. */\n private static resolveIdParams<\n C extends { request?: { params?: TAnyObjectSchema } } | undefined,\n >(opts: { config: C; idType: TIdSchemaType }) {\n const { config, idType } = opts;\n\n return config?.request?.params ?? RouteConfigResolver.idPathParamsSchema({ idType });\n }\n\n /** Creates conditional count response schema. */\n static conditionalCountResponse<T extends z.ZodType>(dataSchema: T) {\n return z.union([\n CountSchema.extend({ data: dataSchema }).openapi({\n description: 'Response with count (when x-request-count header is \"true\" or omitted)',\n }),\n dataSchema.openapi({\n description: 'Data only response (when x-request-count header is \"false\")',\n }),\n ]);\n }\n\n /** Resolves a route's response schema - user override or default. Holds the one cast every `resolve*Config` needs: generic `C` is only known by its wider structural constraint, so it cannot be proven at the value level to collapse to `TResolvedResponseSchema`. */\n private static resolveResponseSchema<\n C extends { response?: { schema?: z.ZodType } } | undefined,\n D extends z.ZodType,\n >(opts: { config: C; defaultSchema: D }): TResolvedResponseSchema<C, D> {\n const { config, defaultSchema } = opts;\n\n return (config?.response?.schema ?? defaultSchema) as TResolvedResponseSchema<C, D>;\n }\n\n static resolveCountConfig<C extends ICustomizableRoutes['count']>(opts: {\n config: C;\n isStrict: boolean;\n }) {\n const { config, isStrict } = opts;\n const defaultQuery = z\n .object({\n where: isStrict\n ? WhereSchema\n : z.optional(WhereSchema).openapi({ description: 'Filter conditions' }),\n })\n .openapi({ description: 'Count query params' });\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n headers: config?.request?.headers ?? trackableHeaders,\n },\n response: {\n description: 'Total count of matching records',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema: CountSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n static resolveFindConfig<\n C extends ICustomizableRoutes['find'],\n FindSchema extends TAnyObjectSchema,\n >(opts: { config: C; selectSchema: FindSchema }) {\n const { config, selectSchema } = opts;\n const defaultQuery = FilterQuerySchema;\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(z.array(selectSchema));\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Array of matching records (with optional count)',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? findResponseHeaders,\n },\n };\n }\n\n static resolveFindByIdConfig<\n C extends ICustomizableRoutes['findById'],\n FindByIdSchema extends TAnyObjectSchema,\n >(opts: { idType: TIdSchemaType; config: C; selectSchema: FindByIdSchema }) {\n const { config, selectSchema, idType } = opts;\n const defaultQuery = FilterQuerySchema.openapi({\n description: 'Filter with fields, order, include (where ignored)',\n });\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n params: RouteConfigResolver.resolveIdParams({ config, idType }),\n query: config?.request?.query ?? defaultQuery,\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Single record matching ID or null',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n static resolveFindOneConfig<\n C extends ICustomizableRoutes['findOne'],\n FindOneSchema extends TAnyObjectSchema,\n >(opts: { config: C; selectSchema: FindOneSchema }) {\n const { config, selectSchema } = opts;\n const defaultQuery = FilterQuerySchema.openapi({\n description: 'Filter with where, fields, order, include',\n });\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'First matching record or null',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n /** `serverStampedKeys` - the keys the default body leaves out. */\n static resolveCreateConfig<\n C extends ICustomizableRoutes['create'],\n SelectSchema extends TAnyObjectSchema,\n CreateSchema extends TAnyObjectSchema,\n >(opts: {\n config: C;\n selectSchema: SelectSchema;\n createSchema: CreateSchema;\n serverStampedKeys?: string[];\n }) {\n const { config, selectSchema, createSchema, serverStampedKeys = [] } = opts;\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n body:\n config?.request?.body ??\n RouteConfigResolver.toWriteBodySchema({\n schema: createSchema,\n route: 'create',\n serverStampedKeys,\n }),\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Created record with generated fields (id, createdAt, etc.)',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n private static resolveUpdateByIdConfig<\n C extends ICustomizableRoutes['updateById'],\n SelectSchema extends TAnyObjectSchema,\n UpdateSchema extends TAnyObjectSchema,\n >(opts: {\n idType: TIdSchemaType;\n config: C;\n selectSchema: SelectSchema;\n updateSchema: UpdateSchema;\n serverStampedKeys: string[];\n }) {\n const { config, selectSchema, updateSchema, idType, serverStampedKeys } = opts;\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n params: RouteConfigResolver.resolveIdParams({ config, idType }),\n body:\n config?.request?.body ??\n RouteConfigResolver.toWriteBodySchema({\n schema: updateSchema,\n route: 'updateById',\n serverStampedKeys,\n }),\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Updated record with all current fields',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n private static resolveUpdateByConfig<\n C extends ICustomizableRoutes['updateBy'],\n SelectSchema extends TAnyObjectSchema,\n UpdateSchema extends TAnyObjectSchema,\n >(opts: {\n config: C;\n selectSchema: SelectSchema;\n updateSchema: UpdateSchema;\n serverStampedKeys: string[];\n }) {\n const { config, selectSchema, updateSchema, serverStampedKeys } = opts;\n const defaultQuery = z.object({ where: WhereSchema.optional() }).openapi({\n description:\n 'Where condition selecting the records to update - here or in the body, not both',\n });\n\n // Built only without a custom body: a custom body must not trip the entity schema's checks.\n const buildDefaultBody = () => {\n const writableSchema = RouteConfigResolver.toWriteBodySchema({\n schema: updateSchema,\n route: 'updateBy',\n serverStampedKeys,\n });\n\n // A model with a real `where` column keeps it: the body reserves the name only when it is\n // free, and the handler then simply finds no `where` there.\n return 'where' in writableSchema.shape\n ? writableSchema\n : writableSchema.extend({ where: WhereSchema.optional() });\n };\n\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(z.array(selectSchema));\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n body: config?.request?.body ?? buildDefaultBody(),\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Array of updated records',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n private static resolveDeleteByIdConfig<\n C extends ICustomizableRoutes['deleteById'],\n SelectSchema extends TAnyObjectSchema,\n >(opts: { idType: TIdSchemaType; config: C; selectSchema: SelectSchema }) {\n const { config, selectSchema, idType } = opts;\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(selectSchema);\n\n return {\n request: {\n params: RouteConfigResolver.resolveIdParams({ config, idType }),\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Deleted record data',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n private static resolveDeleteByConfig<\n C extends ICustomizableRoutes['deleteBy'],\n SelectSchema extends TAnyObjectSchema,\n >(opts: { config: C; selectSchema: SelectSchema }) {\n const { config, selectSchema } = opts;\n const defaultQuery = z.object({ where: WhereSchema.optional() }).openapi({\n description:\n 'Where condition selecting the records to delete - here or in the body, not both',\n });\n const defaultSchema = RouteConfigResolver.conditionalCountResponse(z.array(selectSchema));\n\n return {\n request: {\n query: config?.request?.query ?? defaultQuery,\n // No DEFAULT body schema. Declaring one makes `@hono/zod-openapi` gate the media type, and a\n // client that sends `content-type: application/json` with no body then gets 400 where it used\n // to get 200. The handler reads the body itself; name one here to get the Swagger editor.\n body: config?.request?.body,\n headers: config?.request?.headers ?? defaultRequestHeaders,\n },\n response: {\n description: 'Array of deleted records',\n schema: RouteConfigResolver.resolveResponseSchema({ config, defaultSchema }),\n headers: config?.response?.headers ?? commonResponseHeaders,\n },\n };\n }\n\n /**\n * Generates complete route configurations for a CRUD controller. `serverStampedKeys` - the keys the default\n * write bodies leave out.\n */\n static defineControllerRouteConfigs<\n Routes extends ICustomizableRoutes,\n SelectSchema extends TAnyObjectSchema,\n CreateSchema extends TAnyObjectSchema,\n UpdateSchema extends TAnyObjectSchema,\n >(opts: {\n isStrict: boolean;\n idType: TIdSchemaType;\n authenticate?: { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n authorize?: IAuthorizationSpec | IAuthorizationSpec[];\n schema: { select: SelectSchema; create: CreateSchema; update: UpdateSchema };\n serverStampedKeys?: string[];\n routes?: Routes;\n }) {\n const {\n isStrict,\n idType,\n authenticate: controllerAuth = {},\n authorize: controllerAuthorize,\n schema: { select: selectSchema, create: createSchema, update: updateSchema },\n serverStampedKeys = [],\n routes,\n } = opts;\n const { strategies: defaultStrategies = [], mode: defaultMode } = controllerAuth;\n\n // `Routes` is caller-bound but otherwise unconstrained here, so `{}` cannot be proven to satisfy it structurally even though every field ICustomizableRoutes declares is optional.\n const routesConfig = (routes ?? {}) as Routes;\n\n type TAuthenticateConfig = { strategies?: TAuthStrategy[]; mode?: TAuthMode };\n\n /** Priority: endpoint authenticate > controller authenticate. */\n const resolveRouteAuth = (routeKey: keyof ICustomizableRoutes): TAuthenticateConfig => {\n const endpointConfig = routesConfig[routeKey];\n const authConfig = endpointConfig?.authenticate;\n\n if (authConfig == null) {\n return { strategies: defaultStrategies, mode: defaultMode };\n }\n\n if (authConfig.skip === true) {\n return { strategies: [] };\n }\n\n return {\n strategies: authConfig.strategies ?? defaultStrategies,\n mode: authConfig.mode ?? defaultMode,\n };\n };\n\n type TAuthorizeConfig = IAuthorizationSpec | IAuthorizationSpec[] | undefined;\n\n /** Priority: endpoint authenticate.skip > endpoint authorize.skip > endpoint authorize > controller authorize. */\n const resolveRouteAuthorize = (routeKey: keyof ICustomizableRoutes): TAuthorizeConfig => {\n const endpointConfig = routesConfig[routeKey];\n\n if (endpointConfig?.authenticate?.skip === true) {\n return undefined;\n }\n\n const authorize = endpointConfig?.authorize;\n\n if (authorize == null) {\n return controllerAuthorize;\n }\n\n if (Array.isArray(authorize)) {\n return authorize;\n }\n\n if ('skip' in authorize) {\n return undefined;\n }\n\n return authorize;\n };\n\n const count = RouteConfigResolver.resolveCountConfig({ config: routesConfig.count, isStrict });\n const find = RouteConfigResolver.resolveFindConfig({ config: routesConfig.find, selectSchema });\n const findById = RouteConfigResolver.resolveFindByIdConfig({\n config: routesConfig.findById,\n selectSchema,\n idType,\n });\n const findOne = RouteConfigResolver.resolveFindOneConfig({\n config: routesConfig.findOne,\n selectSchema,\n });\n const create = RouteConfigResolver.resolveCreateConfig({\n config: routesConfig.create,\n selectSchema,\n createSchema,\n serverStampedKeys,\n });\n const updateById = RouteConfigResolver.resolveUpdateByIdConfig({\n config: routesConfig.updateById,\n selectSchema,\n updateSchema,\n idType,\n serverStampedKeys,\n });\n const updateBy = RouteConfigResolver.resolveUpdateByConfig({\n config: routesConfig.updateBy,\n selectSchema,\n updateSchema,\n serverStampedKeys,\n });\n const deleteById = RouteConfigResolver.resolveDeleteByIdConfig({\n config: routesConfig.deleteById,\n selectSchema,\n idType,\n });\n const deleteBy = RouteConfigResolver.resolveDeleteByConfig({\n config: routesConfig.deleteBy,\n selectSchema,\n });\n\n const rs = {\n COUNT: {\n method: HTTP.Methods.GET,\n path: RestPaths.COUNT,\n description: 'Count records matching where condition',\n authenticate: resolveRouteAuth('count'),\n authorize: resolveRouteAuthorize('count'),\n request: count.request,\n responses: OpenApiResponses.jsonResponse(count.response),\n },\n\n FIND: {\n method: HTTP.Methods.GET,\n path: RestPaths.ROOT,\n description: 'Find records with filter, pagination, sorting, and relations',\n authenticate: resolveRouteAuth('find'),\n authorize: resolveRouteAuthorize('find'),\n request: find.request,\n responses: OpenApiResponses.jsonResponse(find.response),\n },\n\n FIND_BY_ID: {\n method: HTTP.Methods.GET,\n path: '/{id}',\n description: 'Find single record by ID',\n authenticate: resolveRouteAuth('findById'),\n authorize: resolveRouteAuthorize('findById'),\n request: findById.request,\n responses: OpenApiResponses.jsonResponse(findById.response),\n },\n\n FIND_ONE: {\n method: HTTP.Methods.GET,\n path: RestPaths.FIND_ONE,\n description: 'Find first record matching filter',\n authenticate: resolveRouteAuth('findOne'),\n authorize: resolveRouteAuthorize('findOne'),\n request: findOne.request,\n responses: OpenApiResponses.jsonResponse(findOne.response),\n },\n\n CREATE: {\n method: HTTP.Methods.POST,\n path: RestPaths.ROOT,\n description: 'Create new record',\n authenticate: resolveRouteAuth('create'),\n authorize: resolveRouteAuthorize('create'),\n request: {\n body: OpenApiResponses.jsonContent({\n description: 'Record data (required fields must be provided)',\n schema: create.request.body,\n }),\n headers: create.request.headers,\n },\n responses: OpenApiResponses.jsonResponse(create.response),\n },\n\n UPDATE_BY_ID: {\n method: HTTP.Methods.PATCH,\n path: '/{id}',\n description: 'Partial update record by ID',\n authenticate: resolveRouteAuth('updateById'),\n authorize: resolveRouteAuthorize('updateById'),\n request: {\n params: updateById.request.params,\n body: OpenApiResponses.jsonContent({\n description: 'Partial data (only changed fields)',\n schema: updateById.request.body,\n }),\n headers: updateById.request.headers,\n },\n responses: OpenApiResponses.jsonResponse(updateById.response),\n },\n\n UPDATE_BY: {\n method: HTTP.Methods.PATCH,\n path: RestPaths.ROOT,\n description: 'Bulk update records matching where condition',\n authenticate: resolveRouteAuth('updateBy'),\n authorize: resolveRouteAuthorize('updateBy'),\n request: {\n query: updateBy.request.query,\n body: OpenApiResponses.jsonContent({\n description: 'Partial data to apply to all matches',\n schema: updateBy.request.body,\n }),\n headers: updateBy.request.headers,\n },\n responses: OpenApiResponses.jsonResponse(updateBy.response),\n },\n\n DELETE_BY_ID: {\n method: HTTP.Methods.DELETE,\n path: '/{id}',\n description: 'Delete record by ID (irreversible)',\n authenticate: resolveRouteAuth('deleteById'),\n authorize: resolveRouteAuthorize('deleteById'),\n request: deleteById.request,\n responses: OpenApiResponses.jsonResponse(deleteById.response),\n },\n\n DELETE_BY: {\n method: HTTP.Methods.DELETE,\n path: RestPaths.ROOT,\n description: 'Bulk delete records matching where condition (irreversible)',\n authenticate: resolveRouteAuth('deleteBy'),\n authorize: resolveRouteAuthorize('deleteBy'),\n request: {\n query: deleteBy.request.query,\n ...(deleteBy.request.body\n ? {\n body: OpenApiResponses.jsonContent({\n description: 'Where condition, when it does not fit in the query',\n schema: deleteBy.request.body,\n required: false,\n }),\n }\n : {}),\n headers: deleteBy.request.headers,\n },\n responses: OpenApiResponses.jsonResponse(deleteBy.response),\n },\n } as const;\n\n return rs;\n }\n}\n"]}
@@ -32,6 +32,11 @@ export const model = (input = {}) => {
32
32
  metadata: input,
33
33
  });
34
34
  const { settings } = metadata;
35
+ if (settings && Reflect.has(settings, 'hiddenProperties')) {
36
+ throw getError({
37
+ message: `[model][${target.name}] hiddenProperties was replaced by properties.hidden`,
38
+ });
39
+ }
35
40
  const defaultLimit = settings?.query?.limit?.default;
36
41
  if (defaultLimit !== undefined && (!Number.isInteger(defaultLimit) || defaultLimit <= 0)) {
37
42
  throw getError({
@@ -1 +1 @@
1
- {"version":3,"file":"persistents.js","sourceRoot":"","sources":["../../../../src/base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AAyB,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IAE3E,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,GAAG,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;AAC7F,CAAC,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,CAIxB,QAAiD,EACjC,EAAE;IAClB,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,MAAM,QAAQ,GAAG,gBAAgB,CAAC,WAAW,EAAE,CAAC;QAEhD,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,uBAAuB,CAAC;gBACtB,QAAQ,EAAE,yBAAyB,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;gBACzD,YAAY,EAAE,EAAE;gBAChB,MAAM;gBACN,QAAQ;aACT,CAAC,CAAC;YAEH,OAAO;QACT,CAAC;QAED,uBAAuB,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IAClF,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { BindingNamespaces } from '@/common/bindings';\nimport type {\n IArtifactRegistrationOptions,\n IDataSourceMetadata,\n IModelMetadata,\n IResolvedRepositoryMetadata,\n TRepositoryMetadata,\n} from '@/helpers/inversion';\nimport { ArtifactTypes, BindingKeys, MetadataKeys, MetadataRegistry } from '@/helpers/inversion';\nimport { ClassResolver, ResolverUtility } from '@venizia/ignis-helpers/common';\nimport type { IInjectMetadata } from '@venizia/ignis-inversion';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IDataSource } from '../datasources';\nimport { DataSourceOpenModes, isDataSourceClass } from '../datasources';\nimport type { AbstractEntity } from '../models';\nimport { RepositoryTypes } from '../repositories/common/constants';\nimport { injectable, InjectableUtility } from './injectable';\nimport { ModelMetadataUtility } from './model-metadata';\n\n/**\n * Registers a model class with its static schema and relations.\n *\n * @example\n * ```typescript\n * import { model } from '@venizia/ignis';\n * import { ModelFactory } from '@venizia/ignis-connectors/postgres';\n * import { pgTable, serial, text } from 'drizzle-orm/pg-core';\n *\n * const noteTable = pgTable('Note', { id: serial('id').primaryKey(), body: text('body') });\n *\n * export @model({ settings: { query: { limit: { default: 20 } } } })\n * class Note extends ModelFactory.defineEntity({ table: noteTable }) {}\n * ```\n */\nexport const model = (input: IModelMetadata = {}): ClassDecorator => {\n return (target) => {\n injectable({\n type: ArtifactTypes.MODEL,\n ...InjectableUtility.pickRegistrationOptions({ metadata: input }),\n })(target);\n\n const metadata = ModelMetadataUtility.normalizeModelMetadata({\n model: target.name,\n metadata: input,\n });\n\n const { settings } = metadata;\n\n const defaultLimit = settings?.query?.limit?.default;\n\n if (defaultLimit !== undefined && (!Number.isInteger(defaultLimit) || defaultLimit <= 0)) {\n throw getError({\n message: `[model][${target.name}] Invalid 'query.limit.default' | Expected a positive integer | Got: ${defaultLimit}`,\n });\n }\n\n // Validated at DECORATION time, like the default limit: a bad ceiling is a wiring mistake, and\n // catching it at boot beats catching it on the one request that happens to reach the limit.\n const maxLimit = settings?.query?.limit?.max;\n\n if (maxLimit !== undefined && (!Number.isInteger(maxLimit) || maxLimit <= 0)) {\n throw getError({\n message: `[model][${target.name}] Invalid 'query.limit.max' | Expected a positive integer | Got: ${maxLimit}`,\n });\n }\n\n // Auto-populate AUTHORIZATION_SUBJECT from authorize.principal if not already set\n const principal = settings?.authorize?.principal;\n\n if (principal && !Object.hasOwn(target, 'AUTHORIZATION_SUBJECT')) {\n (target as Record<string, unknown>).AUTHORIZATION_SUBJECT = principal;\n }\n\n MetadataRegistry.getInstance().registerModel({ target, metadata });\n };\n};\n\n/**\n * Registers a datasource with driver and auto-discovery settings.\n *\n * @example\n * ```typescript\n * import { datasource } from '@venizia/ignis';\n * import { BasePostgresDataSource } from '@venizia/ignis-connectors/postgres';\n * import { NodePostgresDriver } from '@venizia/ignis-connectors/postgres/node-postgres';\n * import { Pool } from 'pg';\n *\n * export @datasource({ driver: NodePostgresDriver })\n * class AppDataSource extends BasePostgresDataSource<{ connectionString: string }> {\n * constructor() { super({ name: AppDataSource.name, config: { connectionString: 'postgres://localhost/app' } }); }\n * override configure(): void { this.client = new Pool(this.settings); }\n * override getConnectionString(): string { return this.settings.connectionString; }\n * }\n * ```\n */\nexport const datasource = (metadata?: IDataSourceMetadata): ClassDecorator => {\n return (target) => {\n const openTimeout = metadata?.open?.timeoutMs;\n\n if (\n openTimeout !== undefined &&\n (typeof openTimeout !== 'number' || !Number.isInteger(openTimeout) || openTimeout < 0)\n ) {\n throw getError({\n message: `[datasource][@datasource][${target.name}] Invalid metadata | 'open.timeoutMs' must be a non-negative integer (ms; 0 waits for ever) | Got: ${String(openTimeout)}`,\n });\n }\n\n const openMode = metadata?.open?.on;\n\n // Untyped JS callers: a misspelt mode would silently mean \"start\", so it is refused where it is written.\n if (openMode !== undefined && !DataSourceOpenModes.isValid(openMode)) {\n throw getError({\n message: `[datasource][@datasource][${target.name}] Invalid metadata | Unknown 'open.on': ${String(openMode)} | Expected one of: ${[...DataSourceOpenModes.SCHEME_SET].join(', ')}`,\n });\n }\n\n injectable({\n type: ArtifactTypes.DATASOURCE,\n ...InjectableUtility.pickRegistrationOptions({ metadata: metadata ?? {} }),\n })(target);\n MetadataRegistry.getInstance().setDataSourceMetadata({ target, metadata });\n };\n};\n\n/** Mirrors the `TRepositoryMetadata` union for JavaScript callers: a known type, a dataSource always, a model exactly when the type is RepositoryTypes.MODEL. */\nconst validateRepositoryMetadata = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(opts: {\n metadata: TRepositoryMetadata<Model, DataSource>;\n target: Function;\n}): void => {\n const { metadata, target } = opts;\n const type = metadata.type ?? RepositoryTypes.MODEL;\n\n if (!RepositoryTypes.isValid(type)) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Unknown 'type': ${type} | Expected one of: ${[...RepositoryTypes.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (type === RepositoryTypes.MODEL && !metadata.model) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Missing 'model'`,\n });\n }\n\n if (type === RepositoryTypes.REMOTE && metadata.model) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | A '${RepositoryTypes.REMOTE}' repository takes no 'model'`,\n });\n }\n\n if (!metadata.dataSource) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Missing 'dataSource'`,\n });\n }\n};\n\n/** Asserts the constructor's first parameter is an AbstractDataSource compatible with what @repository declared. */\nconst validateFirstConstructorParameter = (opts: {\n target: Function;\n firstParamType: Function;\n resolvedDataSource: string | Function;\n}): void => {\n const { target, firstParamType, resolvedDataSource } = opts;\n\n // NOT `instanceof`: two copies of this package give two `AbstractDataSource` classes and the\n // check would be false across them, rejecting a perfectly valid repository at import time.\n const isDataSourceType = isDataSourceClass(firstParamType);\n\n if (!isDataSourceType) {\n throw getError({\n message: `[@repository][${target.name}] Invalid constructor | First parameter must extend AbstractDataSource | Received: '${firstParamType.name}'`,\n });\n }\n\n if (typeof resolvedDataSource !== 'function') {\n return;\n }\n\n const isCompatible =\n firstParamType === resolvedDataSource || resolvedDataSource.prototype instanceof firstParamType;\n\n if (!isCompatible) {\n throw getError({\n message: `[@repository][${target.name}] Invalid constructor | Type mismatch | Constructor expects '${firstParamType.name}' but @repository specifies '${resolvedDataSource.name}'`,\n });\n }\n};\n\n/**\n * Auto-injects dataSource at constructor param[0] unless explicit @inject exists. A class is injected\n * by the class itself, so the container reads the key its registration recorded: a pinned\n * `binding` and a minified class name both resolve. Only a string reference is a key.\n */\nconst registerDataSourceInjection = (opts: {\n target: Function;\n registry: MetadataRegistry;\n dataSourceRef: TRepositoryMetadata['dataSource'];\n resolvedDataSource: string | Function;\n}): void => {\n const { target, registry, dataSourceRef, resolvedDataSource } = opts;\n\n // Own metadata only: `getInjectMetadata` walks the prototype chain, so a repository extending another @repository class would see the BASE's injection at param[0] and silently resolve the base's dataSource.\n const ownInjects: IInjectMetadata[] | undefined = Reflect.getOwnMetadata(\n MetadataKeys.INJECT,\n target,\n );\n const injectAtIndex0 = ownInjects?.find((entry) => entry?.index === 0);\n\n if (injectAtIndex0) {\n // `@inject({ target })` carries no key; read the one recorded on the class. The function form\n // resolves through the same helper the container uses, so both paths read one class.\n const injectedTarget = injectAtIndex0.target\n ? ResolverUtility.resolveInjectTarget({ target: injectAtIndex0.target })\n : undefined;\n const injectKey =\n injectAtIndex0.key ??\n (injectedTarget ? registry.getBindingKey({ target: injectedTarget }) : undefined);\n\n // A class is judged by its brand: its key may sit under any namespace a `binding` pinned, and\n // a provisional key may still change at registration. Only a bare key is judged by its prefix.\n const isDataSourceTarget = injectedTarget\n ? isDataSourceClass(injectedTarget)\n : typeof injectKey === 'string' && injectKey.startsWith(`${BindingNamespaces.DATASOURCE}.`);\n\n if (!isDataSourceTarget) {\n throw getError({\n message: `[@repository][${target.name}] Invalid constructor | First parameter must be a DataSource | Found @inject with key: '${String(injectKey)}' | Expected a key starting with '${BindingNamespaces.DATASOURCE}.' or a DataSource class`,\n });\n }\n\n return;\n }\n\n // Checked only when this decorator writes the injection: an explicit @inject decides for itself.\n // An interface emits `Object` and a type-only class import emits `Function` under tsc (`Object`\n // under bun); neither names the class, so neither is judged.\n const firstParamType = Reflect.getMetadata('design:paramtypes', target)?.[0];\n\n if (firstParamType && firstParamType !== Object && firstParamType !== Function) {\n validateFirstConstructorParameter({ target, firstParamType, resolvedDataSource });\n }\n\n // The inherited list is the base repository's own, and setInjectMetadata may write straight into it.\n if (!ownInjects) {\n Reflect.defineMetadata(\n MetadataKeys.INJECT,\n [...(registry.getInjectMetadata({ target }) ?? [])],\n target,\n );\n }\n\n const derivedKey = BindingKeys.build({\n namespace: BindingNamespaces.DATASOURCE,\n key: typeof resolvedDataSource === 'string' ? resolvedDataSource : resolvedDataSource.name,\n });\n\n // The class first, decided when the repository is resolved: by then any registration - decorated,\n // `bindingList()`, or `dataSource(X, { binding })` - has recorded its key on the class. The derived\n // key is the fallback for a class nothing recorded, bound by hand under exactly that key.\n registry.setInjectMetadata({\n target,\n index: 0,\n metadata:\n typeof dataSourceRef === 'string'\n ? { key: derivedKey, index: 0, isOptional: false }\n : { target: dataSourceRef, key: derivedKey, index: 0, isOptional: false },\n });\n};\n\n/** Resolves repository metadata and registers bindings for schema auto-discovery. */\nconst resolveRepositoryMetadata = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(opts: {\n metadata: TRepositoryMetadata<Model, DataSource>;\n target: Function;\n registry: MetadataRegistry;\n}): IResolvedRepositoryMetadata<Model, DataSource> => {\n const { metadata, target, registry } = opts;\n\n validateRepositoryMetadata({ metadata, target });\n\n const resolvedDataSource = ClassResolver.resolveClass({ ref: metadata.dataSource });\n\n if (!resolvedDataSource) {\n throw getError({\n message: `[@repository][${target.name}] The dataSource resolver returned nothing at decoration time | An import cycle leaves the datasource class undefined here; import it without the cycle, or name it as a string`,\n });\n }\n\n // No model, so no binding: the datasource owns no schema through this repository.\n if (metadata.type === RepositoryTypes.REMOTE) {\n registerDataSourceInjection({\n target,\n registry,\n dataSourceRef: metadata.dataSource,\n resolvedDataSource,\n });\n\n return {\n type: RepositoryTypes.REMOTE,\n dataSource: resolvedDataSource,\n operationScope: metadata.operationScope,\n };\n }\n\n const resolvedModel = ResolverUtility.resolveValue({ value: metadata.model });\n\n registry.registerRepositoryBinding({\n repository: target,\n model: resolvedModel,\n dataSource: resolvedDataSource,\n });\n\n registerDataSourceInjection({\n target,\n registry,\n dataSourceRef: metadata.dataSource,\n resolvedDataSource,\n });\n\n return {\n type: RepositoryTypes.MODEL,\n model: resolvedModel,\n dataSource: resolvedDataSource,\n operationScope: metadata.operationScope,\n };\n};\n\n/** A bare `@repository()` on a subclass reuses the type, model and datasource its nearest decorated parent declared; the registration options (`binding`, `when`, ...) are never inherited, so the subclass registers under its own name. */\nconst inheritRepositoryMetadata = (opts: {\n target: Function;\n registry: MetadataRegistry;\n}): TRepositoryMetadata => {\n // Own metadata does not exist yet at decoration time, so this read walks the prototype chain.\n const inherited = opts.registry.getRepositoryMetadata({ target: opts.target });\n\n if (!inherited) {\n throw getError({\n message: `[@repository][${opts.target.name}] No metadata given and no decorated repository above it in the prototype chain | pass { model, dataSource } or decorate the parent`,\n });\n }\n\n if (inherited.type === RepositoryTypes.REMOTE) {\n const { type, dataSource, operationScope } = inherited;\n\n return { type, dataSource, operationScope };\n }\n\n const { type, model: parentModel, dataSource, operationScope } = inherited;\n\n return { type, model: parentModel, dataSource, operationScope };\n};\n\nconst applyRepositoryMetadata = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(opts: {\n metadata: TRepositoryMetadata<Model, DataSource>;\n registration: IArtifactRegistrationOptions;\n target: Function;\n registry: MetadataRegistry;\n}): void => {\n const { metadata, registration, target, registry } = opts;\n injectable({\n type: ArtifactTypes.REPOSITORY,\n ...InjectableUtility.pickRegistrationOptions({ metadata: registration }),\n })(target);\n\n const resolved = resolveRepositoryMetadata({ metadata, target, registry });\n\n registry.setRepositoryMetadata({ target, metadata: { ...metadata, _resolved: resolved } });\n};\n\n/**\n * Class decorator that registers a repository and binds it to a model (or, for a remote repository, only a datasource). Called without arguments on a subclass it reuses the type, model and datasource of its nearest decorated parent; registration options are not inherited.\n *\n * @example\n * ```typescript\n * import { repository } from '@venizia/ignis';\n * import { DefaultCRUDRepository } from '@venizia/ignis-connectors/postgres';\n * import { AppDataSource } from './app.datasource';\n * import { Note, noteTable } from './note.model';\n *\n * export @repository({ model: Note, dataSource: AppDataSource })\n * class NoteRepository extends DefaultCRUDRepository<typeof noteTable> {}\n * ```\n */\nexport const repository = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(\n metadata?: TRepositoryMetadata<Model, DataSource>,\n): ClassDecorator => {\n return (target) => {\n const registry = MetadataRegistry.getInstance();\n\n if (!metadata) {\n applyRepositoryMetadata({\n metadata: inheritRepositoryMetadata({ target, registry }),\n registration: {},\n target,\n registry,\n });\n\n return;\n }\n\n applyRepositoryMetadata({ metadata, registration: metadata, target, registry });\n };\n};\n"]}
1
+ {"version":3,"file":"persistents.js","sourceRoot":"","sources":["../../../../src/base/metadata/persistents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAQtD,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACjG,OAAO,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAE/E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAExE,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAC7D,OAAO,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAExD;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAC,QAAwB,EAAE,EAAkB,EAAE;IAClE,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,UAAU,CAAC;YACT,IAAI,EAAE,aAAa,CAAC,KAAK;YACzB,GAAG,iBAAiB,CAAC,uBAAuB,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC;SAClE,CAAC,CAAC,MAAM,CAAC,CAAC;QAEX,MAAM,QAAQ,GAAG,oBAAoB,CAAC,sBAAsB,CAAC;YAC3D,KAAK,EAAE,MAAM,CAAC,IAAI;YAClB,QAAQ,EAAE,KAAK;SAChB,CAAC,CAAC;QAEH,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ent":["import { BindingNamespaces } from '@/common/bindings';\nimport type {\n IArtifactRegistrationOptions,\n IDataSourceMetadata,\n IModelMetadata,\n IResolvedRepositoryMetadata,\n TRepositoryMetadata,\n} from '@/helpers/inversion';\nimport { ArtifactTypes, BindingKeys, MetadataKeys, MetadataRegistry } from '@/helpers/inversion';\nimport { ClassResolver, ResolverUtility } from '@venizia/ignis-helpers/common';\nimport type { IInjectMetadata } from '@venizia/ignis-inversion';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { IDataSource } from '../datasources';\nimport { DataSourceOpenModes, isDataSourceClass } from '../datasources';\nimport type { AbstractEntity } from '../models';\nimport { RepositoryTypes } from '../repositories/common/constants';\nimport { injectable, InjectableUtility } from './injectable';\nimport { ModelMetadataUtility } from './model-metadata';\n\n/**\n * Registers a model class with its static schema and relations.\n *\n * @example\n * ```typescript\n * import { model } from '@venizia/ignis';\n * import { ModelFactory } from '@venizia/ignis-connectors/postgres';\n * import { pgTable, serial, text } from 'drizzle-orm/pg-core';\n *\n * const noteTable = pgTable('Note', { id: serial('id').primaryKey(), body: text('body') });\n *\n * export @model({ settings: { query: { limit: { default: 20 } } } })\n * class Note extends ModelFactory.defineEntity({ table: noteTable }) {}\n * ```\n */\nexport const model = (input: IModelMetadata = {}): ClassDecorator => {\n return (target) => {\n injectable({\n type: ArtifactTypes.MODEL,\n ...InjectableUtility.pickRegistrationOptions({ metadata: input }),\n })(target);\n\n const metadata = ModelMetadataUtility.normalizeModelMetadata({\n model: target.name,\n metadata: input,\n });\n\n const { settings } = metadata;\n\n if (settings && Reflect.has(settings, 'hiddenProperties')) {\n throw getError({\n message: `[model][${target.name}] hiddenProperties was replaced by properties.hidden`,\n });\n }\n\n const defaultLimit = settings?.query?.limit?.default;\n\n if (defaultLimit !== undefined && (!Number.isInteger(defaultLimit) || defaultLimit <= 0)) {\n throw getError({\n message: `[model][${target.name}] Invalid 'query.limit.default' | Expected a positive integer | Got: ${defaultLimit}`,\n });\n }\n\n // Validated at DECORATION time, like the default limit: a bad ceiling is a wiring mistake, and\n // catching it at boot beats catching it on the one request that happens to reach the limit.\n const maxLimit = settings?.query?.limit?.max;\n\n if (maxLimit !== undefined && (!Number.isInteger(maxLimit) || maxLimit <= 0)) {\n throw getError({\n message: `[model][${target.name}] Invalid 'query.limit.max' | Expected a positive integer | Got: ${maxLimit}`,\n });\n }\n\n // Auto-populate AUTHORIZATION_SUBJECT from authorize.principal if not already set\n const principal = settings?.authorize?.principal;\n\n if (principal && !Object.hasOwn(target, 'AUTHORIZATION_SUBJECT')) {\n (target as Record<string, unknown>).AUTHORIZATION_SUBJECT = principal;\n }\n\n MetadataRegistry.getInstance().registerModel({ target, metadata });\n };\n};\n\n/**\n * Registers a datasource with driver and auto-discovery settings.\n *\n * @example\n * ```typescript\n * import { datasource } from '@venizia/ignis';\n * import { BasePostgresDataSource } from '@venizia/ignis-connectors/postgres';\n * import { NodePostgresDriver } from '@venizia/ignis-connectors/postgres/node-postgres';\n * import { Pool } from 'pg';\n *\n * export @datasource({ driver: NodePostgresDriver })\n * class AppDataSource extends BasePostgresDataSource<{ connectionString: string }> {\n * constructor() { super({ name: AppDataSource.name, config: { connectionString: 'postgres://localhost/app' } }); }\n * override configure(): void { this.client = new Pool(this.settings); }\n * override getConnectionString(): string { return this.settings.connectionString; }\n * }\n * ```\n */\nexport const datasource = (metadata?: IDataSourceMetadata): ClassDecorator => {\n return (target) => {\n const openTimeout = metadata?.open?.timeoutMs;\n\n if (\n openTimeout !== undefined &&\n (typeof openTimeout !== 'number' || !Number.isInteger(openTimeout) || openTimeout < 0)\n ) {\n throw getError({\n message: `[datasource][@datasource][${target.name}] Invalid metadata | 'open.timeoutMs' must be a non-negative integer (ms; 0 waits for ever) | Got: ${String(openTimeout)}`,\n });\n }\n\n const openMode = metadata?.open?.on;\n\n // Untyped JS callers: a misspelt mode would silently mean \"start\", so it is refused where it is written.\n if (openMode !== undefined && !DataSourceOpenModes.isValid(openMode)) {\n throw getError({\n message: `[datasource][@datasource][${target.name}] Invalid metadata | Unknown 'open.on': ${String(openMode)} | Expected one of: ${[...DataSourceOpenModes.SCHEME_SET].join(', ')}`,\n });\n }\n\n injectable({\n type: ArtifactTypes.DATASOURCE,\n ...InjectableUtility.pickRegistrationOptions({ metadata: metadata ?? {} }),\n })(target);\n MetadataRegistry.getInstance().setDataSourceMetadata({ target, metadata });\n };\n};\n\n/** Mirrors the `TRepositoryMetadata` union for JavaScript callers: a known type, a dataSource always, a model exactly when the type is RepositoryTypes.MODEL. */\nconst validateRepositoryMetadata = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(opts: {\n metadata: TRepositoryMetadata<Model, DataSource>;\n target: Function;\n}): void => {\n const { metadata, target } = opts;\n const type = metadata.type ?? RepositoryTypes.MODEL;\n\n if (!RepositoryTypes.isValid(type)) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Unknown 'type': ${type} | Expected one of: ${[...RepositoryTypes.SCHEME_SET].join(', ')}`,\n });\n }\n\n if (type === RepositoryTypes.MODEL && !metadata.model) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Missing 'model'`,\n });\n }\n\n if (type === RepositoryTypes.REMOTE && metadata.model) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | A '${RepositoryTypes.REMOTE}' repository takes no 'model'`,\n });\n }\n\n if (!metadata.dataSource) {\n throw getError({\n message: `[validateRepositoryMetadata][@repository][${target.name}] Invalid metadata | Missing 'dataSource'`,\n });\n }\n};\n\n/** Asserts the constructor's first parameter is an AbstractDataSource compatible with what @repository declared. */\nconst validateFirstConstructorParameter = (opts: {\n target: Function;\n firstParamType: Function;\n resolvedDataSource: string | Function;\n}): void => {\n const { target, firstParamType, resolvedDataSource } = opts;\n\n // NOT `instanceof`: two copies of this package give two `AbstractDataSource` classes and the\n // check would be false across them, rejecting a perfectly valid repository at import time.\n const isDataSourceType = isDataSourceClass(firstParamType);\n\n if (!isDataSourceType) {\n throw getError({\n message: `[@repository][${target.name}] Invalid constructor | First parameter must extend AbstractDataSource | Received: '${firstParamType.name}'`,\n });\n }\n\n if (typeof resolvedDataSource !== 'function') {\n return;\n }\n\n const isCompatible =\n firstParamType === resolvedDataSource || resolvedDataSource.prototype instanceof firstParamType;\n\n if (!isCompatible) {\n throw getError({\n message: `[@repository][${target.name}] Invalid constructor | Type mismatch | Constructor expects '${firstParamType.name}' but @repository specifies '${resolvedDataSource.name}'`,\n });\n }\n};\n\n/**\n * Auto-injects dataSource at constructor param[0] unless explicit @inject exists. A class is injected\n * by the class itself, so the container reads the key its registration recorded: a pinned\n * `binding` and a minified class name both resolve. Only a string reference is a key.\n */\nconst registerDataSourceInjection = (opts: {\n target: Function;\n registry: MetadataRegistry;\n dataSourceRef: TRepositoryMetadata['dataSource'];\n resolvedDataSource: string | Function;\n}): void => {\n const { target, registry, dataSourceRef, resolvedDataSource } = opts;\n\n // Own metadata only: `getInjectMetadata` walks the prototype chain, so a repository extending another @repository class would see the BASE's injection at param[0] and silently resolve the base's dataSource.\n const ownInjects: IInjectMetadata[] | undefined = Reflect.getOwnMetadata(\n MetadataKeys.INJECT,\n target,\n );\n const injectAtIndex0 = ownInjects?.find((entry) => entry?.index === 0);\n\n if (injectAtIndex0) {\n // `@inject({ target })` carries no key; read the one recorded on the class. The function form\n // resolves through the same helper the container uses, so both paths read one class.\n const injectedTarget = injectAtIndex0.target\n ? ResolverUtility.resolveInjectTarget({ target: injectAtIndex0.target })\n : undefined;\n const injectKey =\n injectAtIndex0.key ??\n (injectedTarget ? registry.getBindingKey({ target: injectedTarget }) : undefined);\n\n // A class is judged by its brand: its key may sit under any namespace a `binding` pinned, and\n // a provisional key may still change at registration. Only a bare key is judged by its prefix.\n const isDataSourceTarget = injectedTarget\n ? isDataSourceClass(injectedTarget)\n : typeof injectKey === 'string' && injectKey.startsWith(`${BindingNamespaces.DATASOURCE}.`);\n\n if (!isDataSourceTarget) {\n throw getError({\n message: `[@repository][${target.name}] Invalid constructor | First parameter must be a DataSource | Found @inject with key: '${String(injectKey)}' | Expected a key starting with '${BindingNamespaces.DATASOURCE}.' or a DataSource class`,\n });\n }\n\n return;\n }\n\n // Checked only when this decorator writes the injection: an explicit @inject decides for itself.\n // An interface emits `Object` and a type-only class import emits `Function` under tsc (`Object`\n // under bun); neither names the class, so neither is judged.\n const firstParamType = Reflect.getMetadata('design:paramtypes', target)?.[0];\n\n if (firstParamType && firstParamType !== Object && firstParamType !== Function) {\n validateFirstConstructorParameter({ target, firstParamType, resolvedDataSource });\n }\n\n // The inherited list is the base repository's own, and setInjectMetadata may write straight into it.\n if (!ownInjects) {\n Reflect.defineMetadata(\n MetadataKeys.INJECT,\n [...(registry.getInjectMetadata({ target }) ?? [])],\n target,\n );\n }\n\n const derivedKey = BindingKeys.build({\n namespace: BindingNamespaces.DATASOURCE,\n key: typeof resolvedDataSource === 'string' ? resolvedDataSource : resolvedDataSource.name,\n });\n\n // The class first, decided when the repository is resolved: by then any registration - decorated,\n // `bindingList()`, or `dataSource(X, { binding })` - has recorded its key on the class. The derived\n // key is the fallback for a class nothing recorded, bound by hand under exactly that key.\n registry.setInjectMetadata({\n target,\n index: 0,\n metadata:\n typeof dataSourceRef === 'string'\n ? { key: derivedKey, index: 0, isOptional: false }\n : { target: dataSourceRef, key: derivedKey, index: 0, isOptional: false },\n });\n};\n\n/** Resolves repository metadata and registers bindings for schema auto-discovery. */\nconst resolveRepositoryMetadata = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(opts: {\n metadata: TRepositoryMetadata<Model, DataSource>;\n target: Function;\n registry: MetadataRegistry;\n}): IResolvedRepositoryMetadata<Model, DataSource> => {\n const { metadata, target, registry } = opts;\n\n validateRepositoryMetadata({ metadata, target });\n\n const resolvedDataSource = ClassResolver.resolveClass({ ref: metadata.dataSource });\n\n if (!resolvedDataSource) {\n throw getError({\n message: `[@repository][${target.name}] The dataSource resolver returned nothing at decoration time | An import cycle leaves the datasource class undefined here; import it without the cycle, or name it as a string`,\n });\n }\n\n // No model, so no binding: the datasource owns no schema through this repository.\n if (metadata.type === RepositoryTypes.REMOTE) {\n registerDataSourceInjection({\n target,\n registry,\n dataSourceRef: metadata.dataSource,\n resolvedDataSource,\n });\n\n return {\n type: RepositoryTypes.REMOTE,\n dataSource: resolvedDataSource,\n operationScope: metadata.operationScope,\n };\n }\n\n const resolvedModel = ResolverUtility.resolveValue({ value: metadata.model });\n\n registry.registerRepositoryBinding({\n repository: target,\n model: resolvedModel,\n dataSource: resolvedDataSource,\n });\n\n registerDataSourceInjection({\n target,\n registry,\n dataSourceRef: metadata.dataSource,\n resolvedDataSource,\n });\n\n return {\n type: RepositoryTypes.MODEL,\n model: resolvedModel,\n dataSource: resolvedDataSource,\n operationScope: metadata.operationScope,\n };\n};\n\n/** A bare `@repository()` on a subclass reuses the type, model and datasource its nearest decorated parent declared; the registration options (`binding`, `when`, ...) are never inherited, so the subclass registers under its own name. */\nconst inheritRepositoryMetadata = (opts: {\n target: Function;\n registry: MetadataRegistry;\n}): TRepositoryMetadata => {\n // Own metadata does not exist yet at decoration time, so this read walks the prototype chain.\n const inherited = opts.registry.getRepositoryMetadata({ target: opts.target });\n\n if (!inherited) {\n throw getError({\n message: `[@repository][${opts.target.name}] No metadata given and no decorated repository above it in the prototype chain | pass { model, dataSource } or decorate the parent`,\n });\n }\n\n if (inherited.type === RepositoryTypes.REMOTE) {\n const { type, dataSource, operationScope } = inherited;\n\n return { type, dataSource, operationScope };\n }\n\n const { type, model: parentModel, dataSource, operationScope } = inherited;\n\n return { type, model: parentModel, dataSource, operationScope };\n};\n\nconst applyRepositoryMetadata = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(opts: {\n metadata: TRepositoryMetadata<Model, DataSource>;\n registration: IArtifactRegistrationOptions;\n target: Function;\n registry: MetadataRegistry;\n}): void => {\n const { metadata, registration, target, registry } = opts;\n injectable({\n type: ArtifactTypes.REPOSITORY,\n ...InjectableUtility.pickRegistrationOptions({ metadata: registration }),\n })(target);\n\n const resolved = resolveRepositoryMetadata({ metadata, target, registry });\n\n registry.setRepositoryMetadata({ target, metadata: { ...metadata, _resolved: resolved } });\n};\n\n/**\n * Class decorator that registers a repository and binds it to a model (or, for a remote repository, only a datasource). Called without arguments on a subclass it reuses the type, model and datasource of its nearest decorated parent; registration options are not inherited.\n *\n * @example\n * ```typescript\n * import { repository } from '@venizia/ignis';\n * import { DefaultCRUDRepository } from '@venizia/ignis-connectors/postgres';\n * import { AppDataSource } from './app.datasource';\n * import { Note, noteTable } from './note.model';\n *\n * export @repository({ model: Note, dataSource: AppDataSource })\n * class NoteRepository extends DefaultCRUDRepository<typeof noteTable> {}\n * ```\n */\nexport const repository = <\n Model extends AbstractEntity = AbstractEntity,\n DataSource extends IDataSource = IDataSource,\n>(\n metadata?: TRepositoryMetadata<Model, DataSource>,\n): ClassDecorator => {\n return (target) => {\n const registry = MetadataRegistry.getInstance();\n\n if (!metadata) {\n applyRepositoryMetadata({\n metadata: inheritRepositoryMetadata({ target, registry }),\n registration: {},\n target,\n registry,\n });\n\n return;\n }\n\n applyRepositoryMetadata({ metadata, registration: metadata, target, registry });\n };\n};\n"]}
@@ -11,8 +11,6 @@ export declare abstract class AbstractEntity<Schema = unknown> extends BaseHelpe
11
11
  }): T;
12
12
  /** Path-param id shape for this entity - default 'string' (every document-family id, e.g. Typesense's). */
13
13
  getIdType(): TIdSchemaType;
14
- /** Keys the server fills on every write, which a generated create or update body leaves out. None here. */
15
- getServerStampedKeys(): string[];
16
14
  toObject(): this;
17
15
  toJSON(): this;
18
16
  }
@@ -9,10 +9,6 @@ export class AbstractEntity extends BaseHelper {
9
9
  getIdType() {
10
10
  return 'string';
11
11
  }
12
- /** Keys the server fills on every write, which a generated create or update body leaves out. None here. */
13
- getServerStampedKeys() {
14
- return [];
15
- }
16
12
  toObject() {
17
13
  return { ...this };
18
14
  }
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../src/base/models/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAGzD,4EAA4E;AAC5E,MAAM,OAAgB,cAAiC,SAAQ,UAAU;IAGvE,YAAY,IAAsB;QAChC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;IACxB,CAAC;IAID,2GAA2G;IAC3G,SAAS;QACP,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,2GAA2G;IAC3G,oBAAoB;QAClB,OAAO,EAAE,CAAC;IACZ,CAAC;IAED,QAAQ;QACN,OAAO,EAAE,GAAG,IAAI,EAAE,CAAC;IACrB,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["import { BaseHelper } from '@venizia/ignis-helpers/core';\nimport type { TIdSchemaType, TSchemaType } from './common';\n\n/** Engine-neutral entity root: named, scoped-logged, zod-schema-capable. */\nexport abstract class AbstractEntity<Schema = unknown> extends BaseHelper {\n name: string;\n\n constructor(opts: { name: string }) {\n super({ scope: opts.name });\n this.name = opts.name;\n }\n\n abstract getSchema<T = Schema>(opts: { type: TSchemaType }): T;\n\n /** Path-param id shape for this entity - default 'string' (every document-family id, e.g. Typesense's). */\n getIdType(): TIdSchemaType {\n return 'string';\n }\n\n /** Keys the server fills on every write, which a generated create or update body leaves out. None here. */\n getServerStampedKeys(): string[] {\n return [];\n }\n\n toObject() {\n return { ...this };\n }\n\n toJSON() {\n return this.toObject();\n }\n}\n"]}
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../src/base/models/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAGzD,4EAA4E;AAC5E,MAAM,OAAgB,cAAiC,SAAQ,UAAU;IAGvE,YAAY,IAAsB;QAChC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QAC5B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;IACxB,CAAC;IAID,2GAA2G;IAC3G,SAAS;QACP,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,QAAQ;QACN,OAAO,EAAE,GAAG,IAAI,EAAE,CAAC;IACrB,CAAC;IAED,MAAM;QACJ,OAAO,IAAI,CAAC,QAAQ,EAAE,CAAC;IACzB,CAAC;CACF","sourcesContent":["import { BaseHelper } from '@venizia/ignis-helpers/core';\nimport type { TIdSchemaType, TSchemaType } from './common';\n\n/** Engine-neutral entity root: named, scoped-logged, zod-schema-capable. */\nexport abstract class AbstractEntity<Schema = unknown> extends BaseHelper {\n name: string;\n\n constructor(opts: { name: string }) {\n super({ scope: opts.name });\n this.name = opts.name;\n }\n\n abstract getSchema<T = Schema>(opts: { type: TSchemaType }): T;\n\n /** Path-param id shape for this entity - default 'string' (every document-family id, e.g. Typesense's). */\n getIdType(): TIdSchemaType {\n return 'string';\n }\n\n toObject() {\n return { ...this };\n }\n\n toJSON() {\n return this.toObject();\n }\n}\n"]}
@@ -10,6 +10,15 @@ export declare class SchemaTypes {
10
10
  }
11
11
  /** Valid `SchemaTypes` values. */
12
12
  export type TSchemaType = TConstValue<typeof SchemaTypes>;
13
+ /** The keys a write stamps, which a generated create or update body leaves out by default (`@model` `settings.properties.stamped`). */
14
+ export declare class AuditFields {
15
+ static readonly CREATED_BY = "createdBy";
16
+ static readonly MODIFIED_BY = "modifiedBy";
17
+ static readonly CREATED_AT = "createdAt";
18
+ static readonly MODIFIED_AT = "modifiedAt";
19
+ static readonly DELETED_AT = "deletedAt";
20
+ static readonly SCHEME_SET: Set<string>;
21
+ }
13
22
  /** What `@model` declares. Only ENTITY (a table-backed model) exists; `type` may be left out. */
14
23
  export declare class ModelTypes {
15
24
  static readonly ENTITY = "entity";
@@ -9,6 +9,21 @@ export class SchemaTypes {
9
9
  return this.SCHEME_SET.has(input);
10
10
  }
11
11
  }
12
+ /** The keys a write stamps, which a generated create or update body leaves out by default (`@model` `settings.properties.stamped`). */
13
+ export class AuditFields {
14
+ static { this.CREATED_BY = 'createdBy'; }
15
+ static { this.MODIFIED_BY = 'modifiedBy'; }
16
+ static { this.CREATED_AT = 'createdAt'; }
17
+ static { this.MODIFIED_AT = 'modifiedAt'; }
18
+ static { this.DELETED_AT = 'deletedAt'; }
19
+ static { this.SCHEME_SET = new Set([
20
+ this.CREATED_BY,
21
+ this.MODIFIED_BY,
22
+ this.CREATED_AT,
23
+ this.MODIFIED_AT,
24
+ this.DELETED_AT,
25
+ ]); }
26
+ }
12
27
  /** What `@model` declares. Only ENTITY (a table-backed model) exists; `type` may be left out. */
13
28
  export class ModelTypes {
14
29
  static { this.ENTITY = 'entity'; }
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/base/models/common/constants.ts"],"names":[],"mappings":"AAEA,6GAA6G;AAC7G,MAAM,OAAO,WAAW;aACN,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,YAAO,GAAG,SAAS,CAAC;aAEpB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAE5F,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,iGAAiG;AACjG,MAAM,OAAO,UAAU;aACL,WAAM,GAAG,QAAQ,CAAC;aAClB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAEpD,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,2FAA2F;AAC3F,MAAM,OAAO,aAAa;aACR,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAElB,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAEzE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\n\n/** The schema variants an entity can produce (`getSchema({ type })`): select, create, update and execute. */\nexport class SchemaTypes {\n static readonly SELECT = 'select';\n static readonly UPDATE = 'update';\n static readonly CREATE = 'create';\n static readonly EXECUTE = 'execute';\n\n static readonly SCHEME_SET = new Set([this.SELECT, this.UPDATE, this.CREATE, this.EXECUTE]);\n\n static isValid(input: string): input is TSchemaType {\n return this.SCHEME_SET.has(input);\n }\n}\n\n/** Valid `SchemaTypes` values. */\nexport type TSchemaType = TConstValue<typeof SchemaTypes>;\n\n/** What `@model` declares. Only ENTITY (a table-backed model) exists; `type` may be left out. */\nexport class ModelTypes {\n static readonly ENTITY = 'entity';\n static readonly SCHEME_SET = new Set([this.ENTITY]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid model type values. */\nexport type TModelType = TConstValue<typeof ModelTypes>;\n\n/** The path-param id shape an entity family resolves to (`AbstractEntity.getIdType()`). */\nexport class IdSchemaTypes {\n static readonly NUMBER = 'number';\n static readonly STRING = 'string';\n\n static readonly SCHEME_SET = new Set<string>([this.NUMBER, this.STRING]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid id schema type values. */\nexport type TIdSchemaType = TConstValue<typeof IdSchemaTypes>;\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../../../src/base/models/common/constants.ts"],"names":[],"mappings":"AAEA,6GAA6G;AAC7G,MAAM,OAAO,WAAW;aACN,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAClB,YAAO,GAAG,SAAS,CAAC;aAEpB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;IAE5F,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,uIAAuI;AACvI,MAAM,OAAO,WAAW;aACN,eAAU,GAAG,WAAW,CAAC;aACzB,gBAAW,GAAG,YAAY,CAAC;aAC3B,eAAU,GAAG,WAAW,CAAC;aACzB,gBAAW,GAAG,YAAY,CAAC;aAC3B,eAAU,GAAG,WAAW,CAAC;aAEzB,eAAU,GAAG,IAAI,GAAG,CAAS;QAC3C,IAAI,CAAC,UAAU;QACf,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,UAAU;QACf,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,UAAU;KAChB,CAAC,CAAC;;AAGL,iGAAiG;AACjG,MAAM,OAAO,UAAU;aACL,WAAM,GAAG,QAAQ,CAAC;aAClB,eAAU,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAEpD,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC;;AAMH,2FAA2F;AAC3F,MAAM,OAAO,aAAa;aACR,WAAM,GAAG,QAAQ,CAAC;aAClB,WAAM,GAAG,QAAQ,CAAC;aAElB,eAAU,GAAG,IAAI,GAAG,CAAS,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC;IAEzE,MAAM,CAAC,OAAO,CAAC,KAAa;QAC1B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACpC,CAAC","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\n\n/** The schema variants an entity can produce (`getSchema({ type })`): select, create, update and execute. */\nexport class SchemaTypes {\n static readonly SELECT = 'select';\n static readonly UPDATE = 'update';\n static readonly CREATE = 'create';\n static readonly EXECUTE = 'execute';\n\n static readonly SCHEME_SET = new Set([this.SELECT, this.UPDATE, this.CREATE, this.EXECUTE]);\n\n static isValid(input: string): input is TSchemaType {\n return this.SCHEME_SET.has(input);\n }\n}\n\n/** Valid `SchemaTypes` values. */\nexport type TSchemaType = TConstValue<typeof SchemaTypes>;\n\n/** The keys a write stamps, which a generated create or update body leaves out by default (`@model` `settings.properties.stamped`). */\nexport class AuditFields {\n static readonly CREATED_BY = 'createdBy';\n static readonly MODIFIED_BY = 'modifiedBy';\n static readonly CREATED_AT = 'createdAt';\n static readonly MODIFIED_AT = 'modifiedAt';\n static readonly DELETED_AT = 'deletedAt';\n\n static readonly SCHEME_SET = new Set<string>([\n this.CREATED_BY,\n this.MODIFIED_BY,\n this.CREATED_AT,\n this.MODIFIED_AT,\n this.DELETED_AT,\n ]);\n}\n\n/** What `@model` declares. Only ENTITY (a table-backed model) exists; `type` may be left out. */\nexport class ModelTypes {\n static readonly ENTITY = 'entity';\n static readonly SCHEME_SET = new Set([this.ENTITY]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid model type values. */\nexport type TModelType = TConstValue<typeof ModelTypes>;\n\n/** The path-param id shape an entity family resolves to (`AbstractEntity.getIdType()`). */\nexport class IdSchemaTypes {\n static readonly NUMBER = 'number';\n static readonly STRING = 'string';\n\n static readonly SCHEME_SET = new Set<string>([this.NUMBER, this.STRING]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid id schema type values. */\nexport type TIdSchemaType = TConstValue<typeof IdSchemaTypes>;\n"]}
@@ -71,7 +71,7 @@ export class AbstractRepository extends BaseHelper {
71
71
  return this._modelSettings;
72
72
  }
73
73
  get hiddenFields() {
74
- return this.modelSettings?.hiddenProperties ?? [];
74
+ return this.modelSettings?.properties?.hidden ?? [];
75
75
  }
76
76
  /**
77
77
  * Refuses (400, `Column NOT FOUND`) a filter that came from a request and names a field the model hides, in its
@@ -1 +1 @@
1
- {"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/base/repositories/core/abstract.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,sBAAsB,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAYpG,sGAAsG;AACtG,sFAAsF;AACtF,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAWpE;;;;GAIG;AACH,MAAM,OAAgB,kBAKpB,SAAQ,UAAU;IAiBlB,YACE,UAA+B,EAC/B,IAIC;QAED,MAAM,SAAS,GACb,IAAI,EAAE,KAAK;YACX,CAAC,IAAI,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC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K,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QACjF,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAI,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import type { AbstractDataSource } from '@/base/datasources';\nimport type { AbstractEntity, IdType } from '@/base/models';\nimport type { IModelMetadata } from '@/helpers/inversion';\nimport { MetadataRegistry } from '@/helpers/inversion';\nimport type { TClass, TNullable } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { ResolverUtility } from '@venizia/ignis-helpers/common';\nimport { RetryBackoffStrategies, RetryHelper, RetryJitterModes } from '@venizia/ignis-helpers/core';\nimport type {\n IExtraOptions,\n IPersistableRepository,\n IWithReadRetry,\n TCount,\n TDataWithRange,\n TFindOneOptions,\n TFindOptions,\n TFindRangeOptions,\n TRepositoryOperationScope,\n} from '../common';\n// The file, not the `../common` barrel: the barrel re-exports the OpenAPI schemas, and this module is\n// on the `./repository` entry, which must load without `@hono/zod-openapi` installed.\nimport {\n DEFAULT_MAX_LIMIT,\n RepositoryErrorCodes,\n RepositoryOperationScopes,\n} from '../common/constants';\nimport { RequestFilterGuard } from '../common/request-filter-guard';\nimport type { IRequestFilterJudge, IRequestFilterShape } from '../common/request-filter-guard';\nimport type {\n TByIdFilter,\n TFields,\n TFilter,\n TInclusion,\n TRow,\n TWhere,\n} from '@venizia/ignis-filter';\n\n/**\n * Engine-neutral repository plumbing - lazy dataSource/entity resolution, class-keyed `@model`\n * settings, operation scope. `TOptions` defaults to `IExtraOptions` so connectors can narrow it\n * while staying assignable to this base.\n */\nexport abstract class AbstractRepository<\n TDataObject extends object,\n TPersistObject extends object = TDataObject,\n TOptions extends IExtraOptions = IExtraOptions,\n>\n extends BaseHelper\n implements IPersistableRepository<TDataObject, TPersistObject, TOptions>\n{\n protected _operationScope: TRepositoryOperationScope;\n\n /** Lazy-resolved on first access if not provided in constructor. */\n protected _dataSource?: AbstractDataSource;\n\n /** Lazy-resolved from @repository metadata on first access. */\n protected _entity?: AbstractEntity;\n\n /**\n * Memoized @model settings for `this.entity`'s class. `null` means not yet resolved - `undefined`\n * is itself a valid resolved value: the model declares no settings.\n */\n private _modelSettings: IModelMetadata['settings'] | null = null;\n\n constructor(\n dataSource?: AbstractDataSource,\n opts?: {\n scope?: string;\n entityClass?: TClass<AbstractEntity>;\n operationScope?: TRepositoryOperationScope;\n },\n ) {\n const scopeName =\n opts?.scope ??\n (opts?.entityClass?.name ? [opts.entityClass.name, 'Repository'].join('') : new.target.name);\n\n super({ scope: scopeName });\n\n this._operationScope = opts?.operationScope ?? RepositoryOperationScopes.READ_ONLY;\n\n if (dataSource) {\n this._dataSource = dataSource;\n }\n\n if (opts?.entityClass) {\n this._entity = new opts.entityClass();\n }\n }\n\n get dataSource(): AbstractDataSource {\n if (!this._dataSource) {\n throw getError({\n message: `[${this.constructor.name}] DataSource not available. Use @repository({ model: YourModel, dataSource: YourDataSource }) or pass dataSource in constructor.`,\n });\n }\n\n return this._dataSource;\n }\n\n set dataSource(value: AbstractDataSource) {\n this._dataSource = value;\n }\n\n /** Auto-resolves from @repository metadata if not explicitly set. */\n get entity(): AbstractEntity {\n this._entity ??= this.resolveEntity();\n\n return this._entity;\n }\n\n set entity(value: AbstractEntity) {\n this._entity = value;\n }\n\n get operationScope(): TRepositoryOperationScope {\n return this._operationScope;\n }\n\n setDataSource(opts: { dataSource: AbstractDataSource }): void {\n this._dataSource = opts.dataSource;\n }\n\n getEntity(): AbstractEntity {\n return this.entity;\n }\n\n /**\n * Resolved `@model` settings for `this.entity`'s class, keyed by Reflect target - not by\n * `entity.name`, which can diverge from the `@model` registry key.\n */\n protected get modelSettings(): IModelMetadata['settings'] {\n if (this._modelSettings !== null) {\n return this._modelSettings;\n }\n\n this._modelSettings = MetadataRegistry.getInstance().getModelMetadata({\n target: this.entity.constructor,\n })?.settings;\n\n return this._modelSettings;\n }\n\n protected get hiddenFields(): string[] {\n return this.modelSettings?.hiddenProperties ?? [];\n }\n\n /**\n * Refuses (400, `Column NOT FOUND`) a filter that came from a request and names a field the model hides, in its\n * `where`, its `order` or the `scope` of an `include` (judged by the hidden fields of the model it reads). The generated\n * controllers call it on what a client sends; the repository's own verbs do not, so server code can still filter and\n * sort on a hidden field.\n */\n assertRequestFilter(opts: { filter?: IRequestFilterShape }): void {\n RequestFilterGuard.assertFilter({\n filter: opts.filter,\n judge: this.createRequestFilterJudge(),\n tableName: this.entity?.name ?? this.constructor.name,\n });\n }\n\n /**\n * How this repository judges the keys of a request filter. The default reads a key as a dotted field name and refuses it with\n * a 400 `Column NOT FOUND`; a relational or a search repository overrides it to read keys as its own query does and to\n * refuse with its own query's error for a column that does not exist.\n */\n protected createRequestFilterJudge(): IRequestFilterJudge {\n const hidden = new Set(this.hiddenFields);\n\n return {\n isHidden: ({ key }) => RequestFilterGuard.isHiddenByName({ key, hidden }),\n refuse: ({ key }) => RequestFilterGuard.columnNotFound({ scope: this.constructor.name, key }),\n };\n }\n\n /** Default where from @model settings.query.filter.where, AND-merged into every query unless skipped. */\n protected get defaultWhere(): TWhere | undefined {\n return this.modelSettings?.query?.filter?.where;\n }\n\n protected get defaultLimit(): number | undefined {\n return this.modelSettings?.query?.limit?.default;\n }\n\n /** Largest `limit` a caller may ask for, when the model declares one; undefined leaves the tier's own default in force. */\n protected get maxLimit(): number | undefined {\n return this.modelSettings?.query?.limit?.max;\n }\n\n /**\n * Both bounds, in one place, for every tier.\n *\n * The upper bound is the point: `@model({ settings: { query: { limit: { max } } } })` is public and validated at\n * decoration time, but the relational tier read it nowhere, so `limit.max: 2` still issued\n * `LIMIT 50000000`.\n *\n * The lower bound matters just as much and is easy to miss: a NEGATIVE limit is not a smaller\n * page. Drizzle renders the LIMIT clause only when the value is `>= 0`, so a negative one removes\n * the clause and returns the whole table. The wire schema now rejects it too, but a server-side\n * caller reaches this method without passing through the schema at all.\n */\n protected assertLimitWithinCeiling(opts: { limit?: number; scope?: string }): void {\n const { limit, scope = 'find' } = opts;\n\n if (limit === undefined) {\n return;\n }\n\n // The shape check first, because it needs no metadata at all.\n if (!Number.isInteger(limit) || limit < 0) {\n throw getError({\n message: `[${this.constructor.name}][${scope}] Invalid 'limit' | Expected a non-negative integer | Got: ${limit}`,\n });\n }\n\n // `limit.max` reaches `modelSettings`, which resolves the entity - and THAT throws for a\n // repository with no `@repository` model binding. Such a repository is a misconfiguration this\n // method has no business reporting, and the caller path that used to reach `getDefaultLimit()`\n // never touched it either, because `??` short-circuits when a limit is given. So the ceiling is\n // consulted only when the binding that makes it resolvable is actually present.\n const hasModelBinding = Boolean(\n MetadataRegistry.getInstance().getRepositoryBinding({ target: this.constructor })?.model,\n );\n const ceiling = (hasModelBinding ? this.maxLimit : undefined) ?? DEFAULT_MAX_LIMIT;\n\n if (limit > ceiling) {\n throw getError({\n message: `[${this.constructor.name}][${scope}] Requested page exceeds this model's limit | requested: ${limit} | maximum: ${ceiling} | raise it with @model settings.query.limit.max if larger pages are genuinely needed`,\n });\n }\n }\n\n /**\n * The whole filter, relations included. Checking only the top-level `limit` left the identical\n * defect reachable one level down: a relation scope's negative limit drops Drizzle's LIMIT clause\n * for that relation and loads the entire related table.\n *\n * A relation's limit gets the SHAPE check only, not a ceiling. The ceiling belongs to the\n * relation's own model, which this repository cannot resolve - claiming otherwise would enforce\n * the parent's `limit.max` on a different entity.\n */\n protected assertFilterLimits(opts: { filter?: TFilter; scope?: string }): void {\n const { filter, scope = 'find' } = opts;\n\n if (!filter) {\n return;\n }\n\n this.assertLimitWithinCeiling({ limit: filter.limit, scope });\n\n const walk = (inclusions: TInclusion[] | undefined, path: string): void => {\n const inclusionsList = inclusions ?? [];\n\n for (const inclusion of inclusionsList) {\n const relationScope = inclusion.scope;\n\n if (!relationScope) {\n continue;\n }\n\n const relationPath = `${path}.${inclusion.relation}`;\n const relationLimit = relationScope.limit;\n\n if (\n relationLimit !== undefined &&\n (!Number.isInteger(relationLimit) || relationLimit < 0)\n ) {\n throw getError({\n message: `[${this.constructor.name}][${scope}] Invalid 'limit' on relation scope | relation: ${relationPath} | Expected a non-negative integer | Got: ${relationLimit}`,\n });\n }\n\n walk(relationScope.include, relationPath);\n }\n };\n\n walk(filter.include, scope);\n }\n\n /** Resolves the entity instance from @repository metadata on first access. */\n protected resolveEntity(): AbstractEntity {\n const registry = MetadataRegistry.getInstance();\n const binding = registry.getRepositoryBinding({ target: this.constructor });\n\n if (!binding?.model) {\n throw getError({\n message: `[${this.constructor.name}] Cannot resolve entity. Either pass entityClass in constructor or use @repository decorator with model option.`,\n });\n }\n\n // ResolverUtility.resolveValue() erases to the resolved value's structural type, not this class-or-resolver\n // union's member - the `@repository` decorator guarantees a class constructor here.\n const ModelClass = ResolverUtility.resolveValue({\n value: binding.model,\n }) as TClass<AbstractEntity>;\n\n return new ModelClass();\n }\n\n /** Rejects a verb the current operation scope does not permit. */\n protected denyOperation(opts: { methodName: string }): never {\n throw getError({\n messageCode: RepositoryErrorCodes.OPERATION_NOT_ALLOWED,\n message: `[${opts.methodName}] Repository operation is NOT ALLOWED | scope: ${this.operationScope}`,\n });\n }\n\n /**\n * Shared retry orchestration for read verbs. Inside a transaction retry is skipped - the pool\n * routes transactions to the primary, so there is no replica lag to wait out.\n */\n protected executeReadWithRetry<TResult>(opts: {\n operation: string;\n options: IExtraOptions & IWithReadRetry<TResult>;\n defaultUntil: (result: TResult) => boolean;\n execution: () => Promise<TResult>;\n }): Promise<TResult> {\n const { operation, options, defaultUntil, execution } = opts;\n\n if (!options.retry) {\n return execution();\n }\n\n if (options.transaction) {\n this.logger.for(operation).debug('Read retry skipped inside transaction');\n\n return execution();\n }\n\n const { maxAttempts, maxTotalMs, signal, backoff, until } = options.retry;\n\n return RetryHelper.executeWithRetryUntil<TResult>({\n operation: [this.constructor.name, operation].join('.'),\n execution,\n until: until ?? defaultUntil,\n maxAttempts,\n maxTotalMs,\n signal,\n backoff: backoff ?? {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: 50,\n maxDelayMs: 500,\n jitter: RetryJitterModes.EQUAL,\n },\n logger: this.logger,\n });\n }\n\n /**\n * A copy of `options` without `retry`, so re-entering a read verb takes its non-retry path - this\n * is what keeps the retry recursion single-depth. Copy-then-delete rather than a rest-destructure\n * (lint rejects the unused rest sibling) or `lodash/omit` (its `Omit<>` return type is not\n * assignable back to `TOptions`).\n */\n private omitReadRetry<TReadOptions extends { retry?: unknown }>(\n options: TReadOptions,\n ): TReadOptions {\n const rest = { ...options };\n delete rest.retry;\n\n return rest;\n }\n\n /** `find`, re-executed until the retry predicate holds - connectors dispatch here from `find` when `options.retry` is set. */\n protected findUntil<R = TDataObject>(opts: {\n filter: TFilter<TDataObject>;\n options: TFindOptions<TOptions, R>;\n }): Promise<Array<R>> {\n const options = this.omitReadRetry(opts.options);\n\n return this.executeReadWithRetry<Array<R>>({\n operation: 'find',\n options: opts.options,\n defaultUntil: (result) => result.length > 0,\n // `R` is named here, so the row is `R`; TypeScript cannot resolve `TRow` for an unresolved `R`.\n execution: () => this.find<R>({ filter: opts.filter, options }) as Promise<Array<R>>,\n });\n }\n\n /** `find` with the range envelope, re-executed until the retry predicate holds - split from `findUntil` so each result shape is checked against its own `find` overload. */\n protected findRangeUntil<R = TDataObject>(opts: {\n filter: TFilter<TDataObject>;\n options: TFindRangeOptions<TOptions, R>;\n }): Promise<TDataWithRange<R>> {\n const options = this.omitReadRetry(opts.options);\n\n return this.executeReadWithRetry<TDataWithRange<R>>({\n operation: 'find',\n options: opts.options,\n defaultUntil: (result) => result.data.length > 0,\n execution: () =>\n this.find<R>({ filter: opts.filter, options }) as unknown as Promise<TDataWithRange<R>>,\n });\n }\n\n /** `findOne`, re-executed until the retry predicate holds - also serves `findById` via its findOne delegation. */\n protected findOneUntil<R = TDataObject>(opts: {\n filter: TFilter<TDataObject>;\n options: TFindOneOptions<TOptions, R>;\n }): Promise<TNullable<R>> {\n const options = this.omitReadRetry(opts.options);\n\n return this.executeReadWithRetry<TNullable<R>>({\n operation: 'findOne',\n options: opts.options,\n defaultUntil: (result) => result !== null && result !== undefined,\n execution: () => this.findOne<R>({ filter: opts.filter, options }) as Promise<TNullable<R>>,\n });\n }\n\n abstract count(opts: { where: TWhere<TDataObject>; options?: TOptions }): Promise<TCount>;\n\n abstract existsWith(opts: { where: TWhere<TDataObject>; options?: TOptions }): Promise<boolean>;\n\n abstract find<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n filter: TFilter<TDataObject, F>;\n options: TFindRangeOptions<TOptions, TRow<TDataObject, R, F>>;\n }): Promise<TDataWithRange<TRow<TDataObject, R, F>>>;\n\n abstract find<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n filter: TFilter<TDataObject, F>;\n options?: TFindOptions<TOptions, TRow<TDataObject, R, F>>;\n }): Promise<Array<TRow<TDataObject, R, F>>>;\n\n abstract findOne<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n filter: TFilter<TDataObject, F>;\n options?: TFindOneOptions<TOptions, TRow<TDataObject, R, F>>;\n }): Promise<TNullable<TRow<TDataObject, R, F>>>;\n\n abstract findById<\n R = unknown,\n const F extends TFields<TDataObject> = TFields<TDataObject>,\n >(opts: {\n id: IdType;\n filter?: TByIdFilter<TDataObject, F>;\n options?: TFindOneOptions<TOptions, TRow<TDataObject, R, F>>;\n }): Promise<TNullable<TRow<TDataObject, R, F>>>;\n\n abstract create(opts: {\n data: TPersistObject;\n options: TOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract create<R = TDataObject>(opts: {\n data: TPersistObject;\n options?: TOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract createAll(opts: {\n data: Array<TPersistObject>;\n options: TOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract createAll<R = TDataObject>(opts: {\n data: Array<TPersistObject>;\n options?: TOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: Array<R> }>;\n\n abstract updateById(opts: {\n id: IdType;\n data: Partial<TPersistObject>;\n options: TOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract updateById<R = TDataObject>(opts: {\n id: IdType;\n data: Partial<TPersistObject>;\n options?: TOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract updateAll(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options: TOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract updateAll<R = TDataObject>(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n\n /** Alias for updateAll. */\n updateBy(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options: TOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n updateBy<R = TDataObject>(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n updateBy<R = TDataObject>(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: boolean; force?: boolean };\n }): Promise<TCount & { data: TNullable<Array<R>> }> {\n const { data, where, options } = opts;\n\n if (options?.shouldReturn === false) {\n return this.updateAll({ data, where, options: { ...options, shouldReturn: false } });\n }\n\n return this.updateAll<R>({ data, where, options });\n }\n\n abstract deleteById(opts: {\n id: IdType;\n options: TOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract deleteById<R = TDataObject>(opts: {\n id: IdType;\n options?: TOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract deleteAll(opts: {\n where?: TWhere<TDataObject>;\n options: TOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract deleteAll<R = TDataObject>(opts: {\n where?: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n\n /** Alias for deleteAll. */\n deleteBy(opts: {\n where: TWhere<TDataObject>;\n options: TOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n deleteBy<R = TDataObject>(opts: {\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n deleteBy<R = TDataObject>(opts: {\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: boolean; force?: boolean };\n }): Promise<TCount & { data: TNullable<Array<R>> }> {\n const { where, options } = opts;\n\n if (options?.shouldReturn === false) {\n return this.deleteAll({ where, options: { ...options, shouldReturn: false } });\n }\n\n return this.deleteAll<R>({ where, options });\n }\n}\n"]}
1
+ {"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/base/repositories/core/abstract.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,sBAAsB,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAYpG,sGAAsG;AACtG,sFAAsF;AACtF,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,yBAAyB,GAC1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAWpE;;;;GAIG;AACH,MAAM,OAAgB,kBAKpB,SAAQ,UAAU;IAiBlB,YACE,UAA+B,EAC/B,IAIC;QAED,MAAM,SAAS,GACb,IAAI,EAAE,KAAK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kB,IAGzB;QACC,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;QAEhC,IAAI,OAAO,EAAE,YAAY,KAAK,KAAK,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,GAAG,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QACjF,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAI,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import type { AbstractDataSource } from '@/base/datasources';\nimport type { AbstractEntity, IdType } from '@/base/models';\nimport type { IModelMetadata } from '@/helpers/inversion';\nimport { MetadataRegistry } from '@/helpers/inversion';\nimport type { TClass, TNullable } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { ResolverUtility } from '@venizia/ignis-helpers/common';\nimport { RetryBackoffStrategies, RetryHelper, RetryJitterModes } from '@venizia/ignis-helpers/core';\nimport type {\n IExtraOptions,\n IPersistableRepository,\n IWithReadRetry,\n TCount,\n TDataWithRange,\n TFindOneOptions,\n TFindOptions,\n TFindRangeOptions,\n TRepositoryOperationScope,\n} from '../common';\n// The file, not the `../common` barrel: the barrel re-exports the OpenAPI schemas, and this module is\n// on the `./repository` entry, which must load without `@hono/zod-openapi` installed.\nimport {\n DEFAULT_MAX_LIMIT,\n RepositoryErrorCodes,\n RepositoryOperationScopes,\n} from '../common/constants';\nimport { RequestFilterGuard } from '../common/request-filter-guard';\nimport type { IRequestFilterJudge, IRequestFilterShape } from '../common/request-filter-guard';\nimport type {\n TByIdFilter,\n TFields,\n TFilter,\n TInclusion,\n TRow,\n TWhere,\n} from '@venizia/ignis-filter';\n\n/**\n * Engine-neutral repository plumbing - lazy dataSource/entity resolution, class-keyed `@model`\n * settings, operation scope. `TOptions` defaults to `IExtraOptions` so connectors can narrow it\n * while staying assignable to this base.\n */\nexport abstract class AbstractRepository<\n TDataObject extends object,\n TPersistObject extends object = TDataObject,\n TOptions extends IExtraOptions = IExtraOptions,\n>\n extends BaseHelper\n implements IPersistableRepository<TDataObject, TPersistObject, TOptions>\n{\n protected _operationScope: TRepositoryOperationScope;\n\n /** Lazy-resolved on first access if not provided in constructor. */\n protected _dataSource?: AbstractDataSource;\n\n /** Lazy-resolved from @repository metadata on first access. */\n protected _entity?: AbstractEntity;\n\n /**\n * Memoized @model settings for `this.entity`'s class. `null` means not yet resolved - `undefined`\n * is itself a valid resolved value: the model declares no settings.\n */\n private _modelSettings: IModelMetadata['settings'] | null = null;\n\n constructor(\n dataSource?: AbstractDataSource,\n opts?: {\n scope?: string;\n entityClass?: TClass<AbstractEntity>;\n operationScope?: TRepositoryOperationScope;\n },\n ) {\n const scopeName =\n opts?.scope ??\n (opts?.entityClass?.name ? [opts.entityClass.name, 'Repository'].join('') : new.target.name);\n\n super({ scope: scopeName });\n\n this._operationScope = opts?.operationScope ?? RepositoryOperationScopes.READ_ONLY;\n\n if (dataSource) {\n this._dataSource = dataSource;\n }\n\n if (opts?.entityClass) {\n this._entity = new opts.entityClass();\n }\n }\n\n get dataSource(): AbstractDataSource {\n if (!this._dataSource) {\n throw getError({\n message: `[${this.constructor.name}] DataSource not available. Use @repository({ model: YourModel, dataSource: YourDataSource }) or pass dataSource in constructor.`,\n });\n }\n\n return this._dataSource;\n }\n\n set dataSource(value: AbstractDataSource) {\n this._dataSource = value;\n }\n\n /** Auto-resolves from @repository metadata if not explicitly set. */\n get entity(): AbstractEntity {\n this._entity ??= this.resolveEntity();\n\n return this._entity;\n }\n\n set entity(value: AbstractEntity) {\n this._entity = value;\n }\n\n get operationScope(): TRepositoryOperationScope {\n return this._operationScope;\n }\n\n setDataSource(opts: { dataSource: AbstractDataSource }): void {\n this._dataSource = opts.dataSource;\n }\n\n getEntity(): AbstractEntity {\n return this.entity;\n }\n\n /**\n * Resolved `@model` settings for `this.entity`'s class, keyed by Reflect target - not by\n * `entity.name`, which can diverge from the `@model` registry key.\n */\n protected get modelSettings(): IModelMetadata['settings'] {\n if (this._modelSettings !== null) {\n return this._modelSettings;\n }\n\n this._modelSettings = MetadataRegistry.getInstance().getModelMetadata({\n target: this.entity.constructor,\n })?.settings;\n\n return this._modelSettings;\n }\n\n protected get hiddenFields(): string[] {\n return this.modelSettings?.properties?.hidden ?? [];\n }\n\n /**\n * Refuses (400, `Column NOT FOUND`) a filter that came from a request and names a field the model hides, in its\n * `where`, its `order` or the `scope` of an `include` (judged by the hidden fields of the model it reads). The generated\n * controllers call it on what a client sends; the repository's own verbs do not, so server code can still filter and\n * sort on a hidden field.\n */\n assertRequestFilter(opts: { filter?: IRequestFilterShape }): void {\n RequestFilterGuard.assertFilter({\n filter: opts.filter,\n judge: this.createRequestFilterJudge(),\n tableName: this.entity?.name ?? this.constructor.name,\n });\n }\n\n /**\n * How this repository judges the keys of a request filter. The default reads a key as a dotted field name and refuses it with\n * a 400 `Column NOT FOUND`; a relational or a search repository overrides it to read keys as its own query does and to\n * refuse with its own query's error for a column that does not exist.\n */\n protected createRequestFilterJudge(): IRequestFilterJudge {\n const hidden = new Set(this.hiddenFields);\n\n return {\n isHidden: ({ key }) => RequestFilterGuard.isHiddenByName({ key, hidden }),\n refuse: ({ key }) => RequestFilterGuard.columnNotFound({ scope: this.constructor.name, key }),\n };\n }\n\n /** Default where from @model settings.query.filter.where, AND-merged into every query unless skipped. */\n protected get defaultWhere(): TWhere | undefined {\n return this.modelSettings?.query?.filter?.where;\n }\n\n protected get defaultLimit(): number | undefined {\n return this.modelSettings?.query?.limit?.default;\n }\n\n /** Largest `limit` a caller may ask for, when the model declares one; undefined leaves the tier's own default in force. */\n protected get maxLimit(): number | undefined {\n return this.modelSettings?.query?.limit?.max;\n }\n\n /**\n * Both bounds, in one place, for every tier.\n *\n * The upper bound is the point: `@model({ settings: { query: { limit: { max } } } })` is public and validated at\n * decoration time, but the relational tier read it nowhere, so `limit.max: 2` still issued\n * `LIMIT 50000000`.\n *\n * The lower bound matters just as much and is easy to miss: a NEGATIVE limit is not a smaller\n * page. Drizzle renders the LIMIT clause only when the value is `>= 0`, so a negative one removes\n * the clause and returns the whole table. The wire schema now rejects it too, but a server-side\n * caller reaches this method without passing through the schema at all.\n */\n protected assertLimitWithinCeiling(opts: { limit?: number; scope?: string }): void {\n const { limit, scope = 'find' } = opts;\n\n if (limit === undefined) {\n return;\n }\n\n // The shape check first, because it needs no metadata at all.\n if (!Number.isInteger(limit) || limit < 0) {\n throw getError({\n message: `[${this.constructor.name}][${scope}] Invalid 'limit' | Expected a non-negative integer | Got: ${limit}`,\n });\n }\n\n // `limit.max` reaches `modelSettings`, which resolves the entity - and THAT throws for a\n // repository with no `@repository` model binding. Such a repository is a misconfiguration this\n // method has no business reporting, and the caller path that used to reach `getDefaultLimit()`\n // never touched it either, because `??` short-circuits when a limit is given. So the ceiling is\n // consulted only when the binding that makes it resolvable is actually present.\n const hasModelBinding = Boolean(\n MetadataRegistry.getInstance().getRepositoryBinding({ target: this.constructor })?.model,\n );\n const ceiling = (hasModelBinding ? this.maxLimit : undefined) ?? DEFAULT_MAX_LIMIT;\n\n if (limit > ceiling) {\n throw getError({\n message: `[${this.constructor.name}][${scope}] Requested page exceeds this model's limit | requested: ${limit} | maximum: ${ceiling} | raise it with @model settings.query.limit.max if larger pages are genuinely needed`,\n });\n }\n }\n\n /**\n * The whole filter, relations included. Checking only the top-level `limit` left the identical\n * defect reachable one level down: a relation scope's negative limit drops Drizzle's LIMIT clause\n * for that relation and loads the entire related table.\n *\n * A relation's limit gets the SHAPE check only, not a ceiling. The ceiling belongs to the\n * relation's own model, which this repository cannot resolve - claiming otherwise would enforce\n * the parent's `limit.max` on a different entity.\n */\n protected assertFilterLimits(opts: { filter?: TFilter; scope?: string }): void {\n const { filter, scope = 'find' } = opts;\n\n if (!filter) {\n return;\n }\n\n this.assertLimitWithinCeiling({ limit: filter.limit, scope });\n\n const walk = (inclusions: TInclusion[] | undefined, path: string): void => {\n const inclusionsList = inclusions ?? [];\n\n for (const inclusion of inclusionsList) {\n const relationScope = inclusion.scope;\n\n if (!relationScope) {\n continue;\n }\n\n const relationPath = `${path}.${inclusion.relation}`;\n const relationLimit = relationScope.limit;\n\n if (\n relationLimit !== undefined &&\n (!Number.isInteger(relationLimit) || relationLimit < 0)\n ) {\n throw getError({\n message: `[${this.constructor.name}][${scope}] Invalid 'limit' on relation scope | relation: ${relationPath} | Expected a non-negative integer | Got: ${relationLimit}`,\n });\n }\n\n walk(relationScope.include, relationPath);\n }\n };\n\n walk(filter.include, scope);\n }\n\n /** Resolves the entity instance from @repository metadata on first access. */\n protected resolveEntity(): AbstractEntity {\n const registry = MetadataRegistry.getInstance();\n const binding = registry.getRepositoryBinding({ target: this.constructor });\n\n if (!binding?.model) {\n throw getError({\n message: `[${this.constructor.name}] Cannot resolve entity. Either pass entityClass in constructor or use @repository decorator with model option.`,\n });\n }\n\n // ResolverUtility.resolveValue() erases to the resolved value's structural type, not this class-or-resolver\n // union's member - the `@repository` decorator guarantees a class constructor here.\n const ModelClass = ResolverUtility.resolveValue({\n value: binding.model,\n }) as TClass<AbstractEntity>;\n\n return new ModelClass();\n }\n\n /** Rejects a verb the current operation scope does not permit. */\n protected denyOperation(opts: { methodName: string }): never {\n throw getError({\n messageCode: RepositoryErrorCodes.OPERATION_NOT_ALLOWED,\n message: `[${opts.methodName}] Repository operation is NOT ALLOWED | scope: ${this.operationScope}`,\n });\n }\n\n /**\n * Shared retry orchestration for read verbs. Inside a transaction retry is skipped - the pool\n * routes transactions to the primary, so there is no replica lag to wait out.\n */\n protected executeReadWithRetry<TResult>(opts: {\n operation: string;\n options: IExtraOptions & IWithReadRetry<TResult>;\n defaultUntil: (result: TResult) => boolean;\n execution: () => Promise<TResult>;\n }): Promise<TResult> {\n const { operation, options, defaultUntil, execution } = opts;\n\n if (!options.retry) {\n return execution();\n }\n\n if (options.transaction) {\n this.logger.for(operation).debug('Read retry skipped inside transaction');\n\n return execution();\n }\n\n const { maxAttempts, maxTotalMs, signal, backoff, until } = options.retry;\n\n return RetryHelper.executeWithRetryUntil<TResult>({\n operation: [this.constructor.name, operation].join('.'),\n execution,\n until: until ?? defaultUntil,\n maxAttempts,\n maxTotalMs,\n signal,\n backoff: backoff ?? {\n strategy: RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs: 50,\n maxDelayMs: 500,\n jitter: RetryJitterModes.EQUAL,\n },\n logger: this.logger,\n });\n }\n\n /**\n * A copy of `options` without `retry`, so re-entering a read verb takes its non-retry path - this\n * is what keeps the retry recursion single-depth. Copy-then-delete rather than a rest-destructure\n * (lint rejects the unused rest sibling) or `lodash/omit` (its `Omit<>` return type is not\n * assignable back to `TOptions`).\n */\n private omitReadRetry<TReadOptions extends { retry?: unknown }>(\n options: TReadOptions,\n ): TReadOptions {\n const rest = { ...options };\n delete rest.retry;\n\n return rest;\n }\n\n /** `find`, re-executed until the retry predicate holds - connectors dispatch here from `find` when `options.retry` is set. */\n protected findUntil<R = TDataObject>(opts: {\n filter: TFilter<TDataObject>;\n options: TFindOptions<TOptions, R>;\n }): Promise<Array<R>> {\n const options = this.omitReadRetry(opts.options);\n\n return this.executeReadWithRetry<Array<R>>({\n operation: 'find',\n options: opts.options,\n defaultUntil: (result) => result.length > 0,\n // `R` is named here, so the row is `R`; TypeScript cannot resolve `TRow` for an unresolved `R`.\n execution: () => this.find<R>({ filter: opts.filter, options }) as Promise<Array<R>>,\n });\n }\n\n /** `find` with the range envelope, re-executed until the retry predicate holds - split from `findUntil` so each result shape is checked against its own `find` overload. */\n protected findRangeUntil<R = TDataObject>(opts: {\n filter: TFilter<TDataObject>;\n options: TFindRangeOptions<TOptions, R>;\n }): Promise<TDataWithRange<R>> {\n const options = this.omitReadRetry(opts.options);\n\n return this.executeReadWithRetry<TDataWithRange<R>>({\n operation: 'find',\n options: opts.options,\n defaultUntil: (result) => result.data.length > 0,\n execution: () =>\n this.find<R>({ filter: opts.filter, options }) as unknown as Promise<TDataWithRange<R>>,\n });\n }\n\n /** `findOne`, re-executed until the retry predicate holds - also serves `findById` via its findOne delegation. */\n protected findOneUntil<R = TDataObject>(opts: {\n filter: TFilter<TDataObject>;\n options: TFindOneOptions<TOptions, R>;\n }): Promise<TNullable<R>> {\n const options = this.omitReadRetry(opts.options);\n\n return this.executeReadWithRetry<TNullable<R>>({\n operation: 'findOne',\n options: opts.options,\n defaultUntil: (result) => result !== null && result !== undefined,\n execution: () => this.findOne<R>({ filter: opts.filter, options }) as Promise<TNullable<R>>,\n });\n }\n\n abstract count(opts: { where: TWhere<TDataObject>; options?: TOptions }): Promise<TCount>;\n\n abstract existsWith(opts: { where: TWhere<TDataObject>; options?: TOptions }): Promise<boolean>;\n\n abstract find<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n filter: TFilter<TDataObject, F>;\n options: TFindRangeOptions<TOptions, TRow<TDataObject, R, F>>;\n }): Promise<TDataWithRange<TRow<TDataObject, R, F>>>;\n\n abstract find<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n filter: TFilter<TDataObject, F>;\n options?: TFindOptions<TOptions, TRow<TDataObject, R, F>>;\n }): Promise<Array<TRow<TDataObject, R, F>>>;\n\n abstract findOne<R = unknown, const F extends TFields<TDataObject> = TFields<TDataObject>>(opts: {\n filter: TFilter<TDataObject, F>;\n options?: TFindOneOptions<TOptions, TRow<TDataObject, R, F>>;\n }): Promise<TNullable<TRow<TDataObject, R, F>>>;\n\n abstract findById<\n R = unknown,\n const F extends TFields<TDataObject> = TFields<TDataObject>,\n >(opts: {\n id: IdType;\n filter?: TByIdFilter<TDataObject, F>;\n options?: TFindOneOptions<TOptions, TRow<TDataObject, R, F>>;\n }): Promise<TNullable<TRow<TDataObject, R, F>>>;\n\n abstract create(opts: {\n data: TPersistObject;\n options: TOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract create<R = TDataObject>(opts: {\n data: TPersistObject;\n options?: TOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract createAll(opts: {\n data: Array<TPersistObject>;\n options: TOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract createAll<R = TDataObject>(opts: {\n data: Array<TPersistObject>;\n options?: TOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: Array<R> }>;\n\n abstract updateById(opts: {\n id: IdType;\n data: Partial<TPersistObject>;\n options: TOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract updateById<R = TDataObject>(opts: {\n id: IdType;\n data: Partial<TPersistObject>;\n options?: TOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract updateAll(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options: TOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract updateAll<R = TDataObject>(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n\n /** Alias for updateAll. */\n updateBy(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options: TOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n updateBy<R = TDataObject>(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n updateBy<R = TDataObject>(opts: {\n data: Partial<TPersistObject>;\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: boolean; force?: boolean };\n }): Promise<TCount & { data: TNullable<Array<R>> }> {\n const { data, where, options } = opts;\n\n if (options?.shouldReturn === false) {\n return this.updateAll({ data, where, options: { ...options, shouldReturn: false } });\n }\n\n return this.updateAll<R>({ data, where, options });\n }\n\n abstract deleteById(opts: {\n id: IdType;\n options: TOptions & { shouldReturn: false };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract deleteById<R = TDataObject>(opts: {\n id: IdType;\n options?: TOptions & { shouldReturn?: true };\n }): Promise<TCount & { data: R }>;\n\n abstract deleteAll(opts: {\n where?: TWhere<TDataObject>;\n options: TOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n\n abstract deleteAll<R = TDataObject>(opts: {\n where?: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n\n /** Alias for deleteAll. */\n deleteBy(opts: {\n where: TWhere<TDataObject>;\n options: TOptions & { shouldReturn: false; force?: boolean };\n }): Promise<TCount & { data: undefined | null }>;\n deleteBy<R = TDataObject>(opts: {\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: true; force?: boolean };\n }): Promise<TCount & { data: Array<R> | null }>;\n deleteBy<R = TDataObject>(opts: {\n where: TWhere<TDataObject>;\n options?: TOptions & { shouldReturn?: boolean; force?: boolean };\n }): Promise<TCount & { data: TNullable<Array<R>> }> {\n const { where, options } = opts;\n\n if (options?.shouldReturn === false) {\n return this.deleteAll({ where, options: { ...options, shouldReturn: false } });\n }\n\n return this.deleteAll<R>({ where, options });\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- /** Application statuses categorized by lifecycle phase (initial, pending, active, completed, inactive, failed). */
1
+ /** Application statuses categorized by lifecycle phase: the leading digit of a code is its phase (0 initial, 1 pending, 2 active, 3 completed, 4 inactive, 5 failed). */
2
2
  export declare class Statuses {
3
3
  static readonly UNKNOWN = "000_UNKNOWN";
4
4
  static readonly DRAFT = "001_DRAFT";
@@ -7,18 +7,24 @@ export declare class Statuses {
7
7
  static readonly SCHEDULED = "102_SCHEDULED";
8
8
  static readonly PENDING = "103_PENDING";
9
9
  static readonly IN_REVIEW = "104_IN_REVIEW";
10
+ static readonly OPEN = "105_OPEN";
11
+ static readonly SUBMITTED = "106_SUBMITTED";
10
12
  static readonly ENABLED = "200_ENABLED";
11
13
  static readonly ACTIVATED = "201_ACTIVATED";
12
14
  static readonly RUNNING = "202_RUNNING";
13
15
  static readonly PROCESSING = "203_PROCESSING";
14
16
  static readonly SENT = "204_SENT";
15
17
  static readonly RECEIVED = "205_RECEIVED";
18
+ static readonly READY = "206_READY";
19
+ static readonly PUBLISHED = "207_PUBLISHED";
20
+ static readonly ISSUED = "208_ISSUED";
16
21
  static readonly PARTIAL = "300_PARTIAL";
17
22
  static readonly APPROVED = "301_APPROVED";
18
23
  static readonly SUCCESS = "302_SUCCESS";
19
24
  static readonly COMPLETED = "303_COMPLETED";
20
25
  static readonly SETTLED = "304_SETTLED";
21
26
  static readonly CONFIRMED = "305_CONFIRMED";
27
+ static readonly RESOLVED = "306_RESOLVED";
22
28
  static readonly DISABLED = "400_DISABLED";
23
29
  static readonly DEACTIVATED = "401_DEACTIVATED";
24
30
  static readonly SUSPENDED = "402_SUSPENDED";
@@ -36,6 +42,7 @@ export declare class Statuses {
36
42
  static readonly CANCELLED = "505_CANCELLED";
37
43
  static readonly DELETED = "506_DELETED";
38
44
  static readonly REJECTED = "507_REJECTED";
45
+ static readonly VOIDED = "508_VOIDED";
39
46
  static readonly INITIAL_SCHEME_SET: Set<string>;
40
47
  static readonly PENDING_SCHEME_SET: Set<string>;
41
48
  static readonly ACTIVE_SCHEME_SET: Set<string>;
@@ -1,4 +1,6 @@
1
- /** Application statuses categorized by lifecycle phase (initial, pending, active, completed, inactive, failed). */
1
+ /** The shape of a status code: a phase digit 0-5, two digits, then the name. */
2
+ const STATUS_CODE = /^[0-5]\d{2}_[A-Z0-9_]+$/;
3
+ /** Application statuses categorized by lifecycle phase: the leading digit of a code is its phase (0 initial, 1 pending, 2 active, 3 completed, 4 inactive, 5 failed). */
2
4
  export class Statuses {
3
5
  // 0xx - Initial
4
6
  static { this.UNKNOWN = '000_UNKNOWN'; }
@@ -9,6 +11,8 @@ export class Statuses {
9
11
  static { this.SCHEDULED = '102_SCHEDULED'; }
10
12
  static { this.PENDING = '103_PENDING'; }
11
13
  static { this.IN_REVIEW = '104_IN_REVIEW'; }
14
+ static { this.OPEN = '105_OPEN'; }
15
+ static { this.SUBMITTED = '106_SUBMITTED'; }
12
16
  // 2xx - Active/Running (in progress)
13
17
  static { this.ENABLED = '200_ENABLED'; }
14
18
  static { this.ACTIVATED = '201_ACTIVATED'; }
@@ -16,6 +20,9 @@ export class Statuses {
16
20
  static { this.PROCESSING = '203_PROCESSING'; }
17
21
  static { this.SENT = '204_SENT'; }
18
22
  static { this.RECEIVED = '205_RECEIVED'; }
23
+ static { this.READY = '206_READY'; }
24
+ static { this.PUBLISHED = '207_PUBLISHED'; }
25
+ static { this.ISSUED = '208_ISSUED'; }
19
26
  // 3xx - Completed (positive terminal)
20
27
  static { this.PARTIAL = '300_PARTIAL'; }
21
28
  static { this.APPROVED = '301_APPROVED'; }
@@ -23,6 +30,7 @@ export class Statuses {
23
30
  static { this.COMPLETED = '303_COMPLETED'; }
24
31
  static { this.SETTLED = '304_SETTLED'; }
25
32
  static { this.CONFIRMED = '305_CONFIRMED'; }
33
+ static { this.RESOLVED = '306_RESOLVED'; }
26
34
  // 4xx - Inactive (negative, reversible)
27
35
  static { this.DISABLED = '400_DISABLED'; }
28
36
  static { this.DEACTIVATED = '401_DEACTIVATED'; }
@@ -42,6 +50,7 @@ export class Statuses {
42
50
  static { this.CANCELLED = '505_CANCELLED'; }
43
51
  static { this.DELETED = '506_DELETED'; }
44
52
  static { this.REJECTED = '507_REJECTED'; }
53
+ static { this.VOIDED = '508_VOIDED'; }
45
54
  static { this.INITIAL_SCHEME_SET = new Set([this.UNKNOWN, this.DRAFT]); }
46
55
  static { this.PENDING_SCHEME_SET = new Set([
47
56
  this.NEW,
@@ -49,6 +58,8 @@ export class Statuses {
49
58
  this.SCHEDULED,
50
59
  this.PENDING,
51
60
  this.IN_REVIEW,
61
+ this.OPEN,
62
+ this.SUBMITTED,
52
63
  ]); }
53
64
  static { this.ACTIVE_SCHEME_SET = new Set([
54
65
  this.ENABLED,
@@ -57,6 +68,9 @@ export class Statuses {
57
68
  this.PROCESSING,
58
69
  this.SENT,
59
70
  this.RECEIVED,
71
+ this.READY,
72
+ this.PUBLISHED,
73
+ this.ISSUED,
60
74
  ]); }
61
75
  static { this.COMPLETED_SCHEME_SET = new Set([
62
76
  this.COMPLETED,
@@ -65,6 +79,7 @@ export class Statuses {
65
79
  this.SETTLED,
66
80
  this.APPROVED,
67
81
  this.CONFIRMED,
82
+ this.RESOLVED,
68
83
  ]); }
69
84
  static { this.INACTIVE_SCHEME_SET = new Set([
70
85
  this.DISABLED,
@@ -86,6 +101,7 @@ export class Statuses {
86
101
  this.CANCELLED,
87
102
  this.DELETED,
88
103
  this.REJECTED,
104
+ this.VOIDED,
89
105
  ]); }
90
106
  static { this.SCHEME_SET = new Set([
91
107
  ...this.INITIAL_SCHEME_SET,
@@ -96,25 +112,25 @@ export class Statuses {
96
112
  ...this.FAILED_SCHEME_SET,
97
113
  ]); }
98
114
  static isInitial(status) {
99
- return this.INITIAL_SCHEME_SET.has(status);
115
+ return status.startsWith('0');
100
116
  }
101
117
  static isPending(status) {
102
- return this.PENDING_SCHEME_SET.has(status);
118
+ return status.startsWith('1');
103
119
  }
104
120
  static isActive(status) {
105
- return this.ACTIVE_SCHEME_SET.has(status);
121
+ return status.startsWith('2');
106
122
  }
107
123
  static isCompleted(status) {
108
- return this.COMPLETED_SCHEME_SET.has(status);
124
+ return status.startsWith('3');
109
125
  }
110
126
  static isInactive(status) {
111
- return this.INACTIVE_SCHEME_SET.has(status);
127
+ return status.startsWith('4');
112
128
  }
113
129
  static isFailed(status) {
114
- return this.FAILED_SCHEME_SET.has(status);
130
+ return status.startsWith('5');
115
131
  }
116
132
  static isValid(status) {
117
- return this.SCHEME_SET.has(status);
133
+ return STATUS_CODE.test(status);
118
134
  }
119
135
  }
120
136
  /** Common reusable entity statuses. */
@@ -1 +1 @@
1
- {"version":3,"file":"common.js","sourceRoot":"","sources":["../../../../src/common/statuses/common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AAW,CAAC;aACnC,YAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;aAC3B,aAAQ,GAAG,QAAQ,CAAC,QAAQ,CAAC;aAE7B,eAAU,GAAG,IAAI,GAAG,CAAC;QACnC,IAAI,CAAC,OAAO;QACZ,IAAI,CAAC,SAAS;QACd,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,OAAO;QACZ,IAAI,CAAC,QAAQ;KACd,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,MAAc;QAC3B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC","sourcesContent":["/** Application statuses categorized by lifecycle phase (initial, pending, active, completed, inactive, failed). */\nexport class Statuses {\n // 0xx - Initial\n static readonly UNKNOWN = '000_UNKNOWN';\n static readonly DRAFT = '001_DRAFT';\n\n // 1xx - Pending/Waiting (awaiting action/decision)\n static readonly NEW = '100_NEW';\n static readonly QUEUED = '101_QUEUED';\n static readonly SCHEDULED = '102_SCHEDULED';\n static readonly PENDING = '103_PENDING';\n static readonly IN_REVIEW = '104_IN_REVIEW';\n\n // 2xx - Active/Running (in progress)\n static readonly ENABLED = '200_ENABLED';\n static readonly ACTIVATED = '201_ACTIVATED';\n static readonly RUNNING = '202_RUNNING';\n static readonly PROCESSING = '203_PROCESSING';\n static readonly SENT = '204_SENT';\n static readonly RECEIVED = '205_RECEIVED';\n\n // 3xx - Completed (positive terminal)\n static readonly PARTIAL = '300_PARTIAL';\n static readonly APPROVED = '301_APPROVED';\n static readonly SUCCESS = '302_SUCCESS';\n static readonly COMPLETED = '303_COMPLETED';\n static readonly SETTLED = '304_SETTLED';\n static readonly CONFIRMED = '305_CONFIRMED';\n\n // 4xx - Inactive (negative, reversible)\n static readonly DISABLED = '400_DISABLED';\n static readonly DEACTIVATED = '401_DEACTIVATED';\n static readonly SUSPENDED = '402_SUSPENDED';\n static readonly BLOCKED = '403_BLOCKED';\n static readonly CLOSED = '404_CLOSED';\n static readonly ARCHIVED = '405_ARCHIVED';\n static readonly PAUSED = '406_PAUSED';\n static readonly REVOKED = '407_REVOKED';\n static readonly REFUNDED = '408_REFUNDED';\n\n // 5xx - Failed/Error (negative terminal, final)\n static readonly FAIL = '500_FAIL';\n static readonly EXPIRED = '501_EXPIRED';\n static readonly TIMEOUT = '502_TIMEOUT';\n static readonly SKIPPED = '503_SKIPPED';\n static readonly ABORTED = '504_ABORTED';\n static readonly CANCELLED = '505_CANCELLED';\n static readonly DELETED = '506_DELETED';\n static readonly REJECTED = '507_REJECTED';\n\n static readonly INITIAL_SCHEME_SET = new Set([this.UNKNOWN, this.DRAFT]);\n\n static readonly PENDING_SCHEME_SET = new Set([\n this.NEW,\n this.QUEUED,\n this.SCHEDULED,\n this.PENDING,\n this.IN_REVIEW,\n ]);\n\n static readonly ACTIVE_SCHEME_SET = new Set([\n this.ENABLED,\n this.ACTIVATED,\n this.RUNNING,\n this.PROCESSING,\n this.SENT,\n this.RECEIVED,\n ]);\n\n static readonly COMPLETED_SCHEME_SET = new Set([\n this.COMPLETED,\n this.SUCCESS,\n this.PARTIAL,\n this.SETTLED,\n this.APPROVED,\n this.CONFIRMED,\n ]);\n\n static readonly INACTIVE_SCHEME_SET = new Set([\n this.DISABLED,\n this.DEACTIVATED,\n this.SUSPENDED,\n this.BLOCKED,\n this.CLOSED,\n this.ARCHIVED,\n this.PAUSED,\n this.REVOKED,\n this.REFUNDED,\n ]);\n\n static readonly FAILED_SCHEME_SET = new Set([\n this.FAIL,\n this.EXPIRED,\n this.TIMEOUT,\n this.SKIPPED,\n this.ABORTED,\n this.CANCELLED,\n this.DELETED,\n this.REJECTED,\n ]);\n\n static readonly SCHEME_SET = new Set([\n ...this.INITIAL_SCHEME_SET,\n ...this.PENDING_SCHEME_SET,\n ...this.ACTIVE_SCHEME_SET,\n ...this.COMPLETED_SCHEME_SET,\n ...this.INACTIVE_SCHEME_SET,\n ...this.FAILED_SCHEME_SET,\n ]);\n\n static isInitial(status: string): boolean {\n return this.INITIAL_SCHEME_SET.has(status);\n }\n\n static isPending(status: string): boolean {\n return this.PENDING_SCHEME_SET.has(status);\n }\n\n static isActive(status: string): boolean {\n return this.ACTIVE_SCHEME_SET.has(status);\n }\n\n static isCompleted(status: string): boolean {\n return this.COMPLETED_SCHEME_SET.has(status);\n }\n\n static isInactive(status: string): boolean {\n return this.INACTIVE_SCHEME_SET.has(status);\n }\n\n static isFailed(status: string): boolean {\n return this.FAILED_SCHEME_SET.has(status);\n }\n\n static isValid(status: string): boolean {\n return this.SCHEME_SET.has(status);\n }\n}\n\n/** Common reusable entity statuses. */\nexport class CommonStatuses {\n static readonly UNKNOWN = Statuses.UNKNOWN;\n static readonly ACTIVATED = Statuses.ACTIVATED;\n static readonly DEACTIVATED = Statuses.DEACTIVATED;\n static readonly BLOCKED = Statuses.BLOCKED;\n static readonly ARCHIVED = Statuses.ARCHIVED;\n\n static readonly SCHEME_SET = new Set([\n this.UNKNOWN,\n this.ACTIVATED,\n this.DEACTIVATED,\n this.BLOCKED,\n this.ARCHIVED,\n ]);\n\n static isValid(scheme: string): boolean {\n return this.SCHEME_SET.has(scheme);\n }\n}\n"]}
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../../../../src/common/statuses/common.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAE9C,yKAAyK;AACzK,MAAM,OAAO,QAAQ;IACnB,gBAAgB;aACA,YAAO,GAAG,aAAa,CAAC;aACxB,UAAK,GAAG,WAAW,CAAC;IAEpC,mDAAmD;aACnC,QAAG,GAAG,SAAS,CAAC;aAChB,WAAM,GAAG,YAAY,CAAC;aACtB,cAAS,GAAG,eAAe,CAAC;aAC5B,YAAO,GAAG,aAAa,CAAC;aACxB,cAAS,GAAG,eAAe,CAAC;aAC5B,SAAI,GAAG,UAAU,CAAC;aAClB,cAAS,GAAG,eAAe,CAAC;IAE5C,qCAAqC;aACrB,YAAO,GAAG,aAAa,CAAC;a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CAAC;QACnC,IAAI,CAAC,OAAO;QACZ,IAAI,CAAC,SAAS;QACd,IAAI,CAAC,WAAW;QAChB,IAAI,CAAC,OAAO;QACZ,IAAI,CAAC,QAAQ;KACd,CAAC,CAAC;IAEH,MAAM,CAAC,OAAO,CAAC,MAAc;QAC3B,OAAO,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC","sourcesContent":["/** The shape of a status code: a phase digit 0-5, two digits, then the name. */\nconst STATUS_CODE = /^[0-5]\\d{2}_[A-Z0-9_]+$/;\n\n/** Application statuses categorized by lifecycle phase: the leading digit of a code is its phase (0 initial, 1 pending, 2 active, 3 completed, 4 inactive, 5 failed). */\nexport class Statuses {\n // 0xx - Initial\n static readonly UNKNOWN = '000_UNKNOWN';\n static readonly DRAFT = '001_DRAFT';\n\n // 1xx - Pending/Waiting (awaiting action/decision)\n static readonly NEW = '100_NEW';\n static readonly QUEUED = '101_QUEUED';\n static readonly SCHEDULED = '102_SCHEDULED';\n static readonly PENDING = '103_PENDING';\n static readonly IN_REVIEW = '104_IN_REVIEW';\n static readonly OPEN = '105_OPEN';\n static readonly SUBMITTED = '106_SUBMITTED';\n\n // 2xx - Active/Running (in progress)\n static readonly ENABLED = '200_ENABLED';\n static readonly ACTIVATED = '201_ACTIVATED';\n static readonly RUNNING = '202_RUNNING';\n static readonly PROCESSING = '203_PROCESSING';\n static readonly SENT = '204_SENT';\n static readonly RECEIVED = '205_RECEIVED';\n static readonly READY = '206_READY';\n static readonly PUBLISHED = '207_PUBLISHED';\n static readonly ISSUED = '208_ISSUED';\n\n // 3xx - Completed (positive terminal)\n static readonly PARTIAL = '300_PARTIAL';\n static readonly APPROVED = '301_APPROVED';\n static readonly SUCCESS = '302_SUCCESS';\n static readonly COMPLETED = '303_COMPLETED';\n static readonly SETTLED = '304_SETTLED';\n static readonly CONFIRMED = '305_CONFIRMED';\n static readonly RESOLVED = '306_RESOLVED';\n\n // 4xx - Inactive (negative, reversible)\n static readonly DISABLED = '400_DISABLED';\n static readonly DEACTIVATED = '401_DEACTIVATED';\n static readonly SUSPENDED = '402_SUSPENDED';\n static readonly BLOCKED = '403_BLOCKED';\n static readonly CLOSED = '404_CLOSED';\n static readonly ARCHIVED = '405_ARCHIVED';\n static readonly PAUSED = '406_PAUSED';\n static readonly REVOKED = '407_REVOKED';\n static readonly REFUNDED = '408_REFUNDED';\n\n // 5xx - Failed/Error (negative terminal, final)\n static readonly FAIL = '500_FAIL';\n static readonly EXPIRED = '501_EXPIRED';\n static readonly TIMEOUT = '502_TIMEOUT';\n static readonly SKIPPED = '503_SKIPPED';\n static readonly ABORTED = '504_ABORTED';\n static readonly CANCELLED = '505_CANCELLED';\n static readonly DELETED = '506_DELETED';\n static readonly REJECTED = '507_REJECTED';\n static readonly VOIDED = '508_VOIDED';\n\n static readonly INITIAL_SCHEME_SET = new Set([this.UNKNOWN, this.DRAFT]);\n\n static readonly PENDING_SCHEME_SET = new Set([\n this.NEW,\n this.QUEUED,\n this.SCHEDULED,\n this.PENDING,\n this.IN_REVIEW,\n this.OPEN,\n this.SUBMITTED,\n ]);\n\n static readonly ACTIVE_SCHEME_SET = new Set([\n this.ENABLED,\n this.ACTIVATED,\n this.RUNNING,\n this.PROCESSING,\n this.SENT,\n this.RECEIVED,\n this.READY,\n this.PUBLISHED,\n this.ISSUED,\n ]);\n\n static readonly COMPLETED_SCHEME_SET = new Set([\n this.COMPLETED,\n this.SUCCESS,\n this.PARTIAL,\n this.SETTLED,\n this.APPROVED,\n this.CONFIRMED,\n this.RESOLVED,\n ]);\n\n static readonly INACTIVE_SCHEME_SET = new Set([\n this.DISABLED,\n this.DEACTIVATED,\n this.SUSPENDED,\n this.BLOCKED,\n this.CLOSED,\n this.ARCHIVED,\n this.PAUSED,\n this.REVOKED,\n this.REFUNDED,\n ]);\n\n static readonly FAILED_SCHEME_SET = new Set([\n this.FAIL,\n this.EXPIRED,\n this.TIMEOUT,\n this.SKIPPED,\n this.ABORTED,\n this.CANCELLED,\n this.DELETED,\n this.REJECTED,\n this.VOIDED,\n ]);\n\n static readonly SCHEME_SET = new Set([\n ...this.INITIAL_SCHEME_SET,\n ...this.PENDING_SCHEME_SET,\n ...this.ACTIVE_SCHEME_SET,\n ...this.COMPLETED_SCHEME_SET,\n ...this.INACTIVE_SCHEME_SET,\n ...this.FAILED_SCHEME_SET,\n ]);\n\n static isInitial(status: string): boolean {\n return status.startsWith('0');\n }\n\n static isPending(status: string): boolean {\n return status.startsWith('1');\n }\n\n static isActive(status: string): boolean {\n return status.startsWith('2');\n }\n\n static isCompleted(status: string): boolean {\n return status.startsWith('3');\n }\n\n static isInactive(status: string): boolean {\n return status.startsWith('4');\n }\n\n static isFailed(status: string): boolean {\n return status.startsWith('5');\n }\n\n static isValid(status: string): boolean {\n return STATUS_CODE.test(status);\n }\n}\n\n/** Common reusable entity statuses. */\nexport class CommonStatuses {\n static readonly UNKNOWN = Statuses.UNKNOWN;\n static readonly ACTIVATED = Statuses.ACTIVATED;\n static readonly DEACTIVATED = Statuses.DEACTIVATED;\n static readonly BLOCKED = Statuses.BLOCKED;\n static readonly ARCHIVED = Statuses.ARCHIVED;\n\n static readonly SCHEME_SET = new Set([\n this.UNKNOWN,\n this.ACTIVATED,\n this.DEACTIVATED,\n this.BLOCKED,\n this.ARCHIVED,\n ]);\n\n static isValid(scheme: string): boolean {\n return this.SCHEME_SET.has(scheme);\n }\n}\n"]}
@@ -165,10 +165,20 @@ export interface IModelQuerySettings {
165
165
  max?: number;
166
166
  };
167
167
  }
168
+ /** Property groups of `@model` settings. */
169
+ export interface IModelProperties {
170
+ /** Properties excluded from all query results at SQL level. */
171
+ hidden?: string[];
172
+ /**
173
+ * Properties the server fills on every write, which a generated create or update body leaves out.
174
+ *
175
+ * @default AuditFields.SCHEME_SET
176
+ */
177
+ stamped?: ReadonlyArray<string> | ReadonlySet<string>;
178
+ }
168
179
  /** Per-model settings passed to `@model` as `settings`. */
169
180
  export interface IModelSettings {
170
- /** Properties excluded from all query results at SQL level. */
171
- hiddenProperties?: string[];
181
+ properties?: IModelProperties;
172
182
  /** Default filter and limits of a query: `filter`, `limit.default`, `limit.max`. */
173
183
  query?: IModelQuerySettings;
174
184
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"model.js","sourceRoot":"","sources":["../../../../../../src/helpers/inversion/common/types/model.ts"],"names":[],"mappings":"","sourcesContent":["import type { AbstractEntity, TModelType } from '@/base/models';\nimport type {\n ScopeFilters,\n ScopeThrough,\n TFilter,\n TScopeFilterMissingBehavior,\n TScopeOperation,\n TScopeWriteGuard,\n TWhere,\n} from '@/base/repositories';\nimport type { TClass, TNullable, TValueOrResolver } from '@venizia/ignis-helpers/common';\nimport type { IArtifactRegistrationOptions } from './artifact';\n\n/** The `authorize` settings of a model. */\nexport interface IModelAuthorizeSettings {\n /** The authorization principal name (resource/subject) for this model. */\n principal: string;\n /** Extensible - consumers can add any extra authorization metadata. */\n [extra: string | symbol]: any;\n}\n\n/** What a restricted caller may write to the scope columns (`@model` settings.access.write). */\nexport interface IModelAccessWriteSettings {\n /**\n * What a create, createAll or an update payload that names a scope column does when its value\n * disagrees with the resolved scope. `reject` refuses the write and writes nothing - for\n * `createAll` not even the valid rows. `assign` also fills a scope column that is ABSENT from a\n * created row, when the scope is a single equality; a value that is present and disagrees is\n * still refused.\n *\n * The scope's columns and allowed values are read from the resolved `where` (equality, `eq`, `inq`\n * and arrays, `and`, and an `or` over one column). Any other shape cannot be checked, and the write\n * is refused with its own message - never skipped. `ScopeFilters.UNRESTRICTED` bypasses the guard\n * too, which is the deliberate way to write across scopes (system scope, an admin role).\n *\n * Not checked: an update that does not name the scope column (the row was already selected through\n * the scoped `where`), and raw statements that bypass the repository.\n *\n * @default 'reject'\n */\n mode?: TScopeWriteGuard;\n\n /**\n * `true` lets a restricted caller write `null` to a scope column, or leave it out on create: the\n * row has no owner and is shared. Without it, `null` is refused like any other value\n * outside the scope, even when the resolved scope has a `null` branch (that branch lets the caller\n * READ shared rows, a separate permission). Reads are scoped as before.\n *\n * @default false\n */\n sharedRows?: boolean;\n}\n\n/**\n * Row access for `@model` settings.access - resolved per query, so it can depend on the current\n * request (tenant, org, membership). Framework-internal escape hatches aside, nothing short of\n * removing this setting from the model turns scoping off.\n *\n * @example\n * ```typescript\n * import { model, ScopeWriteGuards } from '@venizia/ignis';\n * import { ModelFactory } from '@venizia/ignis-connectors/postgres';\n * import { pgTable, serial, text } from 'drizzle-orm/pg-core';\n *\n * const productTable = pgTable('Product', { id: serial('id').primaryKey(), merchantId: text('merchant_id') });\n *\n * export @model({ settings: { access: {\n * resolve: () => ({ merchantId: 'm-1' }),\n * write: { mode: ScopeWriteGuards.ASSIGN },\n * } } })\n * class Product extends ModelFactory.defineEntity({ table: productTable }) {}\n * ```\n */\nexport interface IModelAccessSettings {\n /** A model declares a resolver or a `through`, never both. */\n through?: never;\n\n /**\n * Returns the scope `where`; `ScopeFilters.UNRESTRICTED` to apply no scope for THIS call (an\n * internal operator, a caller the application has decided sees everything); or null/undefined\n * when this caller's scope cannot be determined at all.\n *\n * Receives `{ operation }`: the one concrete operation the call performs (`ScopeOperations.READ`,\n * `CREATE`, `UPDATE` or `DELETE`, never a group), so one function can answer a wide scope for a\n * read and a narrow one for a write. A read, and an included relation, pass `READ`; a create passes\n * `CREATE`; an update passes `UPDATE` for the payload check and for choosing the rows to update; a\n * delete, a soft delete included, passes `DELETE` for both; a restore passes `UPDATE`. A read with a\n * row `lock` passes `READ`. A resolver that takes no argument keeps working. An `or` over different\n * columns is still refused on a write, so return the narrow scope for a write operation.\n */\n resolve: (context: {\n operation: TScopeOperation;\n }) => TNullable<TWhere> | typeof ScopeFilters.UNRESTRICTED;\n\n /**\n * What `applyScopeFilter` does when `resolve()` returns null/undefined - no request context, no\n * tenant, a background job. With `deny`, an unresolved scope matches zero rows, never\n * every row. `allow` is an explicit, reviewed opt-out for migrations and background jobs, declared\n * per MODEL - it cannot express a per-USER bypass; use `ScopeFilters.UNRESTRICTED` for that.\n *\n * @default 'deny'\n */\n onMissing?: TScopeFilterMissingBehavior;\n\n /**\n * The property names the write guard checks. Optional: with none declared the guard checks every\n * column the resolved scope constrains. When declared, each name must exist on the model (checked\n * at boot), and a resolved scope that constrains any other column is refused as unverifiable.\n */\n columns?: string[];\n\n /** What a restricted caller may write to the scope columns. See {@link IModelAccessWriteSettings}. */\n write?: IModelAccessWriteSettings;\n}\n\n/**\n * Row access for a child model that has no scope columns of its own: it inherits the scope of the parent a `one`\n * relation points at. A parent that resolves no scope always denies the child: `onMissing` is not offered here, because\n * `'allow'` would show the child's rows of every tenant while the parent shows none.\n *\n * @example\n * ```typescript\n * import { model, ScopeThrough } from '@venizia/ignis';\n * import { ModelFactory, one } from '@venizia/ignis-connectors/postgres';\n * import { integer, pgTable, serial } from 'drizzle-orm/pg-core';\n * const productTable = pgTable('Product', { id: serial('id').primaryKey() });\n * const variantTable = pgTable('Variant', {\n * id: serial('id').primaryKey(),\n * productId: integer('product_id').references(() => productTable.id),\n * });\n * const VariantBase = ModelFactory.defineEntity({ table: variantTable, relations: () => ({ product: one(productTable) }) });\n * export @model({ settings: { access: { through: ScopeThrough.of({ entity: VariantBase, relation: 'product' }) } } })\n * class Variant extends VariantBase {}\n * ```\n *\n * @example\n * ```typescript\n * // A hand-written entity declares the same relation by hand.\n * import { ScopeThrough } from '@venizia/ignis';\n * import { BaseEntity, one, RelationDeclarations } from '@venizia/ignis-connectors/postgres';\n * import { integer, pgTable, serial } from 'drizzle-orm/pg-core';\n * const productTable = pgTable('Product', { id: serial('id').primaryKey() });\n * const variantTable = pgTable('Variant', { id: serial('id').primaryKey(), productId: integer('product_id').references(() => productTable.id) });\n * const relations = { product: one(productTable) };\n * class VariantBase extends BaseEntity<typeof variantTable> {\n * static override schema = variantTable;\n * static readonly relationDefinitions = relations;\n * static override relations = () => RelationDeclarations.toRelationConfigs({ relations });\n * }\n * const through = ScopeThrough.of({ entity: VariantBase, relation: 'product' });\n * ```\n */\nexport interface IModelAccessThroughSettings {\n through: ScopeThrough;\n onMissing?: never;\n resolve?: never;\n columns?: never;\n write?: never;\n}\n\n/** The two shapes of `@model` settings.access: a resolver, or a `through`. */\nexport type TModelAccessSettings = IModelAccessSettings | IModelAccessThroughSettings;\n\n/** What a query runs with when it names nothing (`@model` settings.query). */\nexport interface IModelQuerySettings {\n /** Default filter auto-applied to all repository operations. Bypassable via shouldSkipDefaultFilter. */\n filter?: TFilter;\n\n limit?: {\n /**\n * Row limit when a query omits `limit`. Must be a positive integer.\n *\n * @default DEFAULT_LIMIT\n */\n default?: number;\n\n /**\n * Largest `limit` a CALLER may ask for. Must be a positive integer.\n *\n * Policy, not capacity - the engine's own ceiling sits far above it. The number is chosen so\n * that reaching it means the caller is doing something unusual, and raising it is how a model\n * says so deliberately.\n *\n * @default DEFAULT_MAX_LIMIT\n */\n max?: number;\n };\n}\n\n/** Per-model settings passed to `@model` as `settings`. */\nexport interface IModelSettings {\n /** Properties excluded from all query results at SQL level. */\n hiddenProperties?: string[];\n\n /** Default filter and limits of a query: `filter`, `limit.default`, `limit.max`. */\n query?: IModelQuerySettings;\n\n /**\n * Row access: the scope ANDed into every read and write whose scope is expressible as a filter\n * clause, NOT removable by `shouldSkipDefaultFilter`, and the guard that holds writes to it.\n * Ownership resolved per row or through a polymorphic reference is NOT expressible here - that\n * check is still the application's to perform.\n *\n * Relational repositories only - a search-backed model (Typesense, Meilisearch) never reads\n * this setting, so mirroring a scoped entity into a search index needs its own query-time scope.\n */\n access?: TModelAccessSettings;\n\n /** Authorization settings for this model (principal name, etc.). */\n authorize?: IModelAuthorizeSettings;\n}\n\n/** Whether tooling that reads the model registry should migrate this model (`@model({ migration })`). */\nexport interface IModelMigrationSettings {\n /**\n * `false` marks the model as one a migration tool leaves alone. IGNIS generates no migrations itself.\n *\n * @default true\n */\n use?: boolean;\n}\n\n/** Metadata accepted by `@model`. */\nexport interface IModelMetadata extends IArtifactRegistrationOptions {\n /**\n * `ModelTypes.ENTITY` is the only value.\n *\n * @default ModelTypes.ENTITY\n */\n type?: TModelType;\n tableName?: string;\n\n /** Migration marker for consumer tooling that reads the public registry. */\n migration?: IModelMigrationSettings;\n\n settings?: IModelSettings;\n}\n\n/** Static members an entity class carries: its `schema` and its `relations` (value or resolver). */\nexport interface IEntityStatics {\n schema?: unknown;\n relations?: TValueOrResolver<Array<unknown>>;\n}\n\n/** A model class together with its entity statics. */\nexport type TModelClass<Model extends AbstractEntity = AbstractEntity> = TClass<Model> &\n IEntityStatics;\n\n/** Decorator target for model classes (supports both strongly typed and ClassDecorator patterns). */\nexport type TDecoratorModelTarget<Model extends AbstractEntity = AbstractEntity> =\n | TModelClass<Model>\n | (Function & IEntityStatics);\n\n/** One model as stored in the metadata registry: class, metadata and schema, with lazily resolved relations. */\nexport interface IModelRegistryEntry<Model extends AbstractEntity = AbstractEntity> {\n target: TValueOrResolver<TClass<Model>>;\n metadata: IModelMetadata;\n schema: unknown;\n\n /** Lazy resolver to avoid circular deps. Resolved when DataSource builds schema. */\n relationsResolver?: TValueOrResolver<Array<unknown>>;\n\n /** Cache populated on first buildSchema() call. */\n _builtRelations?: unknown;\n}\n"]}
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../../../../../src/helpers/inversion/common/types/model.ts"],"names":[],"mappings":"","sourcesContent":["import type { AbstractEntity, TModelType } from '@/base/models';\nimport type {\n ScopeFilters,\n ScopeThrough,\n TFilter,\n TScopeFilterMissingBehavior,\n TScopeOperation,\n TScopeWriteGuard,\n TWhere,\n} from '@/base/repositories';\nimport type { TClass, TNullable, TValueOrResolver } from '@venizia/ignis-helpers/common';\nimport type { IArtifactRegistrationOptions } from './artifact';\n\n/** The `authorize` settings of a model. */\nexport interface IModelAuthorizeSettings {\n /** The authorization principal name (resource/subject) for this model. */\n principal: string;\n /** Extensible - consumers can add any extra authorization metadata. */\n [extra: string | symbol]: any;\n}\n\n/** What a restricted caller may write to the scope columns (`@model` settings.access.write). */\nexport interface IModelAccessWriteSettings {\n /**\n * What a create, createAll or an update payload that names a scope column does when its value\n * disagrees with the resolved scope. `reject` refuses the write and writes nothing - for\n * `createAll` not even the valid rows. `assign` also fills a scope column that is ABSENT from a\n * created row, when the scope is a single equality; a value that is present and disagrees is\n * still refused.\n *\n * The scope's columns and allowed values are read from the resolved `where` (equality, `eq`, `inq`\n * and arrays, `and`, and an `or` over one column). Any other shape cannot be checked, and the write\n * is refused with its own message - never skipped. `ScopeFilters.UNRESTRICTED` bypasses the guard\n * too, which is the deliberate way to write across scopes (system scope, an admin role).\n *\n * Not checked: an update that does not name the scope column (the row was already selected through\n * the scoped `where`), and raw statements that bypass the repository.\n *\n * @default 'reject'\n */\n mode?: TScopeWriteGuard;\n\n /**\n * `true` lets a restricted caller write `null` to a scope column, or leave it out on create: the\n * row has no owner and is shared. Without it, `null` is refused like any other value\n * outside the scope, even when the resolved scope has a `null` branch (that branch lets the caller\n * READ shared rows, a separate permission). Reads are scoped as before.\n *\n * @default false\n */\n sharedRows?: boolean;\n}\n\n/**\n * Row access for `@model` settings.access - resolved per query, so it can depend on the current\n * request (tenant, org, membership). Framework-internal escape hatches aside, nothing short of\n * removing this setting from the model turns scoping off.\n *\n * @example\n * ```typescript\n * import { model, ScopeWriteGuards } from '@venizia/ignis';\n * import { ModelFactory } from '@venizia/ignis-connectors/postgres';\n * import { pgTable, serial, text } from 'drizzle-orm/pg-core';\n *\n * const productTable = pgTable('Product', { id: serial('id').primaryKey(), merchantId: text('merchant_id') });\n *\n * export @model({ settings: { access: {\n * resolve: () => ({ merchantId: 'm-1' }),\n * write: { mode: ScopeWriteGuards.ASSIGN },\n * } } })\n * class Product extends ModelFactory.defineEntity({ table: productTable }) {}\n * ```\n */\nexport interface IModelAccessSettings {\n /** A model declares a resolver or a `through`, never both. */\n through?: never;\n\n /**\n * Returns the scope `where`; `ScopeFilters.UNRESTRICTED` to apply no scope for THIS call (an\n * internal operator, a caller the application has decided sees everything); or null/undefined\n * when this caller's scope cannot be determined at all.\n *\n * Receives `{ operation }`: the one concrete operation the call performs (`ScopeOperations.READ`,\n * `CREATE`, `UPDATE` or `DELETE`, never a group), so one function can answer a wide scope for a\n * read and a narrow one for a write. A read, and an included relation, pass `READ`; a create passes\n * `CREATE`; an update passes `UPDATE` for the payload check and for choosing the rows to update; a\n * delete, a soft delete included, passes `DELETE` for both; a restore passes `UPDATE`. A read with a\n * row `lock` passes `READ`. A resolver that takes no argument keeps working. An `or` over different\n * columns is still refused on a write, so return the narrow scope for a write operation.\n */\n resolve: (context: {\n operation: TScopeOperation;\n }) => TNullable<TWhere> | typeof ScopeFilters.UNRESTRICTED;\n\n /**\n * What `applyScopeFilter` does when `resolve()` returns null/undefined - no request context, no\n * tenant, a background job. With `deny`, an unresolved scope matches zero rows, never\n * every row. `allow` is an explicit, reviewed opt-out for migrations and background jobs, declared\n * per MODEL - it cannot express a per-USER bypass; use `ScopeFilters.UNRESTRICTED` for that.\n *\n * @default 'deny'\n */\n onMissing?: TScopeFilterMissingBehavior;\n\n /**\n * The property names the write guard checks. Optional: with none declared the guard checks every\n * column the resolved scope constrains. When declared, each name must exist on the model (checked\n * at boot), and a resolved scope that constrains any other column is refused as unverifiable.\n */\n columns?: string[];\n\n /** What a restricted caller may write to the scope columns. See {@link IModelAccessWriteSettings}. */\n write?: IModelAccessWriteSettings;\n}\n\n/**\n * Row access for a child model that has no scope columns of its own: it inherits the scope of the parent a `one`\n * relation points at. A parent that resolves no scope always denies the child: `onMissing` is not offered here, because\n * `'allow'` would show the child's rows of every tenant while the parent shows none.\n *\n * @example\n * ```typescript\n * import { model, ScopeThrough } from '@venizia/ignis';\n * import { ModelFactory, one } from '@venizia/ignis-connectors/postgres';\n * import { integer, pgTable, serial } from 'drizzle-orm/pg-core';\n * const productTable = pgTable('Product', { id: serial('id').primaryKey() });\n * const variantTable = pgTable('Variant', {\n * id: serial('id').primaryKey(),\n * productId: integer('product_id').references(() => productTable.id),\n * });\n * const VariantBase = ModelFactory.defineEntity({ table: variantTable, relations: () => ({ product: one(productTable) }) });\n * export @model({ settings: { access: { through: ScopeThrough.of({ entity: VariantBase, relation: 'product' }) } } })\n * class Variant extends VariantBase {}\n * ```\n *\n * @example\n * ```typescript\n * // A hand-written entity declares the same relation by hand.\n * import { ScopeThrough } from '@venizia/ignis';\n * import { BaseEntity, one, RelationDeclarations } from '@venizia/ignis-connectors/postgres';\n * import { integer, pgTable, serial } from 'drizzle-orm/pg-core';\n * const productTable = pgTable('Product', { id: serial('id').primaryKey() });\n * const variantTable = pgTable('Variant', { id: serial('id').primaryKey(), productId: integer('product_id').references(() => productTable.id) });\n * const relations = { product: one(productTable) };\n * class VariantBase extends BaseEntity<typeof variantTable> {\n * static override schema = variantTable;\n * static readonly relationDefinitions = relations;\n * static override relations = () => RelationDeclarations.toRelationConfigs({ relations });\n * }\n * const through = ScopeThrough.of({ entity: VariantBase, relation: 'product' });\n * ```\n */\nexport interface IModelAccessThroughSettings {\n through: ScopeThrough;\n onMissing?: never;\n resolve?: never;\n columns?: never;\n write?: never;\n}\n\n/** The two shapes of `@model` settings.access: a resolver, or a `through`. */\nexport type TModelAccessSettings = IModelAccessSettings | IModelAccessThroughSettings;\n\n/** What a query runs with when it names nothing (`@model` settings.query). */\nexport interface IModelQuerySettings {\n /** Default filter auto-applied to all repository operations. Bypassable via shouldSkipDefaultFilter. */\n filter?: TFilter;\n\n limit?: {\n /**\n * Row limit when a query omits `limit`. Must be a positive integer.\n *\n * @default DEFAULT_LIMIT\n */\n default?: number;\n\n /**\n * Largest `limit` a CALLER may ask for. Must be a positive integer.\n *\n * Policy, not capacity - the engine's own ceiling sits far above it. The number is chosen so\n * that reaching it means the caller is doing something unusual, and raising it is how a model\n * says so deliberately.\n *\n * @default DEFAULT_MAX_LIMIT\n */\n max?: number;\n };\n}\n\n/** Property groups of `@model` settings. */\nexport interface IModelProperties {\n /** Properties excluded from all query results at SQL level. */\n hidden?: string[];\n\n /**\n * Properties the server fills on every write, which a generated create or update body leaves out.\n *\n * @default AuditFields.SCHEME_SET\n */\n stamped?: ReadonlyArray<string> | ReadonlySet<string>;\n}\n\n/** Per-model settings passed to `@model` as `settings`. */\nexport interface IModelSettings {\n properties?: IModelProperties;\n\n /** Default filter and limits of a query: `filter`, `limit.default`, `limit.max`. */\n query?: IModelQuerySettings;\n\n /**\n * Row access: the scope ANDed into every read and write whose scope is expressible as a filter\n * clause, NOT removable by `shouldSkipDefaultFilter`, and the guard that holds writes to it.\n * Ownership resolved per row or through a polymorphic reference is NOT expressible here - that\n * check is still the application's to perform.\n *\n * Relational repositories only - a search-backed model (Typesense, Meilisearch) never reads\n * this setting, so mirroring a scoped entity into a search index needs its own query-time scope.\n */\n access?: TModelAccessSettings;\n\n /** Authorization settings for this model (principal name, etc.). */\n authorize?: IModelAuthorizeSettings;\n}\n\n/** Whether tooling that reads the model registry should migrate this model (`@model({ migration })`). */\nexport interface IModelMigrationSettings {\n /**\n * `false` marks the model as one a migration tool leaves alone. IGNIS generates no migrations itself.\n *\n * @default true\n */\n use?: boolean;\n}\n\n/** Metadata accepted by `@model`. */\nexport interface IModelMetadata extends IArtifactRegistrationOptions {\n /**\n * `ModelTypes.ENTITY` is the only value.\n *\n * @default ModelTypes.ENTITY\n */\n type?: TModelType;\n tableName?: string;\n\n /** Migration marker for consumer tooling that reads the public registry. */\n migration?: IModelMigrationSettings;\n\n settings?: IModelSettings;\n}\n\n/** Static members an entity class carries: its `schema` and its `relations` (value or resolver). */\nexport interface IEntityStatics {\n schema?: unknown;\n relations?: TValueOrResolver<Array<unknown>>;\n}\n\n/** A model class together with its entity statics. */\nexport type TModelClass<Model extends AbstractEntity = AbstractEntity> = TClass<Model> &\n IEntityStatics;\n\n/** Decorator target for model classes (supports both strongly typed and ClassDecorator patterns). */\nexport type TDecoratorModelTarget<Model extends AbstractEntity = AbstractEntity> =\n | TModelClass<Model>\n | (Function & IEntityStatics);\n\n/** One model as stored in the metadata registry: class, metadata and schema, with lazily resolved relations. */\nexport interface IModelRegistryEntry<Model extends AbstractEntity = AbstractEntity> {\n target: TValueOrResolver<TClass<Model>>;\n metadata: IModelMetadata;\n schema: unknown;\n\n /** Lazy resolver to avoid circular deps. Resolved when DataSource builds schema. */\n relationsResolver?: TValueOrResolver<Array<unknown>>;\n\n /** Cache populated on first buildSchema() call. */\n _builtRelations?: unknown;\n}\n"]}
@@ -26,7 +26,7 @@ export { NotSupportedUtility } from './utilities/not-supported.utility.js';
26
26
  export type { TCount, TDataRange, TDataWithRange } from './base/repositories/common/types/results.js';
27
27
  export type { IDataSource } from './base/datasources/common/types.js';
28
28
  export { AbstractEntity } from './base/models/base.js';
29
- export { SchemaTypes } from './base/models/common/constants.js';
29
+ export { AuditFields, SchemaTypes } from './base/models/common/constants.js';
30
30
  export type { TIdSchemaType, TSchemaType } from './base/models/common/index.js';
31
31
  export type { TByIdFilter, TFields, TFilter, TInclusion, TRow, TSelectedRow, TWhere, } from '@venizia/ignis-filter';
32
32
  export { RequestFilterParts } from './base/repositories/common/request-filter-guard.js';
@@ -27,7 +27,7 @@ export { NotSupportedUtility } from './utilities/not-supported.utility.js';
27
27
  // `IRepository` names an entity, so a consumer implementing the contract needs the base to extend.
28
28
  // Engine-neutral like the datasource: a name, `getSchema({ type })`, and an id type.
29
29
  export { AbstractEntity } from './base/models/base.js';
30
- export { SchemaTypes } from './base/models/common/constants.js';
30
+ export { AuditFields, SchemaTypes } from './base/models/common/constants.js';
31
31
  // What a repository on any transport needs to refuse a request filter that names a hidden property.
32
32
  export { RequestFilterParts } from './base/repositories/common/request-filter-guard.js';
33
33
  //# sourceMappingURL=repository.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"repository.js","sourceRoot":"","sources":["../../src/repository.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAYjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAE5E,gGAAgG;AAChG,yCAAyC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,4CAA4C,CAAC;AAChF,OAAO,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAG5E,mGAAmG;AACnG,mEAAmE;AACnE,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,yBAAyB,EACzB,eAAe,GAChB,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAKxE,mGAAmG;AACnG,qFAAqF;AACrF,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAc7D,oGAAoG;AACpG,OAAO,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC","sourcesContent":["/**\n * The persistence contract, and nothing about how a row is served or validated.\n *\n * A repository talks to a datasource. `AbstractDataSource` is engine-neutral - its only required\n * member is `configure()` - so \"an HTTP request to another server\" is a datasource in the same sense\n * Drizzle-over-Postgres is one: same role, different transport. This entry exists so a consumer can\n * implement that without taking the OpenAPI layer, which `base/repositories` reaches through\n * `query-schemas` and `result-schemas`.\n *\n * Both halves already speak `@venizia/ignis-filter`, so a consumer on another transport shares the\n * query vocabulary rather than translating into one.\n *\n * Weight is a contract, checked by `src/__tests__/bundle/browser-weight.test.ts`.\n */\n\nexport { AbstractRepository } from '@/base/repositories/core/abstract';\nexport { AbstractDataSource } from '@/base/datasources/abstract';\n\nexport type {\n ICreatableRepository,\n ICrudRepository,\n IDeletableRepository,\n IPersistableRepository,\n IReadableRepository,\n IRepository,\n IUpdatableRepository,\n} from '@/base/repositories/common/types/contracts';\n\nexport { DataRangeUtility } from '@/base/repositories/common/types/results';\n\n// How a client reads what an IGNIS server answers - shared by the http connector and any client\n// that reads the same server without it.\nexport { HttpResponseReader } from '@/base/repositories/common/response-reader';\nexport { HttpExtraRequest } from '@/base/repositories/common/extra-request';\nexport type { TExtraRequest, TExtraResult } from '@/base/repositories/common/extra-request';\n\n// What a repository on any transport raises and bounds itself by - the constants, the error codes,\n// and the helper an engine that lacks an operation throws through.\nexport {\n DEFAULT_LIMIT,\n DEFAULT_MAX_LIMIT,\n RepositoryOperationScopes,\n RepositoryTypes,\n} from '@/base/repositories/common/constants';\nexport type { TRepositoryType } from '@/base/repositories/common/constants';\nexport { CoreErrorCodes, SearchErrorCodes } from '@/common/error-codes';\nexport { NotSupportedUtility } from '@/utilities/not-supported.utility';\nexport type { TCount, TDataRange, TDataWithRange } from '@/base/repositories/common/types/results';\n\nexport type { IDataSource } from '@/base/datasources/common/types';\n\n// `IRepository` names an entity, so a consumer implementing the contract needs the base to extend.\n// Engine-neutral like the datasource: a name, `getSchema({ type })`, and an id type.\nexport { AbstractEntity } from '@/base/models/base';\nexport { SchemaTypes } from '@/base/models/common/constants';\nexport type { TIdSchemaType, TSchemaType } from '@/base/models/common';\n\n// The query vocabulary both transports share.\nexport type {\n TByIdFilter,\n TFields,\n TFilter,\n TInclusion,\n TRow,\n TSelectedRow,\n TWhere,\n} from '@venizia/ignis-filter';\n\n// What a repository on any transport needs to refuse a request filter that names a hidden property.\nexport { RequestFilterParts } from '@/base/repositories/common/request-filter-guard';\nexport type {\n IRequestFilterJudge,\n IRequestFilterShape,\n TRequestFilterPart,\n TRequestFilterPiece,\n} from '@/base/repositories/common/request-filter-guard';\n"]}
1
+ {"version":3,"file":"repository.js","sourceRoot":"","sources":["../../src/repository.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAYjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAE5E,gGAAgG;AAChG,yCAAyC;AACzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,4CAA4C,CAAC;AAChF,OAAO,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AAG5E,mGAAmG;AACnG,mEAAmE;AACnE,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,yBAAyB,EACzB,eAAe,GAChB,MAAM,sCAAsC,CAAC;AAE9C,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAKxE,mGAAmG;AACnG,qFAAqF;AACrF,OAAO,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACpD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;AAc1E,oGAAoG;AACpG,OAAO,EAAE,kBAAkB,EAAE,MAAM,iDAAiD,CAAC","sourcesContent":["/**\n * The persistence contract, and nothing about how a row is served or validated.\n *\n * A repository talks to a datasource. `AbstractDataSource` is engine-neutral - its only required\n * member is `configure()` - so \"an HTTP request to another server\" is a datasource in the same sense\n * Drizzle-over-Postgres is one: same role, different transport. This entry exists so a consumer can\n * implement that without taking the OpenAPI layer, which `base/repositories` reaches through\n * `query-schemas` and `result-schemas`.\n *\n * Both halves already speak `@venizia/ignis-filter`, so a consumer on another transport shares the\n * query vocabulary rather than translating into one.\n *\n * Weight is a contract, checked by `src/__tests__/bundle/browser-weight.test.ts`.\n */\n\nexport { AbstractRepository } from '@/base/repositories/core/abstract';\nexport { AbstractDataSource } from '@/base/datasources/abstract';\n\nexport type {\n ICreatableRepository,\n ICrudRepository,\n IDeletableRepository,\n IPersistableRepository,\n IReadableRepository,\n IRepository,\n IUpdatableRepository,\n} from '@/base/repositories/common/types/contracts';\n\nexport { DataRangeUtility } from '@/base/repositories/common/types/results';\n\n// How a client reads what an IGNIS server answers - shared by the http connector and any client\n// that reads the same server without it.\nexport { HttpResponseReader } from '@/base/repositories/common/response-reader';\nexport { HttpExtraRequest } from '@/base/repositories/common/extra-request';\nexport type { TExtraRequest, TExtraResult } from '@/base/repositories/common/extra-request';\n\n// What a repository on any transport raises and bounds itself by - the constants, the error codes,\n// and the helper an engine that lacks an operation throws through.\nexport {\n DEFAULT_LIMIT,\n DEFAULT_MAX_LIMIT,\n RepositoryOperationScopes,\n RepositoryTypes,\n} from '@/base/repositories/common/constants';\nexport type { TRepositoryType } from '@/base/repositories/common/constants';\nexport { CoreErrorCodes, SearchErrorCodes } from '@/common/error-codes';\nexport { NotSupportedUtility } from '@/utilities/not-supported.utility';\nexport type { TCount, TDataRange, TDataWithRange } from '@/base/repositories/common/types/results';\n\nexport type { IDataSource } from '@/base/datasources/common/types';\n\n// `IRepository` names an entity, so a consumer implementing the contract needs the base to extend.\n// Engine-neutral like the datasource: a name, `getSchema({ type })`, and an id type.\nexport { AbstractEntity } from '@/base/models/base';\nexport { AuditFields, SchemaTypes } from '@/base/models/common/constants';\nexport type { TIdSchemaType, TSchemaType } from '@/base/models/common';\n\n// The query vocabulary both transports share.\nexport type {\n TByIdFilter,\n TFields,\n TFilter,\n TInclusion,\n TRow,\n TSelectedRow,\n TWhere,\n} from '@venizia/ignis-filter';\n\n// What a repository on any transport needs to refuse a request filter that names a hidden property.\nexport { RequestFilterParts } from '@/base/repositories/common/request-filter-guard';\nexport type {\n IRequestFilterJudge,\n IRequestFilterShape,\n TRequestFilterPart,\n TRequestFilterPiece,\n} from '@/base/repositories/common/request-filter-guard';\n"]}
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The status codes, and nothing else: `Statuses` and `CommonStatuses` import nothing, so a browser bundle
3
+ * that needs a status constant takes this entry instead of the server kernel.
4
+ *
5
+ * Weight is a contract, checked by `src/__tests__/bundle/browser-weight.test.ts`.
6
+ */
7
+ export { CommonStatuses, Statuses } from './common/statuses/common.js';
8
+ //# sourceMappingURL=statuses.d.ts.map
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The status codes, and nothing else: `Statuses` and `CommonStatuses` import nothing, so a browser bundle
3
+ * that needs a status constant takes this entry instead of the server kernel.
4
+ *
5
+ * Weight is a contract, checked by `src/__tests__/bundle/browser-weight.test.ts`.
6
+ */
7
+ export { CommonStatuses, Statuses } from './common/statuses/common.js';
8
+ //# sourceMappingURL=statuses.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"statuses.js","sourceRoot":"","sources":["../../src/statuses.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC","sourcesContent":["/**\n * The status codes, and nothing else: `Statuses` and `CommonStatuses` import nothing, so a browser bundle\n * that needs a status constant takes this entry instead of the server kernel.\n *\n * Weight is a contract, checked by `src/__tests__/bundle/browser-weight.test.ts`.\n */\n\nexport { CommonStatuses, Statuses } from '@/common/statuses/common';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis-kernel",
3
- "version": "0.4.8-6",
3
+ "version": "0.4.8-7",
4
4
  "description": "Browser-pure kernel of the IGNIS framework: dependency injection, lifecycle, REST controllers, repository and datasource abstractions, and the authentication and authorization seams. No node builtin and no server-only peer, so the same kernel serves a Bun server and a browser Worker.",
5
5
  "keywords": [
6
6
  "authentication",
@@ -60,6 +60,10 @@
60
60
  "types": "./dist/esm/repository.d.ts",
61
61
  "default": "./dist/esm/repository.js"
62
62
  },
63
+ "./statuses": {
64
+ "types": "./dist/esm/statuses.d.ts",
65
+ "default": "./dist/esm/statuses.js"
66
+ },
63
67
  "./package.json": "./package.json"
64
68
  },
65
69
  "publishConfig": {
@@ -70,13 +74,13 @@
70
74
  },
71
75
  "dependencies": {
72
76
  "@venizia/ignis-filter": "0.4.7-4",
73
- "@venizia/ignis-helpers": "0.4.8-6",
77
+ "@venizia/ignis-helpers": "0.4.8-7",
74
78
  "@venizia/ignis-inversion": "0.4.7-3",
75
79
  "reflect-metadata": "^0.2.2"
76
80
  },
77
81
  "devDependencies": {
78
82
  "@types/bun": "^1.4.3",
79
- "@venizia/dev-configs": "0.4.8-3",
83
+ "@venizia/dev-configs": "0.4.8-4",
80
84
  "casbin": "^5.51.1",
81
85
  "eslint": "^10.13.0",
82
86
  "oxlint": "1.89.0",