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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/esm/base/applications/common/types/application.d.ts +3 -4
  2. package/dist/esm/base/applications/common/types/application.js.map +1 -1
  3. package/dist/esm/base/applications/rest.d.ts +13 -7
  4. package/dist/esm/base/applications/rest.js +52 -7
  5. package/dist/esm/base/applications/rest.js.map +1 -1
  6. package/dist/esm/base/applications/router-factory.d.ts +27 -0
  7. package/dist/esm/base/applications/router-factory.js +28 -0
  8. package/dist/esm/base/applications/router-factory.js.map +1 -0
  9. package/dist/esm/base/auth/authenticate/common/types/jwt.d.ts +6 -4
  10. package/dist/esm/base/auth/authenticate/common/types/jwt.js.map +1 -1
  11. package/dist/esm/base/auth/authenticate/common/types/service.d.ts +1 -1
  12. package/dist/esm/base/auth/authenticate/common/types/service.js.map +1 -1
  13. package/dist/esm/base/controllers/factory/crud/readable.js +2 -1
  14. package/dist/esm/base/controllers/factory/crud/readable.js.map +1 -1
  15. package/dist/esm/base/controllers/rest/abstract.js +5 -0
  16. package/dist/esm/base/controllers/rest/abstract.js.map +1 -1
  17. package/dist/esm/base/datasources/abstract.d.ts +69 -2
  18. package/dist/esm/base/datasources/abstract.js +186 -1
  19. package/dist/esm/base/datasources/abstract.js.map +1 -1
  20. package/dist/esm/base/datasources/common/types.d.ts +60 -1
  21. package/dist/esm/base/datasources/common/types.js +14 -0
  22. package/dist/esm/base/datasources/common/types.js.map +1 -1
  23. package/dist/esm/base/datasources/opening-handles.d.ts +8 -0
  24. package/dist/esm/base/datasources/opening-handles.js +8 -0
  25. package/dist/esm/base/datasources/opening-handles.js.map +1 -0
  26. package/dist/esm/base/metadata/persistents.js +15 -1
  27. package/dist/esm/base/metadata/persistents.js.map +1 -1
  28. package/dist/esm/base/middlewares/app-error/app-error.middleware.js +12 -1
  29. package/dist/esm/base/middlewares/app-error/app-error.middleware.js.map +1 -1
  30. package/dist/esm/base/middlewares/app-error/common/types.d.ts +10 -8
  31. package/dist/esm/base/middlewares/app-error/common/types.js.map +1 -1
  32. package/dist/esm/base/middlewares/app-error/database.handler.js +14 -14
  33. package/dist/esm/base/middlewares/app-error/database.handler.js.map +1 -1
  34. package/dist/esm/base/middlewares/app-error/index.d.ts +2 -0
  35. package/dist/esm/base/middlewares/app-error/index.js +1 -0
  36. package/dist/esm/base/middlewares/app-error/index.js.map +1 -1
  37. package/dist/esm/base/middlewares/app-error/postgres-errors.d.ts +20 -0
  38. package/dist/esm/base/middlewares/app-error/postgres-errors.js +74 -0
  39. package/dist/esm/base/middlewares/app-error/postgres-errors.js.map +1 -0
  40. package/dist/esm/base/repositories/common/request-filter-guard.d.ts +52 -2
  41. package/dist/esm/base/repositories/common/request-filter-guard.js +110 -25
  42. package/dist/esm/base/repositories/common/request-filter-guard.js.map +1 -1
  43. package/dist/esm/helpers/inversion/common/types/persistence.d.ts +3 -1
  44. package/dist/esm/helpers/inversion/common/types/persistence.js.map +1 -1
  45. package/dist/esm/repository.d.ts +2 -0
  46. package/dist/esm/repository.js +2 -0
  47. package/dist/esm/repository.js.map +1 -1
  48. package/package.json +5 -5
@@ -91,7 +91,7 @@ export interface IServiceAuthOptions<E extends Env = Env> {
91
91
  cacheMaxAgeMs?: number;
92
92
  /** @default 30_000 */
93
93
  cooldownMs?: number;
94
- /** Host names that may serve a caller's key set over `http:`. Unset means `https:` or loopback only. */
94
+ /** Exact hosts (name, IP or bracketed IPv6, each with an optional `:port`) that may serve a caller's key set over `http:`. Unset means `https:` or loopback only. */
95
95
  hosts?: IJWKSHosts;
96
96
  };
97
97
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/service.ts"],"names":[],"mappings":"","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport type { TNullable, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { Env } from 'hono';\nimport type { JWTPayload } from 'jose';\nimport type { TJWKSKeyDriver, TJWKSKeyFormat } from '../constants';\nimport type { IJWKSHosts } from './jwt';\nimport type { IAuthUser } from './strategy';\n\n/**\n * The request binding, following RFC 9449's `htm`/`htu`. A captured assertion cannot be replayed\n * against a different method or path.\n *\n * `htu` is the percent-ENCODED pathname on both ends. Compare it against\n * `new URL(context.req.url).pathname`, never `context.req.path` - Hono hands that one back DECODED,\n * so any route carrying a space or a non-ASCII slug would never match what the caller signed.\n */\nexport interface IServiceAssertionClaims extends JWTPayload {\n htm: string;\n htu: string;\n}\n\n/**\n * One entry in the caller allowlist: the JWKS url, or that url plus settings for this caller alone.\n */\nexport type TServiceCallerEntry =\n | string\n | {\n jwksUrl: string;\n /** Widens the accepted age for THIS caller only. Falls back to the service-wide setting. */\n acceptMaxAgeSeconds?: number;\n };\n\n/** Service-to-service authentication: an Ed25519 assertion per request, verified against the caller's JWKS. */\nexport interface IServiceAuthOptions<E extends Env = Env> {\n /** What this service calls itself: the `iss` it stamps, and the `aud` it demands. */\n name: string;\n\n /**\n * Present only on a service that CALLS OUT. Absent means verify-only, and no certs route is\n * mounted - which is the common case, since most services are called and never call.\n */\n keys?: {\n driver: TJWKSKeyDriver;\n format: TJWKSKeyFormat;\n /** PEM or JWK by `format`; content for the `text` driver, a path for `file`. */\n private: string;\n public: string;\n kid?: string;\n };\n\n /**\n * Caller name to its JWKS url. THIS IS ALSO THE ALLOWLIST - a name absent from the map cannot\n * call, and an empty map correctly allows nobody.\n *\n * The bare-string form is the common case. The object form exists to widen the accepted age for\n * ONE caller: a nightly batch may legitimately need more slack than an interactive service, and\n * granting it per caller keeps the concession named and visible in config.\n */\n callers?: Record<string, TServiceCallerEntry>;\n\n /** Where the certs route is mounted. */\n rest?: {\n /** @default '/svc-certs' */\n path: string;\n };\n\n /**\n * How long the assertions this service MINTS stay valid. Only meaningful where `keys` is set.\n *\n * @default 60\n */\n signLifetimeSeconds?: number;\n\n /**\n * The oldest assertion this service ACCEPTS, measured from `iat`.\n *\n * Deliberately separate from `signLifetimeSeconds`, and deliberately not requestable by the\n * caller. The caller already controls `exp` - it signs the token - so this is the only bound that\n * survives a compromised caller. A per-caller override belongs in {@link callers}, never in the\n * assertion.\n *\n * Composes with `clockToleranceSeconds`: the real acceptance window is the sum of the two.\n *\n * @default 60\n */\n acceptMaxAgeSeconds?: number;\n\n /**\n * Clock skew allowance. A SECURITY knob, not an operational one.\n *\n * Its job is the future case: two machines never agree to the second, and without it a caller one\n * second ahead is refused outright. But it also widens the REPLAY window second for second - a\n * callee accepting an `iat` 5s in its own future keeps accepting that token for the rest of the\n * window too. Measured at the defaults: 65s accepted on our clock, 70s of wall-clock life for a\n * capture minted by a caller running the full tolerance fast.\n *\n * @default 5\n */\n clockToleranceSeconds?: number;\n\n jwks?: {\n /** @default 600_000 */\n cacheMaxAgeMs?: number;\n\n /** @default 30_000 */\n cooldownMs?: number;\n\n /** Host names that may serve a caller's key set over `http:`. Unset means `https:` or loopback only. */\n hosts?: IJWKSHosts;\n };\n\n /**\n * WHO a verified assertion acts as. The framework has already proven the caller; this only maps a\n * caller name onto an application principal. Return `null` to refuse a caller the allowlist\n * admits but the application does not recognise.\n */\n resolvePrincipal: (opts: {\n issuer: string;\n context: TContext<E, string>;\n }) => ValueOrPromise<TNullable<IAuthUser>>;\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["../../../../../../../src/base/auth/authenticate/common/types/service.ts"],"names":[],"mappings":"","sourcesContent":["import type { TContext } from '@/base/controllers/common/types';\nimport type { TNullable, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport type { Env } from 'hono';\nimport type { JWTPayload } from 'jose';\nimport type { TJWKSKeyDriver, TJWKSKeyFormat } from '../constants';\nimport type { IJWKSHosts } from './jwt';\nimport type { IAuthUser } from './strategy';\n\n/**\n * The request binding, following RFC 9449's `htm`/`htu`. A captured assertion cannot be replayed\n * against a different method or path.\n *\n * `htu` is the percent-ENCODED pathname on both ends. Compare it against\n * `new URL(context.req.url).pathname`, never `context.req.path` - Hono hands that one back DECODED,\n * so any route carrying a space or a non-ASCII slug would never match what the caller signed.\n */\nexport interface IServiceAssertionClaims extends JWTPayload {\n htm: string;\n htu: string;\n}\n\n/**\n * One entry in the caller allowlist: the JWKS url, or that url plus settings for this caller alone.\n */\nexport type TServiceCallerEntry =\n | string\n | {\n jwksUrl: string;\n /** Widens the accepted age for THIS caller only. Falls back to the service-wide setting. */\n acceptMaxAgeSeconds?: number;\n };\n\n/** Service-to-service authentication: an Ed25519 assertion per request, verified against the caller's JWKS. */\nexport interface IServiceAuthOptions<E extends Env = Env> {\n /** What this service calls itself: the `iss` it stamps, and the `aud` it demands. */\n name: string;\n\n /**\n * Present only on a service that CALLS OUT. Absent means verify-only, and no certs route is\n * mounted - which is the common case, since most services are called and never call.\n */\n keys?: {\n driver: TJWKSKeyDriver;\n format: TJWKSKeyFormat;\n /** PEM or JWK by `format`; content for the `text` driver, a path for `file`. */\n private: string;\n public: string;\n kid?: string;\n };\n\n /**\n * Caller name to its JWKS url. THIS IS ALSO THE ALLOWLIST - a name absent from the map cannot\n * call, and an empty map correctly allows nobody.\n *\n * The bare-string form is the common case. The object form exists to widen the accepted age for\n * ONE caller: a nightly batch may legitimately need more slack than an interactive service, and\n * granting it per caller keeps the concession named and visible in config.\n */\n callers?: Record<string, TServiceCallerEntry>;\n\n /** Where the certs route is mounted. */\n rest?: {\n /** @default '/svc-certs' */\n path: string;\n };\n\n /**\n * How long the assertions this service MINTS stay valid. Only meaningful where `keys` is set.\n *\n * @default 60\n */\n signLifetimeSeconds?: number;\n\n /**\n * The oldest assertion this service ACCEPTS, measured from `iat`.\n *\n * Deliberately separate from `signLifetimeSeconds`, and deliberately not requestable by the\n * caller. The caller already controls `exp` - it signs the token - so this is the only bound that\n * survives a compromised caller. A per-caller override belongs in {@link callers}, never in the\n * assertion.\n *\n * Composes with `clockToleranceSeconds`: the real acceptance window is the sum of the two.\n *\n * @default 60\n */\n acceptMaxAgeSeconds?: number;\n\n /**\n * Clock skew allowance. A SECURITY knob, not an operational one.\n *\n * Its job is the future case: two machines never agree to the second, and without it a caller one\n * second ahead is refused outright. But it also widens the REPLAY window second for second - a\n * callee accepting an `iat` 5s in its own future keeps accepting that token for the rest of the\n * window too. Measured at the defaults: 65s accepted on our clock, 70s of wall-clock life for a\n * capture minted by a caller running the full tolerance fast.\n *\n * @default 5\n */\n clockToleranceSeconds?: number;\n\n jwks?: {\n /** @default 600_000 */\n cacheMaxAgeMs?: number;\n\n /** @default 30_000 */\n cooldownMs?: number;\n\n /** Exact hosts (name, IP or bracketed IPv6, each with an optional `:port`) that may serve a caller's key set over `http:`. Unset means `https:` or loopback only. */\n hosts?: IJWKSHosts;\n };\n\n /**\n * WHO a verified assertion acts as. The framework has already proven the caller; this only maps a\n * caller name onto an application principal. Return `null` to refuse a caller the allowlist\n * admits but the application does not recognise.\n */\n resolvePrincipal: (opts: {\n issuer: string;\n context: TContext<E, string>;\n }) => ValueOrPromise<TNullable<IAuthUser>>;\n}\n"]}
@@ -69,7 +69,8 @@ export class ReadableCrudController extends AbstractCrudController {
69
69
  const { context } = opts;
70
70
  const { id } = context.req.valid('param');
71
71
  const { filter } = context.req.valid('query');
72
- this.assertRequestFilter({ filter });
72
+ // The read is by id, so a `where` the client sent is never read; the check reads only what the query reads.
73
+ this.assertRequestFilter({ filter: filter && { ...filter, where: undefined } });
73
74
  const baseWhere = await this.getBaseWhere({ context });
74
75
  // `repository.findById` takes no where, so a scoped read goes through `findOne` - the same
75
76
  // substrate every family's findById delegates to - and answers null on an out-of-scope id.
@@ -1 +1 @@
1
- {"version":3,"file":"readable.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/factory/crud/readable.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AAGrD,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,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AAU,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC,CAAC;gBAEvE,OAAO,IAAI,CAAC,OAAO,CAAc;oBAC/B,OAAO;oBACP,MAAM,EAAE,eAAe,CAAC,MAAM;oBAC9B,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE;iBACjD,CAAC,CAAC;YACL,CAAC;SACF,CAAC,CAAC;QAEH,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpD,CAAC;CACF","sourcesContent":["import type { AbstractEntity, IdType } from '@/base/models';\nimport type { TFilter, TWhere } from '@venizia/ignis-filter';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport type { TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common';\nimport { AbstractCrudController } from './abstract';\nimport { ResponseFormats } from '../../common';\n\n/** The one combination point of a base where and a request where; without a request side there is no `and` wrapper. */\nconst withBaseWhere = <TDataObject extends object>(opts: {\n baseWhere: TWhere<TDataObject>;\n where?: TWhere<TDataObject>;\n}): TWhere<TDataObject> => {\n const { baseWhere, where } = opts;\n\n if (!where) {\n return baseWhere;\n }\n\n // `Pick` resolves the one key: a literal cannot be checked against `TWhere` over an unresolved type parameter.\n const scoped: Pick<TWhere<TDataObject>, 'and'> = { and: [baseWhere, where] };\n\n return scoped;\n};\n\n/** `id` is the primary key every entity family reads by; built at the default `TWhere` for the same unresolved-parameter reason. */\nconst whereById = <TDataObject extends object>(opts: { id: IdType }): TWhere<TDataObject> => {\n const where: TWhere = { id: opts.id };\n\n return where;\n};\n\n/** Read tier: count / find / findById / findOne. Read-only controllers can extend this directly. */\nexport abstract class ReadableCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\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> extends AbstractCrudController<\n TEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n> {\n /** Narrows EVERY read of this controller - override it to scope rows to a tenant, an owner or a status. Public because a generated controller's declaration cannot carry a protected member (TS4094). */\n async getBaseWhere(_opts: {\n context: TRouteContext<RouteEnv>;\n }): Promise<TWhere<TDataObject> | undefined> {\n return undefined;\n }\n\n /** GET /count */\n async count(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { where } = context.req.valid<{ where: TWhere<TDataObject> }>('query');\n\n // What the client sent, before the base where joins it: a hidden field cannot be asked about.\n this.assertRequestFilter({ filter: { where } });\n\n const baseWhere = await this.getBaseWhere({ context });\n const scopedWhere = baseWhere ? withBaseWhere({ baseWhere, where }) : where;\n\n const rs = await this.measure({\n scope: 'count',\n args: { where: scopedWhere },\n task: () => this.repository.count({ where: scopedWhere }),\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET / - paginated list with a Content-Range header. */\n async find(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { filter = {} } = context.req.valid<{ filter?: TFilter<TDataObject> }>('query');\n\n this.assertRequestFilter({ filter });\n\n const baseWhere = await this.getBaseWhere({ context });\n const scopedFilter = baseWhere\n ? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }\n : filter;\n\n const rs = await this.measure({\n scope: 'find',\n args: scopedFilter,\n task: async () => {\n const { data, range } = await this.repository.find({\n filter: scopedFilter,\n options: { shouldQueryRange: true },\n });\n\n return this.respond<Array<TDataObject>>({\n context,\n format: ResponseFormats.ARRAY,\n payload: { count: data.length, data },\n range,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET /:id */\n async findById(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { id } = context.req.valid<{ id: IdType }>('param');\n const { filter } = context.req.valid<{ filter?: Omit<TFilter<TDataObject>, 'where'> }>('query');\n\n this.assertRequestFilter({ filter });\n\n const baseWhere = await this.getBaseWhere({ context });\n\n // `repository.findById` takes no where, so a scoped read goes through `findOne` - the same\n // substrate every family's findById delegates to - and answers null on an out-of-scope id.\n const scopedWhere = baseWhere\n ? withBaseWhere({ baseWhere, where: whereById({ id }) })\n : undefined;\n\n const rs = await this.measure({\n scope: 'findById',\n args: filter,\n task: async () => {\n const lookup = scopedWhere\n ? this.repository.findOne({ filter: { ...filter, where: scopedWhere } })\n : this.repository.findById({ id, filter });\n const record = await lookup;\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload: { count: record ? 1 : 0, data: record },\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET /find-one */\n async findOne(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { filter = {} } = context.req.valid<{ filter?: TFilter<TDataObject> }>('query');\n\n this.assertRequestFilter({ filter });\n\n const baseWhere = await this.getBaseWhere({ context });\n const scopedFilter = baseWhere\n ? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }\n : filter;\n\n const rs = await this.measure({\n scope: 'findOne',\n args: scopedFilter,\n task: async () => {\n const record = await this.repository.findOne({ filter: scopedFilter });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload: { count: record ? 1 : 0, data: record },\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n"]}
1
+ {"version":3,"file":"readable.js","sourceRoot":"","sources":["../../../../../../src/base/controllers/factory/crud/readable.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,IAAI,EAAE,MAAM,+BA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AAC;QAEX,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC;YAC5B,KAAK,EAAE,SAAS;YAChB,IAAI,EAAE,YAAY;YAClB,IAAI,EAAE,KAAK,IAAI,EAAE;gBACf,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,CAAC,CAAC;gBAEvE,OAAO,IAAI,CAAC,OAAO,CAAc;oBAC/B,OAAO;oBACP,MAAM,EAAE,eAAe,CAAC,MAAM;oBAC9B,OAAO,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE;iBACjD,CAAC,CAAC;YACL,CAAC;SACF,CAAC,CAAC;QAEH,OAAO,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACpD,CAAC;CACF","sourcesContent":["import type { AbstractEntity, IdType } from '@/base/models';\nimport type { TFilter, TWhere } from '@venizia/ignis-filter';\nimport type { TAnyObjectSchema } from '@/base/controllers/common/schema-builders';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport type { Env, Schema } from 'hono';\nimport type { TEntityDataObject, TEntityPersistObject, TRouteContext } from '../../common';\nimport { AbstractCrudController } from './abstract';\nimport { ResponseFormats } from '../../common';\n\n/** The one combination point of a base where and a request where; without a request side there is no `and` wrapper. */\nconst withBaseWhere = <TDataObject extends object>(opts: {\n baseWhere: TWhere<TDataObject>;\n where?: TWhere<TDataObject>;\n}): TWhere<TDataObject> => {\n const { baseWhere, where } = opts;\n\n if (!where) {\n return baseWhere;\n }\n\n // `Pick` resolves the one key: a literal cannot be checked against `TWhere` over an unresolved type parameter.\n const scoped: Pick<TWhere<TDataObject>, 'and'> = { and: [baseWhere, where] };\n\n return scoped;\n};\n\n/** `id` is the primary key every entity family reads by; built at the default `TWhere` for the same unresolved-parameter reason. */\nconst whereById = <TDataObject extends object>(opts: { id: IdType }): TWhere<TDataObject> => {\n const where: TWhere = { id: opts.id };\n\n return where;\n};\n\n/** Read tier: count / find / findById / findOne. Read-only controllers can extend this directly. */\nexport abstract class ReadableCrudController<\n TEntity extends AbstractEntity<TAnyObjectSchema> = AbstractEntity<TAnyObjectSchema>,\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> extends AbstractCrudController<\n TEntity,\n RouteEnv,\n RouteSchema,\n BasePath,\n ConfigurableOptions,\n TDataObject,\n TPersistObject\n> {\n /** Narrows EVERY read of this controller - override it to scope rows to a tenant, an owner or a status. Public because a generated controller's declaration cannot carry a protected member (TS4094). */\n async getBaseWhere(_opts: {\n context: TRouteContext<RouteEnv>;\n }): Promise<TWhere<TDataObject> | undefined> {\n return undefined;\n }\n\n /** GET /count */\n async count(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { where } = context.req.valid<{ where: TWhere<TDataObject> }>('query');\n\n // What the client sent, before the base where joins it: a hidden field cannot be asked about.\n this.assertRequestFilter({ filter: { where } });\n\n const baseWhere = await this.getBaseWhere({ context });\n const scopedWhere = baseWhere ? withBaseWhere({ baseWhere, where }) : where;\n\n const rs = await this.measure({\n scope: 'count',\n args: { where: scopedWhere },\n task: () => this.repository.count({ where: scopedWhere }),\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET / - paginated list with a Content-Range header. */\n async find(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { filter = {} } = context.req.valid<{ filter?: TFilter<TDataObject> }>('query');\n\n this.assertRequestFilter({ filter });\n\n const baseWhere = await this.getBaseWhere({ context });\n const scopedFilter = baseWhere\n ? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }\n : filter;\n\n const rs = await this.measure({\n scope: 'find',\n args: scopedFilter,\n task: async () => {\n const { data, range } = await this.repository.find({\n filter: scopedFilter,\n options: { shouldQueryRange: true },\n });\n\n return this.respond<Array<TDataObject>>({\n context,\n format: ResponseFormats.ARRAY,\n payload: { count: data.length, data },\n range,\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET /:id */\n async findById(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { id } = context.req.valid<{ id: IdType }>('param');\n const { filter } = context.req.valid<{ filter?: Omit<TFilter<TDataObject>, 'where'> }>('query');\n\n // The read is by id, so a `where` the client sent is never read; the check reads only what the query reads.\n this.assertRequestFilter({ filter: filter && { ...filter, where: undefined } });\n\n const baseWhere = await this.getBaseWhere({ context });\n\n // `repository.findById` takes no where, so a scoped read goes through `findOne` - the same\n // substrate every family's findById delegates to - and answers null on an out-of-scope id.\n const scopedWhere = baseWhere\n ? withBaseWhere({ baseWhere, where: whereById({ id }) })\n : undefined;\n\n const rs = await this.measure({\n scope: 'findById',\n args: filter,\n task: async () => {\n const lookup = scopedWhere\n ? this.repository.findOne({ filter: { ...filter, where: scopedWhere } })\n : this.repository.findById({ id, filter });\n const record = await lookup;\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload: { count: record ? 1 : 0, data: record },\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n\n /** GET /find-one */\n async findOne(opts: { context: TRouteContext<RouteEnv> }) {\n const { context } = opts;\n const { filter = {} } = context.req.valid<{ filter?: TFilter<TDataObject> }>('query');\n\n this.assertRequestFilter({ filter });\n\n const baseWhere = await this.getBaseWhere({ context });\n const scopedFilter = baseWhere\n ? { ...filter, where: withBaseWhere({ baseWhere, where: filter.where }) }\n : filter;\n\n const rs = await this.measure({\n scope: 'findOne',\n args: scopedFilter,\n task: async () => {\n const record = await this.repository.findOne({ filter: scopedFilter });\n\n return this.respond<TDataObject>({\n context,\n format: ResponseFormats.OBJECT,\n payload: { count: record ? 1 : 0, data: record },\n });\n },\n });\n\n return context.json(rs, HTTP.ResultCodes.RS_2.Ok);\n }\n}\n"]}
@@ -9,6 +9,11 @@ import { RoutePathScopes } from '../common/constants.js';
9
9
  import { OpenApiResponses } from '../../models/common/index.js';
10
10
  import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
11
11
  import { BaseHelper, getError } from '@venizia/ignis-helpers/core';
12
+ import { RouterFactories } from '../../applications/router-factory.js';
13
+ // Loading this module makes the application's routers `OpenAPIHono` (see `RouterFactories`).
14
+ RouterFactories.registerOpenApi({
15
+ factory: ({ strict }) => new OpenAPIHono({ strict }),
16
+ });
12
17
  /** True for a route path carrying a path parameter, in either supported syntax: `/{id}` or `/:id`. */
13
18
  const hasPathParam = (opts) => {
14
19
  return /\{[^}]+\}|:[^/]+/.test(opts.path);
@@ -1 +1 @@
1
- {"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/base/controllers/rest/abstract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,2CAA2C,CAAC;AAChF,OAAO,EAAE,YAAY,IAAI,cAAc,EAAE,MAAM,8DAA8D,CAAC;AAE9G,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,wDAAwD,CAAC;AAClG,OAAO,EAAE,kBAAkB,EAAE,MAAM,mDAAmD,CAAC;AACvF,OAAO,EAAE,8BAA8B,EAAE,MAAM,uDAAuD,CAAC;AACvG,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,gBAAgB,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,EAAE,eAAe,EAAwB,MAAM,qCAAqC,CAAC;AAC5F,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAExD,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAE7D,OAAO,EAAE,UAAU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,QAAQ,EAAE,GAAG,EAAE,CAAC;IACvC,CAAC;IAED,oFAAoF;IACpF,eAAe,CAAuC,IAA8B;QAClF,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;QACvE,MAAM,EAAE,IAAI,GAAG,EAAE,EAAE,GAAG,UAAU,CAAC;QAEjC,mPAAmP;QACnP,OAAO,WAAW,CAChB,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE;YAC5B,UAAU,EAAE,GAAG;YACf,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC;YAC3B,QAAQ;SACT,CAAQ,CACV,CAAC;IACJ,CAAC;IAED,4EAA4E;IAC5E,kBAAkB,CAAuC,IAA8B;QACrF,MAAM,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,CAAC;QACvE,MAAM,EAAE,SAAS,EAAE,IAAI,GAAG,EAAE,EAAE,GAAG,UAAU,CAAC;QAE5C,qEAAqE;QACrE,OAAO,WAAW,CAChB,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE;YAC5B,UAAU,EAAE,GAAG;YACf,SAAS,EAAE,MAAM,CAAC,MAAM,CACtB,EAAE,EACF,gBAAgB,CAAC,YAAY,CAAC,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC,EAC3D,SAAS,CACV;YACD,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC;YAC3B,QAAQ;SACT,CAAQ,CACV,CAAC;IACJ,CAAC;CAeF","sourcesContent":["import { AuthenticationModes } from '@/base/auth/authenticate/common/constants';\nimport { authenticate as authenticateFn } from '@/base/auth/authenticate/middlewares/authenticate.middleware';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport { authorize as authorizeFn } from '@/base/auth/authorize/middlewares/authorize.middleware';\nimport { FormBodyMiddleware } from '@/base/middlewares/form-body/form-body.middleware';\nimport { AuthenticationStrategyRegistry } from '@/base/auth/authenticate/strategies/strategy-registry';\nimport { DroppedRouteDecorators } from '@/base/metadata/routes/common';\nimport { MetadataRegistry } from '@/helpers/inversion/registry';\nimport { RoutePathScopes, type TRoutePathScope } from '@/base/controllers/common/constants';\nimport { OpenApiResponses } from '@/base/models/common';\nimport type { Hook } from '@hono/zod-openapi';\nimport { createRoute, OpenAPIHono } from '@hono/zod-openapi';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type { Env, Schema } from 'hono';\nimport type {\n IAuthRouteConfig,\n IBindRouteOptions,\n IController,\n IControllerOptions,\n IDefineRouteOptions,\n TRouteHandler,\n} from '../common/types';\n\n/** True for a route path carrying a path parameter, in either supported syntax: `/{id}` or `/:id`. */\nconst hasPathParam = (opts: { path: string }): boolean => {\n return /\\{[^}]+\\}|:[^/]+/.test(opts.path);\n};\n\n/** Abstract base class for all REST controllers, providing route registration and auth middleware integration. */\nexport abstract class AbstractRestController<\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n Definitions extends Record<string, IAuthRouteConfig> = Record<string, IAuthRouteConfig>,\n>\n extends BaseHelper\n implements IController<RouteEnv, RouteSchema, BasePath, ConfigurableOptions>\n{\n isConfigured = false;\n router: OpenAPIHono<RouteEnv, RouteSchema, BasePath>;\n path: string;\n definitions: Definitions;\n\n constructor(opts: IControllerOptions) {\n super(opts);\n const { isStrict = true } = opts;\n\n const decoratorMetadata = MetadataRegistry.getInstance().getControllerMetadata({\n target: new.target,\n });\n const resolvedPath = decoratorMetadata?.path ?? opts.path;\n\n if (!resolvedPath) {\n throw getError({\n message: `[${new.target.name}] Controller path is required. Provide path via @controller decorator or constructor options.`,\n });\n }\n\n this.path = resolvedPath;\n\n this.router = new OpenAPIHono<RouteEnv, RouteSchema, BasePath>({\n strict: isStrict,\n defaultHook: (result, _context) => {\n if (!result.success) {\n throw result.error;\n }\n },\n });\n }\n\n /** Returns the OpenAPIHono router instance for this controller. */\n getRouter() {\n return this.router;\n }\n\n /** Registers decorator-defined routes from the metadata registry; `paths` selects them by shape - see the two-phase call in {@link configure}. */\n registerRoutesFromRegistry(opts?: { paths?: TRoutePathScope }): void {\n const { paths = RoutePathScopes.ALL } = opts ?? {};\n\n const logger = this.logger.for(this.registerRoutesFromRegistry.name);\n DroppedRouteDecorators.report({ logger });\n\n const routes = MetadataRegistry.getInstance().getRoutes({\n target: Object.getPrototypeOf(this),\n });\n\n if (!routes?.size) {\n return;\n }\n\n const routeDefs = routes.entries();\n\n for (const [methodName, routeConfigs] of routeDefs) {\n if (\n paths !== RoutePathScopes.ALL &&\n hasPathParam({ path: routeConfigs.path }) !== (paths === RoutePathScopes.PARAM)\n ) {\n continue;\n }\n\n // Dynamic dispatch by decorator-recorded method name - the controller class has no static index signature, so this read cannot be typed narrower than `unknown`.\n const handler = (this as Record<string | symbol, unknown>)[methodName];\n\n if (typeof handler !== 'function') {\n logger.warn('Route method \"%s\" not found on controller', String(methodName));\n continue;\n }\n\n this.bindRoute({ configs: routeConfigs }).to({\n handler: (handler as TRouteHandler<unknown, RouteEnv>).bind(this),\n });\n }\n }\n\n /** Configures the controller by binding all routes and registering decorator-based routes. Idempotent. */\n async configure(\n opts?: ConfigurableOptions,\n ): Promise<OpenAPIHono<RouteEnv, RouteSchema, BasePath>> {\n if (this.isConfigured) {\n return this.router;\n }\n\n const t = performance.now();\n const logger = this.logger.for(this.configure.name);\n\n const configureOptions = opts ?? {};\n logger.info('START | Binding controller | Options: %j', configureOptions);\n\n // Hono matches in registration order, so registration runs by SHAPE not source: every static path first, then binding()'s routes, then decorator param routes last (`/{id}` early would eat `/count`).\n this.registerRoutesFromRegistry({ paths: RoutePathScopes.STATIC });\n await this.binding();\n this.registerRoutesFromRegistry({ paths: RoutePathScopes.PARAM });\n\n this.isConfigured = true;\n logger.info('DONE | Binding controller | Took: %s (ms)', performance.now() - t);\n\n return this.router;\n }\n\n /** @internal Builds auth + custom middlewares and security specs from route config. */\n buildRouteMiddlewares<RouteConfig extends IAuthRouteConfig>(opts: { configs: RouteConfig }) {\n const { authenticate = {}, authorize, ...restConfig } = opts.configs;\n const { strategies = [], mode = AuthenticationModes.ANY } = authenticate;\n\n // Boot-time and NON-fatal: names a misspelled strategy at error level instead of leaving it as\n // a 401 nobody can explain. Deliberately not a throw - `AuthControllerFactory.define` hard-codes `jwt`\n // on four routes, and ANY mode tolerates a strategy that does not resolve, so failing here would\n // stop applications booting that work today. `assertRegistered` is there for an application that\n // does want the hard failure.\n AuthenticationStrategyRegistry.getInstance().reportUnregistered({\n names: strategies,\n scope: this.constructor.name,\n });\n\n const security = strategies.map((strategy: string) => ({ [strategy]: [] }));\n const mws: ReturnType<typeof authenticateFn>[] = [];\n\n if (strategies.length > 0) {\n mws.push(authenticateFn({ strategies, mode }));\n }\n\n // Inject authorize middleware AFTER authenticate\n if (authorize) {\n const specs: IAuthorizationSpec[] = Array.isArray(authorize) ? authorize : [authorize];\n\n for (const spec of specs) {\n mws.push(authorizeFn({ spec }));\n }\n }\n\n const configuredMiddleware = restConfig.middleware;\n const extraMws = Array.isArray(configuredMiddleware)\n ? configuredMiddleware\n : [configuredMiddleware];\n\n for (const mw of extraMws) {\n if (!mw) {\n continue;\n }\n\n mws.push(mw);\n }\n\n // Last: an application middleware and any size check run before the body is read.\n if (FormBodyMiddleware.hasFormBody({ content: restConfig.request?.body?.content })) {\n mws.push(FormBodyMiddleware.read);\n }\n\n return { restConfig, security, mws };\n }\n\n /** Processes route config, injecting auth middleware and OpenAPI security specs. */\n getRouteConfigs<RouteConfig extends IAuthRouteConfig>(opts: { configs: RouteConfig }) {\n const { restConfig, security, mws } = this.buildRouteMiddlewares(opts);\n const { tags = [] } = restConfig;\n\n // `restConfig` already omitted `authenticate`/`authorize` (this library's fields, not Hono's `createRoute` ones); reassembled with the injected middleware/tags/security it no longer structurally overlaps RouteConfig enough to assert directly.\n return createRoute<string, RouteConfig>(\n Object.assign({}, restConfig, {\n middleware: mws,\n tags: [...tags, this.scope],\n security,\n }) as any,\n );\n }\n\n /** Like getRouteConfigs but adds HTML response schema for JSX rendering. */\n getJSXRouteConfigs<RouteConfig extends IAuthRouteConfig>(opts: { configs: RouteConfig }) {\n const { restConfig, security, mws } = this.buildRouteMiddlewares(opts);\n const { responses, tags = [] } = restConfig;\n\n // Same reassembled-vs-RouteConfig boundary as getRouteConfigs above.\n return createRoute<string, RouteConfig>(\n Object.assign({}, restConfig, {\n middleware: mws,\n responses: Object.assign(\n {},\n OpenApiResponses.htmlResponse({ description: 'HTML page' }),\n responses,\n ),\n tags: [...tags, this.scope],\n security,\n }) as any,\n );\n }\n /** Override to register routes using bindRoute or defineRoute. */\n abstract binding(): ValueOrPromise<void>;\n\n /** Creates a fluent binding for registering a route (call .to() to attach handler). */\n abstract bindRoute<RouteConfig extends IAuthRouteConfig>(opts: {\n configs: RouteConfig;\n }): IBindRouteOptions<RouteConfig, RouteEnv, RouteSchema, BasePath>;\n\n /** Defines and registers a route with its handler in a single call. */\n abstract defineRoute<RouteConfig extends IAuthRouteConfig, ResponseType = unknown>(opts: {\n configs: RouteConfig;\n handler: TRouteHandler<ResponseType, RouteEnv>;\n hook?: Hook<any, RouteEnv, string, ValueOrPromise<any>>;\n }): IDefineRouteOptions<RouteConfig, RouteEnv, RouteSchema, BasePath>;\n}\n"]}
1
+ {"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../../src/base/controllers/rest/abstract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,2CAA2C,CAAC;AAChF,OAAO,EAAE,YAAY,IAAI,cAAc,EAAE,MAAM,8DAA8D,CAAC;AAE9G,OAAO,EAAE,SAAS,IAAI,WAAW,EAAE,MAAM,wDAAwD,CAAC;AAClG,OAAO,EAAE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;QACvE,MAAM,EAAE,SAAS,EAAE,IAAI,GAAG,EAAE,EAAE,GAAG,UAAU,CAAC;QAE5C,qEAAqE;QACrE,OAAO,WAAW,CAChB,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE;YAC5B,UAAU,EAAE,GAAG;YACf,SAAS,EAAE,MAAM,CAAC,MAAM,CACtB,EAAE,EACF,gBAAgB,CAAC,YAAY,CAAC,EAAE,WAAW,EAAE,WAAW,EAAE,CAAC,EAC3D,SAAS,CACV;YACD,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC;YAC3B,QAAQ;SACT,CAAQ,CACV,CAAC;IACJ,CAAC;CAeF","sourcesContent":["import { AuthenticationModes } from '@/base/auth/authenticate/common/constants';\nimport { authenticate as authenticateFn } from '@/base/auth/authenticate/middlewares/authenticate.middleware';\nimport type { IAuthorizationSpec } from '@/base/auth/authorize/common/types';\nimport { authorize as authorizeFn } from '@/base/auth/authorize/middlewares/authorize.middleware';\nimport { FormBodyMiddleware } from '@/base/middlewares/form-body/form-body.middleware';\nimport { AuthenticationStrategyRegistry } from '@/base/auth/authenticate/strategies/strategy-registry';\nimport { DroppedRouteDecorators } from '@/base/metadata/routes/common';\nimport { MetadataRegistry } from '@/helpers/inversion/registry';\nimport { RoutePathScopes, type TRoutePathScope } from '@/base/controllers/common/constants';\nimport { OpenApiResponses } from '@/base/models/common';\nimport type { Hook } from '@hono/zod-openapi';\nimport { createRoute, OpenAPIHono } from '@hono/zod-openapi';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type { Env, Schema } from 'hono';\nimport { RouterFactories } from '@/base/applications/router-factory';\nimport type {\n IAuthRouteConfig,\n IBindRouteOptions,\n IController,\n IControllerOptions,\n IDefineRouteOptions,\n TRouteHandler,\n} from '../common/types';\n\n// Loading this module makes the application's routers `OpenAPIHono` (see `RouterFactories`).\nRouterFactories.registerOpenApi({\n factory: ({ strict }) => new OpenAPIHono({ strict }),\n});\n\n/** True for a route path carrying a path parameter, in either supported syntax: `/{id}` or `/:id`. */\nconst hasPathParam = (opts: { path: string }): boolean => {\n return /\\{[^}]+\\}|:[^/]+/.test(opts.path);\n};\n\n/** Abstract base class for all REST controllers, providing route registration and auth middleware integration. */\nexport abstract class AbstractRestController<\n RouteEnv extends Env = Env,\n RouteSchema extends Schema = {},\n BasePath extends string = '/',\n ConfigurableOptions extends object = {},\n Definitions extends Record<string, IAuthRouteConfig> = Record<string, IAuthRouteConfig>,\n>\n extends BaseHelper\n implements IController<RouteEnv, RouteSchema, BasePath, ConfigurableOptions>\n{\n isConfigured = false;\n router: OpenAPIHono<RouteEnv, RouteSchema, BasePath>;\n path: string;\n definitions: Definitions;\n\n constructor(opts: IControllerOptions) {\n super(opts);\n const { isStrict = true } = opts;\n\n const decoratorMetadata = MetadataRegistry.getInstance().getControllerMetadata({\n target: new.target,\n });\n const resolvedPath = decoratorMetadata?.path ?? opts.path;\n\n if (!resolvedPath) {\n throw getError({\n message: `[${new.target.name}] Controller path is required. Provide path via @controller decorator or constructor options.`,\n });\n }\n\n this.path = resolvedPath;\n\n this.router = new OpenAPIHono<RouteEnv, RouteSchema, BasePath>({\n strict: isStrict,\n defaultHook: (result, _context) => {\n if (!result.success) {\n throw result.error;\n }\n },\n });\n }\n\n /** Returns the OpenAPIHono router instance for this controller. */\n getRouter() {\n return this.router;\n }\n\n /** Registers decorator-defined routes from the metadata registry; `paths` selects them by shape - see the two-phase call in {@link configure}. */\n registerRoutesFromRegistry(opts?: { paths?: TRoutePathScope }): void {\n const { paths = RoutePathScopes.ALL } = opts ?? {};\n\n const logger = this.logger.for(this.registerRoutesFromRegistry.name);\n DroppedRouteDecorators.report({ logger });\n\n const routes = MetadataRegistry.getInstance().getRoutes({\n target: Object.getPrototypeOf(this),\n });\n\n if (!routes?.size) {\n return;\n }\n\n const routeDefs = routes.entries();\n\n for (const [methodName, routeConfigs] of routeDefs) {\n if (\n paths !== RoutePathScopes.ALL &&\n hasPathParam({ path: routeConfigs.path }) !== (paths === RoutePathScopes.PARAM)\n ) {\n continue;\n }\n\n // Dynamic dispatch by decorator-recorded method name - the controller class has no static index signature, so this read cannot be typed narrower than `unknown`.\n const handler = (this as Record<string | symbol, unknown>)[methodName];\n\n if (typeof handler !== 'function') {\n logger.warn('Route method \"%s\" not found on controller', String(methodName));\n continue;\n }\n\n this.bindRoute({ configs: routeConfigs }).to({\n handler: (handler as TRouteHandler<unknown, RouteEnv>).bind(this),\n });\n }\n }\n\n /** Configures the controller by binding all routes and registering decorator-based routes. Idempotent. */\n async configure(\n opts?: ConfigurableOptions,\n ): Promise<OpenAPIHono<RouteEnv, RouteSchema, BasePath>> {\n if (this.isConfigured) {\n return this.router;\n }\n\n const t = performance.now();\n const logger = this.logger.for(this.configure.name);\n\n const configureOptions = opts ?? {};\n logger.info('START | Binding controller | Options: %j', configureOptions);\n\n // Hono matches in registration order, so registration runs by SHAPE not source: every static path first, then binding()'s routes, then decorator param routes last (`/{id}` early would eat `/count`).\n this.registerRoutesFromRegistry({ paths: RoutePathScopes.STATIC });\n await this.binding();\n this.registerRoutesFromRegistry({ paths: RoutePathScopes.PARAM });\n\n this.isConfigured = true;\n logger.info('DONE | Binding controller | Took: %s (ms)', performance.now() - t);\n\n return this.router;\n }\n\n /** @internal Builds auth + custom middlewares and security specs from route config. */\n buildRouteMiddlewares<RouteConfig extends IAuthRouteConfig>(opts: { configs: RouteConfig }) {\n const { authenticate = {}, authorize, ...restConfig } = opts.configs;\n const { strategies = [], mode = AuthenticationModes.ANY } = authenticate;\n\n // Boot-time and NON-fatal: names a misspelled strategy at error level instead of leaving it as\n // a 401 nobody can explain. Deliberately not a throw - `AuthControllerFactory.define` hard-codes `jwt`\n // on four routes, and ANY mode tolerates a strategy that does not resolve, so failing here would\n // stop applications booting that work today. `assertRegistered` is there for an application that\n // does want the hard failure.\n AuthenticationStrategyRegistry.getInstance().reportUnregistered({\n names: strategies,\n scope: this.constructor.name,\n });\n\n const security = strategies.map((strategy: string) => ({ [strategy]: [] }));\n const mws: ReturnType<typeof authenticateFn>[] = [];\n\n if (strategies.length > 0) {\n mws.push(authenticateFn({ strategies, mode }));\n }\n\n // Inject authorize middleware AFTER authenticate\n if (authorize) {\n const specs: IAuthorizationSpec[] = Array.isArray(authorize) ? authorize : [authorize];\n\n for (const spec of specs) {\n mws.push(authorizeFn({ spec }));\n }\n }\n\n const configuredMiddleware = restConfig.middleware;\n const extraMws = Array.isArray(configuredMiddleware)\n ? configuredMiddleware\n : [configuredMiddleware];\n\n for (const mw of extraMws) {\n if (!mw) {\n continue;\n }\n\n mws.push(mw);\n }\n\n // Last: an application middleware and any size check run before the body is read.\n if (FormBodyMiddleware.hasFormBody({ content: restConfig.request?.body?.content })) {\n mws.push(FormBodyMiddleware.read);\n }\n\n return { restConfig, security, mws };\n }\n\n /** Processes route config, injecting auth middleware and OpenAPI security specs. */\n getRouteConfigs<RouteConfig extends IAuthRouteConfig>(opts: { configs: RouteConfig }) {\n const { restConfig, security, mws } = this.buildRouteMiddlewares(opts);\n const { tags = [] } = restConfig;\n\n // `restConfig` already omitted `authenticate`/`authorize` (this library's fields, not Hono's `createRoute` ones); reassembled with the injected middleware/tags/security it no longer structurally overlaps RouteConfig enough to assert directly.\n return createRoute<string, RouteConfig>(\n Object.assign({}, restConfig, {\n middleware: mws,\n tags: [...tags, this.scope],\n security,\n }) as any,\n );\n }\n\n /** Like getRouteConfigs but adds HTML response schema for JSX rendering. */\n getJSXRouteConfigs<RouteConfig extends IAuthRouteConfig>(opts: { configs: RouteConfig }) {\n const { restConfig, security, mws } = this.buildRouteMiddlewares(opts);\n const { responses, tags = [] } = restConfig;\n\n // Same reassembled-vs-RouteConfig boundary as getRouteConfigs above.\n return createRoute<string, RouteConfig>(\n Object.assign({}, restConfig, {\n middleware: mws,\n responses: Object.assign(\n {},\n OpenApiResponses.htmlResponse({ description: 'HTML page' }),\n responses,\n ),\n tags: [...tags, this.scope],\n security,\n }) as any,\n );\n }\n /** Override to register routes using bindRoute or defineRoute. */\n abstract binding(): ValueOrPromise<void>;\n\n /** Creates a fluent binding for registering a route (call .to() to attach handler). */\n abstract bindRoute<RouteConfig extends IAuthRouteConfig>(opts: {\n configs: RouteConfig;\n }): IBindRouteOptions<RouteConfig, RouteEnv, RouteSchema, BasePath>;\n\n /** Defines and registers a route with its handler in a single call. */\n abstract defineRoute<RouteConfig extends IAuthRouteConfig, ResponseType = unknown>(opts: {\n configs: RouteConfig;\n handler: TRouteHandler<ResponseType, RouteEnv>;\n hook?: Hook<any, RouteEnv, string, ValueOrPromise<any>>;\n }): IDefineRouteOptions<RouteConfig, RouteEnv, RouteSchema, BasePath>;\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { AnyType, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';
2
2
  import { BaseHelper } from '@venizia/ignis-helpers/core';
3
- import type { IDataSource, IDataSourceCapabilities, ITransaction, ITransactionOptions, TAnyDataSourceSchema } from './common/index.js';
3
+ import type { IDataSource, IDataSourceCapabilities, IDataSourceOpening, ITransaction, ITransactionOptions, TAnyDataSourceSchema, TDataSourceOpenMode } from './common/index.js';
4
+ import { OPENING_HANDLES } from './opening-handles.js';
4
5
  /**
5
6
  * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.
6
7
  *
@@ -19,7 +20,73 @@ export declare abstract class AbstractDataSource<Settings extends object = {}, S
19
20
  name: string;
20
21
  settings: Settings;
21
22
  schema: Schema;
22
- abstract configure(opts?: ConfigurableOptions): ValueOrPromise<void>;
23
+ abstract configure(opts?: ConfigurableOptions, opening?: IDataSourceOpening): ValueOrPromise<void>;
24
+ /** The options the boot would have given `configure()`, kept for the open that the first use starts. */
25
+ private deferredOptions?;
26
+ /** The open in flight: every call that arrives meanwhile awaits this one promise. */
27
+ private opening?;
28
+ /**
29
+ * An open that outlived its timeout and has not settled. Nothing is retried until it has: two `configure()` must never
30
+ * run at once, and when it does settle what it built is closed, never published.
31
+ */
32
+ private abandoned?;
33
+ private isOpened;
34
+ private isShutDown;
35
+ /**
36
+ * Whether this family can open on first use: only a family whose every entry point first awaits {@link ensureOpen}
37
+ * says yes (the relational one does). A family that does not is refused at boot rather than left half-working.
38
+ */
39
+ protected supportsDeferredOpen(): boolean;
40
+ /** The `open.on` of `@datasource`, `start` when unset. */
41
+ getOpenMode(): TDataSourceOpenMode;
42
+ isOpenDeferred(): boolean;
43
+ /** The `open.timeoutMs` of `@datasource` (ms; `0` waits for ever), 60 s when unset. */
44
+ getOpenTimeoutMs(): number;
45
+ /**
46
+ * Whether the datasource is open. One that opens on first use: after the first use has finished, until `close()`. One that
47
+ * opens at start: from the moment the application has started it, until `close()`.
48
+ */
49
+ isOpen(): boolean;
50
+ /** Whether the first use is opening the datasource right now. */
51
+ isOpening(): boolean;
52
+ /** Whether `close()` has begun. A datasource that opens on first use is not reopened after it. */
53
+ isClosed(): boolean;
54
+ /**
55
+ * What the application boot calls to get the handles it passes to `configure()` of a datasource that opens at start. Keyed by a
56
+ * symbol the package does not export, so nothing else can obtain the handles: see {@link OPENING_HANDLES}.
57
+ */
58
+ [OPENING_HANDLES](): IDataSourceOpening;
59
+ /**
60
+ * The handles `configure()` gets as its second argument, in both modes. The root has no connector, client or transaction to
61
+ * hand out; a family that has them overrides this. Protected: the only ways out are the argument of `configure()` and the
62
+ * boot's private key.
63
+ */
64
+ protected createOpening(): IDataSourceOpening;
65
+ /**
66
+ * The boot's replacement for `configure()` on a datasource that opens on first use: records the options and opens nothing.
67
+ * Refused for a family that cannot honour it.
68
+ */
69
+ deferOpen(opts: {
70
+ options?: ConfigurableOptions;
71
+ }): void;
72
+ /**
73
+ * Resolves once the datasource is open. At once for one that opens with the application. Otherwise the first caller
74
+ * starts `configure()` and the rest await the same promise, so it runs once; a failure rejects all of them, undoes what the
75
+ * failed `configure()` left ({@link discardPartialOpen}) and clears the slot, so the next call opens afresh. After
76
+ * `close()` it rejects: a stopped application does not reopen its datasources.
77
+ */
78
+ ensureOpen(): Promise<void>;
79
+ private runOpen;
80
+ /** When an abandoned open finally settles, whatever it built is closed (it was never published) and retries are allowed again. */
81
+ private settleAbandoned;
82
+ private discardOpenAttempt;
83
+ /** Undoes what a `configure()` that threw left behind, so the next open starts clean. The root holds nothing; a family that keeps a client overrides it. */
84
+ protected discardPartialOpen(): ValueOrPromise<void>;
85
+ /**
86
+ * Waits for an open in flight and refuses any later one. A family's `close()` calls it first, so a stop that arrives
87
+ * during the first use closes what that open built instead of racing it.
88
+ */
89
+ protected settleOpening(): Promise<void>;
23
90
  getSettings(): Settings;
24
91
  getSchema(): Schema;
25
92
  /** Capability probe, overridden by connectors that support it (e.g. postgres reports `{ transactions: true }`). */
@@ -2,6 +2,8 @@ var _a;
2
2
  import { MetadataRegistry } from '../../helpers/inversion/index.js';
3
3
  import { NotSupportedUtility } from '../../utilities/index.js';
4
4
  import { BaseHelper, getError } from '@venizia/ignis-helpers/core';
5
+ import { DataSourceOpenDefaults, DataSourceOpenModes } from './common/index.js';
6
+ import { OPENING_HANDLES } from './opening-handles.js';
5
7
  /**
6
8
  * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.
7
9
  *
@@ -15,11 +17,194 @@ export const DATA_SOURCE_BRAND = Symbol.for('@venizia/ignis-kernel:abstract-data
15
17
  export const isDataSourceClass = (value) => {
16
18
  return typeof value === 'function' && DATA_SOURCE_BRAND in value;
17
19
  };
20
+ /** The two ways a race between the open and its timeout can end. */
21
+ const OPEN_DONE = 'done';
22
+ const OPEN_TIMED_OUT = 'timed-out';
18
23
  /** Engine-neutral datasource root - NO SQL members. Every connector family extends this. */
19
24
  export class AbstractDataSource extends BaseHelper {
20
- static { _a = DATA_SOURCE_BRAND; }
25
+ constructor() {
26
+ super(...arguments);
27
+ this.isOpened = false;
28
+ this.isShutDown = false;
29
+ }
21
30
  /** Read by {@link isDataSourceClass}. Static, so every subclass inherits it. */
22
31
  static { this[_a] = true; }
32
+ /**
33
+ * Whether this family can open on first use: only a family whose every entry point first awaits {@link ensureOpen}
34
+ * says yes (the relational one does). A family that does not is refused at boot rather than left half-working.
35
+ */
36
+ supportsDeferredOpen() {
37
+ return false;
38
+ }
39
+ /** The `open.on` of `@datasource`, `start` when unset. */
40
+ getOpenMode() {
41
+ const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({
42
+ target: this.constructor,
43
+ });
44
+ return metadata?.open?.on ?? DataSourceOpenModes.START;
45
+ }
46
+ isOpenDeferred() {
47
+ return this.getOpenMode() === DataSourceOpenModes.FIRST_USE;
48
+ }
49
+ /** The `open.timeoutMs` of `@datasource` (ms; `0` waits for ever), 60 s when unset. */
50
+ getOpenTimeoutMs() {
51
+ const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({
52
+ target: this.constructor,
53
+ });
54
+ return metadata?.open?.timeoutMs ?? DataSourceOpenDefaults.TIMEOUT_MS;
55
+ }
56
+ /**
57
+ * Whether the datasource is open. One that opens on first use: after the first use has finished, until `close()`. One that
58
+ * opens at start: from the moment the application has started it, until `close()`.
59
+ */
60
+ isOpen() {
61
+ if (this.isShutDown) {
62
+ return false;
63
+ }
64
+ return this.isOpenDeferred() ? this.isOpened : true;
65
+ }
66
+ /** Whether the first use is opening the datasource right now. */
67
+ isOpening() {
68
+ return this.opening !== undefined;
69
+ }
70
+ /** Whether `close()` has begun. A datasource that opens on first use is not reopened after it. */
71
+ isClosed() {
72
+ return this.isShutDown;
73
+ }
74
+ /**
75
+ * What the application boot calls to get the handles it passes to `configure()` of a datasource that opens at start. Keyed by a
76
+ * symbol the package does not export, so nothing else can obtain the handles: see {@link OPENING_HANDLES}.
77
+ */
78
+ [(_a = DATA_SOURCE_BRAND, OPENING_HANDLES)]() {
79
+ return this.createOpening();
80
+ }
81
+ /**
82
+ * The handles `configure()` gets as its second argument, in both modes. The root has no connector, client or transaction to
83
+ * hand out; a family that has them overrides this. Protected: the only ways out are the argument of `configure()` and the
84
+ * boot's private key.
85
+ */
86
+ createOpening() {
87
+ const refuse = (member) => NotSupportedUtility.throwNotSupported({
88
+ scope: this.constructor.name,
89
+ feature: `opening.${member}`,
90
+ logger: this.logger,
91
+ });
92
+ return {
93
+ getConnector: () => refuse('getConnector'),
94
+ getClient: () => refuse('getClient'),
95
+ beginTransaction: () => Promise.resolve().then(() => refuse('beginTransaction')),
96
+ };
97
+ }
98
+ /**
99
+ * The boot's replacement for `configure()` on a datasource that opens on first use: records the options and opens nothing.
100
+ * Refused for a family that cannot honour it.
101
+ */
102
+ deferOpen(opts) {
103
+ if (!this.supportsDeferredOpen()) {
104
+ throw getError({
105
+ message: `[${this.constructor.name}][deferOpen] open: 'first-use' is not supported by this datasource family | Use open: { on: 'start' }, or remove the option`,
106
+ });
107
+ }
108
+ this.deferredOptions = opts.options;
109
+ }
110
+ /**
111
+ * Resolves once the datasource is open. At once for one that opens with the application. Otherwise the first caller
112
+ * starts `configure()` and the rest await the same promise, so it runs once; a failure rejects all of them, undoes what the
113
+ * failed `configure()` left ({@link discardPartialOpen}) and clears the slot, so the next call opens afresh. After
114
+ * `close()` it rejects: a stopped application does not reopen its datasources.
115
+ */
116
+ ensureOpen() {
117
+ if (!this.isOpenDeferred()) {
118
+ return Promise.resolve();
119
+ }
120
+ // Closed first: a call after `close()` is told so, whether or not the datasource had been opened.
121
+ if (this.isShutDown) {
122
+ return Promise.reject(getError({
123
+ message: `[${this.constructor.name}][ensureOpen] The datasource is closed | It opens on first use only before close()`,
124
+ }));
125
+ }
126
+ if (this.isOpened) {
127
+ return Promise.resolve();
128
+ }
129
+ if (this.abandoned) {
130
+ return Promise.reject(getError({
131
+ message: `[${this.constructor.name}][ensureOpen] The previous open is still running after its timeout | It is retried once it has settled`,
132
+ }));
133
+ }
134
+ this.opening ??= this.runOpen();
135
+ return this.opening;
136
+ }
137
+ async runOpen() {
138
+ const timeoutMs = this.getOpenTimeoutMs();
139
+ const work = Promise.resolve().then(() => this.configure(this.deferredOptions, this.createOpening()));
140
+ let timer;
141
+ const expired = new Promise((resolve) => {
142
+ if (timeoutMs > 0) {
143
+ timer = setTimeout(() => resolve(OPEN_TIMED_OUT), timeoutMs);
144
+ }
145
+ });
146
+ try {
147
+ const outcome = await Promise.race([work.then(() => OPEN_DONE), expired]);
148
+ if (outcome === OPEN_TIMED_OUT) {
149
+ this.abandoned = this.settleAbandoned({ work });
150
+ throw getError({
151
+ message: `[${this.constructor.name}][ensureOpen] The open did not finish within ${timeoutMs} ms | Does configure() await the datasource (a repository, ensureOpen)? Use the opening argument inside configure()`,
152
+ });
153
+ }
154
+ this.isOpened = true;
155
+ }
156
+ catch (error) {
157
+ await this.discardOpenAttempt();
158
+ throw error;
159
+ }
160
+ finally {
161
+ if (timer !== undefined) {
162
+ clearTimeout(timer);
163
+ }
164
+ this.opening = undefined;
165
+ }
166
+ }
167
+ /** When an abandoned open finally settles, whatever it built is closed (it was never published) and retries are allowed again. */
168
+ async settleAbandoned(opts) {
169
+ try {
170
+ await opts.work;
171
+ // eslint-disable-next-line venizia/no-silent-catch -- the abandoned attempt's own outcome was already reported by the timeout; only its clean-up matters now
172
+ }
173
+ catch {
174
+ // Falls through to the clean-up.
175
+ }
176
+ await this.discardOpenAttempt();
177
+ this.abandoned = undefined;
178
+ }
179
+ async discardOpenAttempt() {
180
+ try {
181
+ await this.discardPartialOpen();
182
+ // eslint-disable-next-line venizia/no-silent-catch -- the open's own error is what the caller must see: a failed clean-up is logged, never thrown over it
183
+ }
184
+ catch (cleanupError) {
185
+ this.logger
186
+ .for(this.ensureOpen.name)
187
+ .warn('Clean-up after a failed open also failed | error: %s', cleanupError);
188
+ }
189
+ }
190
+ /** Undoes what a `configure()` that threw left behind, so the next open starts clean. The root holds nothing; a family that keeps a client overrides it. */
191
+ discardPartialOpen() { }
192
+ /**
193
+ * Waits for an open in flight and refuses any later one. A family's `close()` calls it first, so a stop that arrives
194
+ * during the first use closes what that open built instead of racing it.
195
+ */
196
+ async settleOpening() {
197
+ this.isShutDown = true;
198
+ try {
199
+ await this.opening;
200
+ // eslint-disable-next-line venizia/no-silent-catch -- the failed open was reported to its own waiters; stopping goes on
201
+ }
202
+ catch (openError) {
203
+ this.logger
204
+ .for(this.close.name)
205
+ .debug('The open in flight failed while stopping | error: %s', openError);
206
+ }
207
+ }
23
208
  getSettings() {
24
209
  return this.settings;
25
210
  }
@@ -1 +1 @@
1
- {"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../src/base/datasources/abstract.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AASnE;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;AAE1F,kGAAkG;AAClG,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,KAAc,EAA4B,EAAE;IAC5E,OAAO,OAAO,KAAK,KAAK,UAAU,IAAI,iBAAiB,IAAI,KAAK,CAAC;AACnE,CAAC,CAAC;AAEF,4FAA4F;AAC5F,MAAM,OAAgB,kBAKpB,SAAQ,UAAU;kBAID,iBAAiB;IADlC,gFAAgF;aAChE,QAAmB,GAAG,IAAI,CAAC;IAQ3C,WAAW;QACT,OAAO,IAAI,CAAC,QAAQ,CAAC;IACvB,CAAC;IAED,SAAS;QACP,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;YACjB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,kFAAkF;aACrH,CAAC,CAAC;QACL,CAAC;QAED,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,mHAAmH;IACnH,eAAe;QACb,OAAO,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC;IACjC,CAAC;IAED,sFAAsF;IACtF,KAAK;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C;YAEpC,IAAI,CAAC,UAAU,EAAE,CAAC;gBAChB,MAAM,CAAC,IAAI,CACT,8DAA8D,EAC9D,IAAI,EACJ,IAAI,CAAC,IAAI,EACT,UAAU,CAAC,IAAI,CAChB,CAAC;gBACF,SAAS;YACX,CAAC;YAED,MAAM,aAAa,GAAG,gBAAgB,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAE5D,IAAI,aAAa,KAAK,SAAS,IAAI,aAAa,KAAK,UAAU,CAAC,IAAI,EAAE,CAAC;gBACrE,MAAM,QAAQ,CAAC;oBACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,oCAAoC,IAAI,UAAU,UAAU,CAAC,IAAI,aAAa,IAAI,CAAC,IAAI,eAAe,aAAa,KAAK,UAAU,CAAC,IAAI,EAAE;iBAC5K,CAAC,CAAC;YACL,CAAC;YAED,gBAAgB,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;YACvD,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC;QAC5C,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACvC,MAAM,CAAC,KAAK,CACV,mDAAmD,EACnD,IAAI,EACJ,IAAI,CAAC,IAAI,EACT,KAAK,CAAC,MAAM,EACZ,KAAK,CACN,CAAC;QAEF,OAAO,WAAW,CAAC;IACrB,CAAC","sourcesContent":["import { MetadataRegistry } from '@/helpers/inversion';\nimport { NotSupportedUtility } from '@/utilities';\nimport type { AnyType, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type {\n IDataSource,\n IDataSourceCapabilities,\n ITransaction,\n ITransactionOptions,\n TAnyDataSourceSchema,\n} from './common';\n\n/**\n * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.\n *\n * Two copies of this package give two `AbstractDataSource` classes, and `instanceof` across them is\n * false - the same trap `isApplicationError` exists to avoid for `ApplicationError`. `Symbol.for` is\n * realm-keyed, so both copies produce this exact symbol, and a static is inherited by every\n * subclass however deep.\n */\nexport const DATA_SOURCE_BRAND = Symbol.for('@venizia/ignis-kernel:abstract-data-source');\n\n/** True for `AbstractDataSource` itself and for any class extending it, across package copies. */\nexport const isDataSourceClass = (value: unknown): value is TClass<AnyType> => {\n return typeof value === 'function' && DATA_SOURCE_BRAND in value;\n};\n\n/** Engine-neutral datasource root - NO SQL members. Every connector family extends this. */\nexport abstract class AbstractDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n>\n extends BaseHelper\n implements IDataSource<Settings, Schema, ConfigurableOptions>\n{\n /** Read by {@link isDataSourceClass}. Static, so every subclass inherits it. */\n static readonly [DATA_SOURCE_BRAND] = true;\n\n name: string;\n settings: Settings;\n schema: Schema;\n\n abstract configure(opts?: ConfigurableOptions): ValueOrPromise<void>;\n\n getSettings() {\n return this.settings;\n }\n\n getSchema(): Schema {\n if (!this.schema) {\n throw getError({\n message: `[${this.constructor.name}] Schema not initialized. Override getSchema() or provide schema in constructor.`,\n });\n }\n\n return this.schema;\n }\n\n /** Capability probe, overridden by connectors that support it (e.g. postgres reports `{ transactions: true }`). */\n getCapabilities(): IDataSourceCapabilities {\n return { transactions: false };\n }\n\n /** Nothing to release at this root; a family that holds a connection overrides it. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /** Defaults to throwing NotSupported - only connectors with real transaction support override this; async so callers get a rejected promise, not a synchronous throw that skips try/catch. */\n async beginTransaction(_opts?: ITransactionOptions): Promise<ITransaction> {\n return NotSupportedUtility.throwNotSupported({\n scope: this.constructor.name,\n feature: 'Transactions',\n logger: this.logger,\n });\n }\n\n /** Model classes bound to this datasource via `@repository` metadata - paradigm-free (no schema/relation resolution). */\n protected getBoundModelClasses(): Array<TClass<unknown>> {\n return MetadataRegistry.getInstance().getModelClasses({\n dataSource: this.constructor as TClass<IDataSource>,\n });\n }\n\n /** Walks model classes bound to this datasource, reads a connector-specific artifact via `read`, and returns a name-keyed registry - skips undefined reads, throws on duplicate names, honors `autoDiscovery: false`. */\n protected discoverDefinitions<TDefinition extends { name: string }>(opts: {\n read: (modelClass: TClass<unknown>) => TDefinition | undefined;\n kind: string;\n }): Record<string, TDefinition> {\n const { read, kind } = opts;\n const logger = this.logger.for(this.discoverDefinitions.name);\n const registry = MetadataRegistry.getInstance();\n\n const metadata = registry.getDataSourceMetadata({ target: this.constructor });\n\n if (metadata?.autoDiscovery === false) {\n logger.debug('Auto-discovery disabled for %s', this.name);\n\n return {};\n }\n\n const modelClasses = this.getBoundModelClasses();\n\n const definitions: Record<string, TDefinition> = {};\n const definitionOwners = new Map<string, string>();\n\n for (const modelClass of modelClasses) {\n const definition = read(modelClass);\n\n if (!definition) {\n logger.warn(\n 'Model has no %s definition | Skipping | Name: %s | Model: %s',\n kind,\n this.name,\n modelClass.name,\n );\n continue;\n }\n\n const existingOwner = definitionOwners.get(definition.name);\n\n if (existingOwner !== undefined && existingOwner !== modelClass.name) {\n throw getError({\n message: `[${this.constructor.name}][discoverDefinitions] Duplicate ${kind} name '${definition.name}' | Name: ${this.name} | Classes: ${existingOwner}, ${modelClass.name}`,\n });\n }\n\n definitionOwners.set(definition.name, modelClass.name);\n definitions[definition.name] = definition;\n }\n\n const names = Object.keys(definitions);\n logger.debug(\n 'Detected %s(s) | Name: %s | Count: %s | Names: %j',\n kind,\n this.name,\n names.length,\n names,\n );\n\n return definitions;\n }\n}\n"]}
1
+ {"version":3,"file":"abstract.js","sourceRoot":"","sources":["../../../../src/base/datasources/abstract.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM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AC;YAED,MAAM,aAAa,GAAG,gBAAgB,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;YAE5D,IAAI,aAAa,KAAK,SAAS,IAAI,aAAa,KAAK,UAAU,CAAC,IAAI,EAAE,CAAC;gBACrE,MAAM,QAAQ,CAAC;oBACb,OAAO,EAAE,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,oCAAoC,IAAI,UAAU,UAAU,CAAC,IAAI,aAAa,IAAI,CAAC,IAAI,eAAe,aAAa,KAAK,UAAU,CAAC,IAAI,EAAE;iBAC5K,CAAC,CAAC;YACL,CAAC;YAED,gBAAgB,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;YACvD,WAAW,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC;QAC5C,CAAC;QAED,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACvC,MAAM,CAAC,KAAK,CACV,mDAAmD,EACnD,IAAI,EACJ,IAAI,CAAC,IAAI,EACT,KAAK,CAAC,MAAM,EACZ,KAAK,CACN,CAAC;QAEF,OAAO,WAAW,CAAC;IACrB,CAAC","sourcesContent":["import { MetadataRegistry } from '@/helpers/inversion';\nimport { NotSupportedUtility } from '@/utilities';\nimport type { AnyType, TClass, ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport type {\n IDataSource,\n IDataSourceCapabilities,\n IDataSourceOpening,\n ITransaction,\n ITransactionOptions,\n TAnyDataSourceSchema,\n TDataSourceOpenMode,\n} from './common';\nimport { DataSourceOpenDefaults, DataSourceOpenModes } from './common';\nimport { OPENING_HANDLES } from './opening-handles';\n\n/**\n * Brands the datasource root so `@repository` can recognise a subclass WITHOUT `instanceof`.\n *\n * Two copies of this package give two `AbstractDataSource` classes, and `instanceof` across them is\n * false - the same trap `isApplicationError` exists to avoid for `ApplicationError`. `Symbol.for` is\n * realm-keyed, so both copies produce this exact symbol, and a static is inherited by every\n * subclass however deep.\n */\nexport const DATA_SOURCE_BRAND = Symbol.for('@venizia/ignis-kernel:abstract-data-source');\n\n/** True for `AbstractDataSource` itself and for any class extending it, across package copies. */\nexport const isDataSourceClass = (value: unknown): value is TClass<AnyType> => {\n return typeof value === 'function' && DATA_SOURCE_BRAND in value;\n};\n\n/** The two ways a race between the open and its timeout can end. */\nconst OPEN_DONE = 'done';\nconst OPEN_TIMED_OUT = 'timed-out';\n\n/** Engine-neutral datasource root - NO SQL members. Every connector family extends this. */\nexport abstract class AbstractDataSource<\n Settings extends object = {},\n Schema extends TAnyDataSourceSchema = TAnyDataSourceSchema,\n ConfigurableOptions extends object = {},\n>\n extends BaseHelper\n implements IDataSource<Settings, Schema, ConfigurableOptions>\n{\n /** Read by {@link isDataSourceClass}. Static, so every subclass inherits it. */\n static readonly [DATA_SOURCE_BRAND] = true;\n\n name: string;\n settings: Settings;\n schema: Schema;\n\n abstract configure(\n opts?: ConfigurableOptions,\n opening?: IDataSourceOpening,\n ): ValueOrPromise<void>;\n\n /** The options the boot would have given `configure()`, kept for the open that the first use starts. */\n private deferredOptions?: ConfigurableOptions;\n\n /** The open in flight: every call that arrives meanwhile awaits this one promise. */\n private opening?: Promise<void>;\n\n /**\n * An open that outlived its timeout and has not settled. Nothing is retried until it has: two `configure()` must never\n * run at once, and when it does settle what it built is closed, never published.\n */\n private abandoned?: Promise<void>;\n\n private isOpened = false;\n private isShutDown = false;\n\n /**\n * Whether this family can open on first use: only a family whose every entry point first awaits {@link ensureOpen}\n * says yes (the relational one does). A family that does not is refused at boot rather than left half-working.\n */\n protected supportsDeferredOpen(): boolean {\n return false;\n }\n\n /** The `open.on` of `@datasource`, `start` when unset. */\n getOpenMode(): TDataSourceOpenMode {\n const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({\n target: this.constructor,\n });\n\n return metadata?.open?.on ?? DataSourceOpenModes.START;\n }\n\n isOpenDeferred(): boolean {\n return this.getOpenMode() === DataSourceOpenModes.FIRST_USE;\n }\n\n /** The `open.timeoutMs` of `@datasource` (ms; `0` waits for ever), 60 s when unset. */\n getOpenTimeoutMs(): number {\n const metadata = MetadataRegistry.getInstance().getDataSourceMetadata({\n target: this.constructor,\n });\n\n return metadata?.open?.timeoutMs ?? DataSourceOpenDefaults.TIMEOUT_MS;\n }\n\n /**\n * Whether the datasource is open. One that opens on first use: after the first use has finished, until `close()`. One that\n * opens at start: from the moment the application has started it, until `close()`.\n */\n isOpen(): boolean {\n if (this.isShutDown) {\n return false;\n }\n\n return this.isOpenDeferred() ? this.isOpened : true;\n }\n\n /** Whether the first use is opening the datasource right now. */\n isOpening(): boolean {\n return this.opening !== undefined;\n }\n\n /** Whether `close()` has begun. A datasource that opens on first use is not reopened after it. */\n isClosed(): boolean {\n return this.isShutDown;\n }\n\n /**\n * What the application boot calls to get the handles it passes to `configure()` of a datasource that opens at start. Keyed by a\n * symbol the package does not export, so nothing else can obtain the handles: see {@link OPENING_HANDLES}.\n */\n [OPENING_HANDLES](): IDataSourceOpening {\n return this.createOpening();\n }\n\n /**\n * The handles `configure()` gets as its second argument, in both modes. The root has no connector, client or transaction to\n * hand out; a family that has them overrides this. Protected: the only ways out are the argument of `configure()` and the\n * boot's private key.\n */\n protected createOpening(): IDataSourceOpening {\n const refuse = (member: string): never =>\n NotSupportedUtility.throwNotSupported({\n scope: this.constructor.name,\n feature: `opening.${member}`,\n logger: this.logger,\n });\n\n return {\n getConnector: () => refuse('getConnector'),\n getClient: () => refuse('getClient'),\n beginTransaction: () => Promise.resolve().then(() => refuse('beginTransaction')),\n };\n }\n\n /**\n * The boot's replacement for `configure()` on a datasource that opens on first use: records the options and opens nothing.\n * Refused for a family that cannot honour it.\n */\n deferOpen(opts: { options?: ConfigurableOptions }): void {\n if (!this.supportsDeferredOpen()) {\n throw getError({\n message: `[${this.constructor.name}][deferOpen] open: 'first-use' is not supported by this datasource family | Use open: { on: 'start' }, or remove the option`,\n });\n }\n\n this.deferredOptions = opts.options;\n }\n\n /**\n * Resolves once the datasource is open. At once for one that opens with the application. Otherwise the first caller\n * starts `configure()` and the rest await the same promise, so it runs once; a failure rejects all of them, undoes what the\n * failed `configure()` left ({@link discardPartialOpen}) and clears the slot, so the next call opens afresh. After\n * `close()` it rejects: a stopped application does not reopen its datasources.\n */\n ensureOpen(): Promise<void> {\n if (!this.isOpenDeferred()) {\n return Promise.resolve();\n }\n\n // Closed first: a call after `close()` is told so, whether or not the datasource had been opened.\n if (this.isShutDown) {\n return Promise.reject(\n getError({\n message: `[${this.constructor.name}][ensureOpen] The datasource is closed | It opens on first use only before close()`,\n }),\n );\n }\n\n if (this.isOpened) {\n return Promise.resolve();\n }\n\n if (this.abandoned) {\n return Promise.reject(\n getError({\n message: `[${this.constructor.name}][ensureOpen] The previous open is still running after its timeout | It is retried once it has settled`,\n }),\n );\n }\n\n this.opening ??= this.runOpen();\n\n return this.opening;\n }\n\n private async runOpen(): Promise<void> {\n const timeoutMs = this.getOpenTimeoutMs();\n const work = Promise.resolve().then(() =>\n this.configure(this.deferredOptions, this.createOpening()),\n );\n let timer: ReturnType<typeof setTimeout> | undefined;\n const expired = new Promise<typeof OPEN_TIMED_OUT>((resolve) => {\n if (timeoutMs > 0) {\n timer = setTimeout(() => resolve(OPEN_TIMED_OUT), timeoutMs);\n }\n });\n\n try {\n const outcome = await Promise.race([work.then(() => OPEN_DONE), expired]);\n\n if (outcome === OPEN_TIMED_OUT) {\n this.abandoned = this.settleAbandoned({ work });\n\n throw getError({\n message: `[${this.constructor.name}][ensureOpen] The open did not finish within ${timeoutMs} ms | Does configure() await the datasource (a repository, ensureOpen)? Use the opening argument inside configure()`,\n });\n }\n\n this.isOpened = true;\n } catch (error) {\n await this.discardOpenAttempt();\n\n throw error;\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n\n this.opening = undefined;\n }\n }\n\n /** When an abandoned open finally settles, whatever it built is closed (it was never published) and retries are allowed again. */\n private async settleAbandoned(opts: { work: Promise<unknown> }): Promise<void> {\n try {\n await opts.work;\n // eslint-disable-next-line venizia/no-silent-catch -- the abandoned attempt's own outcome was already reported by the timeout; only its clean-up matters now\n } catch {\n // Falls through to the clean-up.\n }\n\n await this.discardOpenAttempt();\n this.abandoned = undefined;\n }\n\n private async discardOpenAttempt(): Promise<void> {\n try {\n await this.discardPartialOpen();\n // eslint-disable-next-line venizia/no-silent-catch -- the open's own error is what the caller must see: a failed clean-up is logged, never thrown over it\n } catch (cleanupError) {\n this.logger\n .for(this.ensureOpen.name)\n .warn('Clean-up after a failed open also failed | error: %s', cleanupError);\n }\n }\n\n /** Undoes what a `configure()` that threw left behind, so the next open starts clean. The root holds nothing; a family that keeps a client overrides it. */\n protected discardPartialOpen(): ValueOrPromise<void> {}\n\n /**\n * Waits for an open in flight and refuses any later one. A family's `close()` calls it first, so a stop that arrives\n * during the first use closes what that open built instead of racing it.\n */\n protected async settleOpening(): Promise<void> {\n this.isShutDown = true;\n\n try {\n await this.opening;\n // eslint-disable-next-line venizia/no-silent-catch -- the failed open was reported to its own waiters; stopping goes on\n } catch (openError) {\n this.logger\n .for(this.close.name)\n .debug('The open in flight failed while stopping | error: %s', openError);\n }\n }\n\n getSettings() {\n return this.settings;\n }\n\n getSchema(): Schema {\n if (!this.schema) {\n throw getError({\n message: `[${this.constructor.name}] Schema not initialized. Override getSchema() or provide schema in constructor.`,\n });\n }\n\n return this.schema;\n }\n\n /** Capability probe, overridden by connectors that support it (e.g. postgres reports `{ transactions: true }`). */\n getCapabilities(): IDataSourceCapabilities {\n return { transactions: false };\n }\n\n /** Nothing to release at this root; a family that holds a connection overrides it. */\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /** Defaults to throwing NotSupported - only connectors with real transaction support override this; async so callers get a rejected promise, not a synchronous throw that skips try/catch. */\n async beginTransaction(_opts?: ITransactionOptions): Promise<ITransaction> {\n return NotSupportedUtility.throwNotSupported({\n scope: this.constructor.name,\n feature: 'Transactions',\n logger: this.logger,\n });\n }\n\n /** Model classes bound to this datasource via `@repository` metadata - paradigm-free (no schema/relation resolution). */\n protected getBoundModelClasses(): Array<TClass<unknown>> {\n return MetadataRegistry.getInstance().getModelClasses({\n dataSource: this.constructor as TClass<IDataSource>,\n });\n }\n\n /** Walks model classes bound to this datasource, reads a connector-specific artifact via `read`, and returns a name-keyed registry - skips undefined reads, throws on duplicate names, honors `autoDiscovery: false`. */\n protected discoverDefinitions<TDefinition extends { name: string }>(opts: {\n read: (modelClass: TClass<unknown>) => TDefinition | undefined;\n kind: string;\n }): Record<string, TDefinition> {\n const { read, kind } = opts;\n const logger = this.logger.for(this.discoverDefinitions.name);\n const registry = MetadataRegistry.getInstance();\n\n const metadata = registry.getDataSourceMetadata({ target: this.constructor });\n\n if (metadata?.autoDiscovery === false) {\n logger.debug('Auto-discovery disabled for %s', this.name);\n\n return {};\n }\n\n const modelClasses = this.getBoundModelClasses();\n\n const definitions: Record<string, TDefinition> = {};\n const definitionOwners = new Map<string, string>();\n\n for (const modelClass of modelClasses) {\n const definition = read(modelClass);\n\n if (!definition) {\n logger.warn(\n 'Model has no %s definition | Skipping | Name: %s | Model: %s',\n kind,\n this.name,\n modelClass.name,\n );\n continue;\n }\n\n const existingOwner = definitionOwners.get(definition.name);\n\n if (existingOwner !== undefined && existingOwner !== modelClass.name) {\n throw getError({\n message: `[${this.constructor.name}][discoverDefinitions] Duplicate ${kind} name '${definition.name}' | Name: ${this.name} | Classes: ${existingOwner}, ${modelClass.name}`,\n });\n }\n\n definitionOwners.set(definition.name, modelClass.name);\n definitions[definition.name] = definition;\n }\n\n const names = Object.keys(definitions);\n logger.debug(\n 'Detected %s(s) | Name: %s | Count: %s | Names: %j',\n kind,\n this.name,\n names.length,\n names,\n );\n\n return definitions;\n }\n}\n"]}