@venizia/ignis-kernel 0.4.8-5 → 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.
Files changed (69) 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/controller.js +5 -2
  14. package/dist/esm/base/controllers/factory/controller.js.map +1 -1
  15. package/dist/esm/base/controllers/factory/crud/readable.js +2 -1
  16. package/dist/esm/base/controllers/factory/crud/readable.js.map +1 -1
  17. package/dist/esm/base/controllers/factory/definition.d.ts +3 -3
  18. package/dist/esm/base/controllers/factory/definition.js +3 -3
  19. package/dist/esm/base/controllers/factory/definition.js.map +1 -1
  20. package/dist/esm/base/controllers/rest/abstract.js +5 -0
  21. package/dist/esm/base/controllers/rest/abstract.js.map +1 -1
  22. package/dist/esm/base/datasources/abstract.d.ts +69 -2
  23. package/dist/esm/base/datasources/abstract.js +186 -1
  24. package/dist/esm/base/datasources/abstract.js.map +1 -1
  25. package/dist/esm/base/datasources/common/types.d.ts +60 -1
  26. package/dist/esm/base/datasources/common/types.js +14 -0
  27. package/dist/esm/base/datasources/common/types.js.map +1 -1
  28. package/dist/esm/base/datasources/opening-handles.d.ts +8 -0
  29. package/dist/esm/base/datasources/opening-handles.js +8 -0
  30. package/dist/esm/base/datasources/opening-handles.js.map +1 -0
  31. package/dist/esm/base/metadata/persistents.js +20 -1
  32. package/dist/esm/base/metadata/persistents.js.map +1 -1
  33. package/dist/esm/base/middlewares/app-error/app-error.middleware.js +12 -1
  34. package/dist/esm/base/middlewares/app-error/app-error.middleware.js.map +1 -1
  35. package/dist/esm/base/middlewares/app-error/common/types.d.ts +10 -8
  36. package/dist/esm/base/middlewares/app-error/common/types.js.map +1 -1
  37. package/dist/esm/base/middlewares/app-error/database.handler.js +14 -14
  38. package/dist/esm/base/middlewares/app-error/database.handler.js.map +1 -1
  39. package/dist/esm/base/middlewares/app-error/index.d.ts +2 -0
  40. package/dist/esm/base/middlewares/app-error/index.js +1 -0
  41. package/dist/esm/base/middlewares/app-error/index.js.map +1 -1
  42. package/dist/esm/base/middlewares/app-error/postgres-errors.d.ts +20 -0
  43. package/dist/esm/base/middlewares/app-error/postgres-errors.js +74 -0
  44. package/dist/esm/base/middlewares/app-error/postgres-errors.js.map +1 -0
  45. package/dist/esm/base/models/base.d.ts +0 -2
  46. package/dist/esm/base/models/base.js +0 -4
  47. package/dist/esm/base/models/base.js.map +1 -1
  48. package/dist/esm/base/models/common/constants.d.ts +9 -0
  49. package/dist/esm/base/models/common/constants.js +15 -0
  50. package/dist/esm/base/models/common/constants.js.map +1 -1
  51. package/dist/esm/base/repositories/common/request-filter-guard.d.ts +52 -2
  52. package/dist/esm/base/repositories/common/request-filter-guard.js +110 -25
  53. package/dist/esm/base/repositories/common/request-filter-guard.js.map +1 -1
  54. package/dist/esm/base/repositories/core/abstract.js +1 -1
  55. package/dist/esm/base/repositories/core/abstract.js.map +1 -1
  56. package/dist/esm/common/statuses/common.d.ts +8 -1
  57. package/dist/esm/common/statuses/common.js +24 -8
  58. package/dist/esm/common/statuses/common.js.map +1 -1
  59. package/dist/esm/helpers/inversion/common/types/model.d.ts +12 -2
  60. package/dist/esm/helpers/inversion/common/types/model.js.map +1 -1
  61. package/dist/esm/helpers/inversion/common/types/persistence.d.ts +3 -1
  62. package/dist/esm/helpers/inversion/common/types/persistence.js.map +1 -1
  63. package/dist/esm/repository.d.ts +3 -1
  64. package/dist/esm/repository.js +3 -1
  65. package/dist/esm/repository.js.map +1 -1
  66. package/dist/esm/statuses.d.ts +8 -0
  67. package/dist/esm/statuses.js +8 -0
  68. package/dist/esm/statuses.js.map +1 -0
  69. package/package.json +9 -5
@@ -1 +1 @@
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,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAEnD,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,KAA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,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 { 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 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,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,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 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"]}
@@ -5,6 +5,12 @@ import { DatabaseErrorHandler } from './database.handler.js';
5
5
  import { ApplicationErrorTypes, DATABASE_RETRYABLE_ERROR_CODE, DATABASE_RETRYABLE_ERROR_MESSAGE, } from './definition.js';
6
6
  import { ZodErrorHandler } from './zod.handler.js';
7
7
  const DEFAULT_INTERNAL_ERROR_MESSAGE = 'Internal Server Error';
8
+ /**
9
+ * Set by `ApplicationError.fromUnknown` on an error it wrapped from a value with no usable HTTP status. Read by registry key, so
10
+ * kernel and inversion share no export. Such an error carries a `statusCode` (500) like any `ApplicationError`, yet its message
11
+ * came from a foreign value, so it is answered as UNEXPECTED: generic to the client in production.
12
+ */
13
+ const UNEXPECTED_ERROR_MARKER = Symbol.for('@venizia/ignis-inversion:unexpected-error');
8
14
  /** An intentional error's throw site is still worth naming; its caller chain is framework plumbing, so it gets a smaller budget than an unexpected one. */
9
15
  const DEFAULT_INTENTIONAL_STACK_FRAMES = 5;
10
16
  const DEFAULT_UNEXPECTED_STACK_FRAMES = 10;
@@ -132,6 +138,9 @@ export class BaseAppErrorMiddleware extends BaseHelper {
132
138
  if (DatabaseErrorHandler.isRetryableDatabaseError({ error })) {
133
139
  return ApplicationErrorTypes.DATABASE_RETRYABLE;
134
140
  }
141
+ if (UNEXPECTED_ERROR_MARKER in error) {
142
+ return ApplicationErrorTypes.UNEXPECTED;
143
+ }
135
144
  if ('statusCode' in error || this.readClientErrorStatus({ error }) !== undefined) {
136
145
  return ApplicationErrorTypes.INTENTIONAL;
137
146
  }
@@ -161,7 +170,9 @@ export class BaseAppErrorMiddleware extends BaseHelper {
161
170
  // Fallback for a FOREIGN error that sets its own code; an ApplicationError reports via `normalized`.
162
171
  const code = messageCode ??
163
172
  MessageCode.resolve('messageCode' in error ? error.messageCode : undefined);
164
- const normalized = 'normalized' in error
173
+ // An error wrapped from a foreign value keeps that value's text in `normalized`: the response must carry the answer chosen
174
+ // here (generic in production), never the wrapped text.
175
+ const normalized = 'normalized' in error && !(UNEXPECTED_ERROR_MARKER in error)
165
176
  ? error.normalized
166
177
  : { text: message, code, args: {} };
167
178
  return { statusCode, message, normalized, type };
@@ -1 +1 @@
1
- {"version":3,"file":"app-error.middleware.js","sourceRoot":"","sources":["../../../../../src/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GAAG,QAAQ,CAAC;YAElD,IAAI,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;YAE7F,MAAM,EAAE,GAAG;gBACT,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;gBAClE,UAAU;gBACV,UAAU,EAAE,IAAI,CAAC,gBAAgB,CAAC,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC;gBAC/D,SAAS;gBACT,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC;gBAC5D,OAAO,EAAE;oBACP,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,GAAG;oBACpB,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,IAAI;oBACtB,KAAK,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;oBAC9C,KAAK,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;iBAC/C;aACF,CAAC;YAEF,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,UAAgD,CAAC,CAAC;QAC9F,CAAC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { ILogger, TLogLevel } from '@venizia/ignis-helpers/core';\nimport type { TNullable } from '@venizia/ignis-helpers/common';\nimport {\n BaseHelper,\n EnvironmentNames,\n LogLevels,\n MessageCode,\n MessageTemplate,\n} from '@venizia/ignis-helpers/core';\nimport { HTTP, RedactUtility } from '@venizia/ignis-helpers/common';\nimport type { IProvider } from '@venizia/ignis-inversion';\nimport type { Context } from 'hono';\nimport type { ErrorHandler, HTTPResponseError } from 'hono/types';\nimport { REQUEST_ID_KEY } from '../common';\nimport { DatabaseErrorHandler } from './database.handler';\nimport {\n ApplicationErrorTypes,\n DATABASE_RETRYABLE_ERROR_CODE,\n DATABASE_RETRYABLE_ERROR_MESSAGE,\n} from './definition';\nimport type { IResolvedApplicationError, TApplicationErrorType } from './common';\nimport { ZodErrorHandler } from './zod.handler';\n\nconst DEFAULT_INTERNAL_ERROR_MESSAGE = 'Internal Server Error';\n\n/** An intentional error's throw site is still worth naming; its caller chain is framework plumbing, so it gets a smaller budget than an unexpected one. */\nconst DEFAULT_INTENTIONAL_STACK_FRAMES = 5;\nconst DEFAULT_UNEXPECTED_STACK_FRAMES = 10;\n\n/** How a thrown error is rendered into the log line. Must never throw - a throw inside the error handler turns a handled failure into an unhandled one. */\nexport type TErrorLogFormatter = (opts: {\n error: unknown;\n messageCode?: string;\n extra?: Record<string, unknown>;\n includeStack?: boolean;\n maxStackFrames?: number;\n}) => string;\n\ntype TThrown = Error | HTTPResponseError;\ntype TDatabaseClientError = ReturnType<typeof DatabaseErrorHandler.isDatabaseClientError>;\n\n/**\n * Renders a value into one log-safe fragment.\n *\n * Redaction is not optional here. This runs on `extra`, which is whatever a throw site chose to\n * attach - `getError({ extra: { apiKey } })` is a shape applications write - and in a Worker this\n * fragment lands in the browser console. `toJsonSafe` masks secret-shaped keys; a hand-rolled\n * `JSON.stringify` does not, and the server path has always redacted.\n *\n * The BigInt replacer stays: `toJsonSafe` leaves BigInt intact and `JSON.stringify` refuses it, so\n * without this a single BigInt would collapse the whole fragment to the marker below. Anything else\n * it refuses yields that marker rather than a throw - this is the last-resort error handler, where a\n * throw turns a handled failure into an unhandled one.\n */\nconst renderValue = (opts: { value: unknown }): string => {\n const { value } = opts;\n\n if (typeof value === 'string') {\n return value;\n }\n\n const safe = RedactUtility.toJsonSafe({ value });\n\n try {\n return JSON.stringify(safe) ?? String(value);\n } catch {\n // A replacer is 6x the cost of plain stringify and deopts every key, so it is installed only\n // once BigInt has actually thrown - the case it exists for, and the rare one.\n try {\n const rendered = JSON.stringify(safe, (_key, entry: unknown) =>\n typeof entry === 'bigint' ? entry.toString() : entry,\n );\n\n return rendered ?? String(value);\n // eslint-disable-next-line venizia/no-silent-catch -- the marker returned below is the report; the only thing lost is the unrenderable value's text in the log line\n } catch {\n // Not a swallowed failure: this marker IS the report, and it lands in the log line the caller\n // is building.\n return '[unrenderable]';\n }\n }\n};\n\n/**\n * Hono `onError`: ZodError -> 422, DB client error -> 400, retryable conflict -> 409, `getError` ->\n * its own status, else 500. Browser-pure: the two reads that need a host - the ambient environment\n * name and the error formatter - are constructor OPTIONS, not methods to subclass.\n *\n * They were hooks once, and three subclasses existed to answer them and nothing else. A class seam\n * is also unreachable from application code, so the browser example had to fake the environment with\n * a Hono middleware assigning `context.env`. `@venizia/ignis`'s `AppErrorMiddleware` now just\n * supplies `process.env.NODE_ENV` and `ErrorPrettier` as options.\n */\nexport class BaseAppErrorMiddleware extends BaseHelper implements IProvider<ErrorHandler> {\n private rootKey: TNullable<string>;\n private intentionalStackFrames: number;\n private unexpectedStackFrames: number;\n\n /**\n * How this host reads its ambient environment name, and the ONE option that says whether it has\n * one at all: absent means it does not (a browser), so an unresolved name is by design; present\n * but returning `undefined` means a host that should have one is misconfigured. Either way\n * {@link isProduction} fails closed.\n *\n * A function, not a string: `process.env.NODE_ENV` has to be read per request, since a test - and\n * a `--env-file` reload - can change it after the middleware is built.\n */\n private readonly environment?: () => string | undefined;\n\n /** Replaces {@link renderErrorForLog} - `@venizia/ignis` passes `ErrorPrettier`, which reaches `node:util` and so cannot live here. */\n private readonly formatErrorOverride?: TErrorLogFormatter;\n\n constructor(opts?: {\n logger?: ILogger;\n rootKey?: string;\n intentionalStackFrames?: number;\n unexpectedStackFrames?: number;\n environment?: () => string | undefined;\n formatError?: TErrorLogFormatter;\n }) {\n // `new.target`, not a literal: a subclass logs under its own name, so `@venizia/ignis`'s\n // `AppErrorMiddleware` keeps the scope it has always logged under.\n super({ scope: new.target.name });\n\n this.rootKey = opts?.rootKey;\n this.intentionalStackFrames = opts?.intentionalStackFrames ?? DEFAULT_INTENTIONAL_STACK_FRAMES;\n this.unexpectedStackFrames = opts?.unexpectedStackFrames ?? DEFAULT_UNEXPECTED_STACK_FRAMES;\n this.environment = opts?.environment;\n this.formatErrorOverride = opts?.formatError;\n\n if (opts?.logger) {\n this.logger = opts.logger;\n }\n }\n\n /** Renders a thrown error for the log, through the `formatError` option when one was given. */\n protected formatError(opts: {\n error: unknown;\n messageCode?: string;\n extra?: Record<string, unknown>;\n includeStack?: boolean;\n maxStackFrames?: number;\n }): string {\n return (this.formatErrorOverride ?? ((o) => this.renderErrorForLog(o)))(opts);\n }\n\n /**\n * The default log rendering: pure and deliberately small, so the whole middleware stays\n * browser-pure.\n *\n * Must never throw, cycles included: a throw inside the error handler turns a handled failure\n * into an unhandled one.\n */\n private renderErrorForLog(opts: {\n error: unknown;\n messageCode?: string;\n extra?: Record<string, unknown>;\n includeStack?: boolean;\n maxStackFrames?: number;\n }): string {\n const { error, messageCode, extra, includeStack = true, maxStackFrames } = opts;\n const thrown = error as Partial<Error> | null | undefined;\n const lines: Array<string> = [];\n\n if (typeof thrown?.name === 'string') {\n lines.push(`name: ${thrown.name}`);\n }\n\n lines.push(\n `message: ${typeof thrown?.message === 'string' ? thrown.message : renderValue({ value: error })}`,\n );\n\n if (messageCode) {\n lines.push(`code: ${messageCode}`);\n }\n\n if (extra && Object.keys(extra).length > 0) {\n lines.push(`extra: ${renderValue({ value: extra })}`);\n }\n\n if (includeStack && typeof thrown?.stack === 'string') {\n const frames = thrown.stack.split('\\n').filter((line) => line.trimStart().startsWith('at '));\n const capped = maxStackFrames === undefined ? frames : frames.slice(0, maxStackFrames);\n\n if (capped.length > 0) {\n lines.push(`stack:\\n${capped.join('\\n')}`);\n }\n }\n\n return lines.map((line) => `- ${line}`).join('\\n');\n }\n\n private withRootKey(payload: object) {\n return this.rootKey ? { [this.rootKey]: payload } : payload;\n }\n\n /** Fail-closed: an unset or unrecognized env is production. */\n private isProduction(opts: { context: Context; error: TThrown; requestId: string }): boolean {\n const { context, error, requestId } = opts;\n const env = [context.env?.NODE_ENV, this.environment?.()].find(Boolean);\n\n if (!env) {\n // Only a host that HAS an ambient environment can be misconfigured about it. In a browser the\n // absence is by design, and shouting it at error level on every request buries the error the\n // reader is actually looking at. Both paths still sanitize.\n if (this.environment) {\n this.logger.error(\n '[%s] INVALID ENV IDENTIFIER | env: %s | path: %s | method: %s | url: %s\\n%s',\n requestId,\n env,\n context.req.path,\n context.req.method,\n context.req.url,\n this.formatError({ error }),\n );\n } else {\n this.logger.debug(\n '[%s] No ambient environment - sanitizing as production | path: %s | set NODE_ENV on the Hono env binding to opt out',\n requestId,\n context.req.path,\n );\n }\n\n return true;\n }\n\n return !EnvironmentNames.DEVELOPMENT_ENVS.has(env.toLowerCase());\n }\n\n private classify(opts: { error: TThrown; dbError: TDatabaseClientError }): TApplicationErrorType {\n const { error, dbError } = opts;\n\n if (dbError.isClientError) {\n return ApplicationErrorTypes.DATABASE_CLIENT;\n }\n\n if (DatabaseErrorHandler.isRetryableDatabaseError({ error })) {\n return ApplicationErrorTypes.DATABASE_RETRYABLE;\n }\n\n if ('statusCode' in error || this.readClientErrorStatus({ error }) !== undefined) {\n return ApplicationErrorTypes.INTENTIONAL;\n }\n\n return ApplicationErrorTypes.UNEXPECTED;\n }\n\n /** Hono's `HTTPException` carries `status`, not `statusCode`. Only a 4xx is the caller's fault; a 5xx stays unexpected, so its message is sanitized. */\n private readClientErrorStatus(opts: { error: TThrown }): number | undefined {\n const { error } = opts;\n\n if (!('getResponse' in error) || !('status' in error) || typeof error.status !== 'number') {\n return undefined;\n }\n\n const isClientError =\n error.status >= HTTP.ResultCodes.RS_4.BadRequest &&\n error.status < HTTP.ResultCodes.RS_5.InternalServerError;\n\n return isClientError ? error.status : undefined;\n }\n\n /** `getError` sets `statusCode`, and it wins when a foreign error carries both. Neither usable is a 500. */\n private readIntentionalStatus(opts: { error: TThrown }): number {\n const { error } = opts;\n\n if ('statusCode' in error && typeof error.statusCode === 'number') {\n return error.statusCode;\n }\n\n return this.readClientErrorStatus({ error }) ?? HTTP.ResultCodes.RS_5.InternalServerError;\n }\n\n /** An ApplicationError's `normalized` is authoritative - a `transform` may have reworded `text`. */\n private build(opts: {\n error: TThrown;\n statusCode: number;\n message: string;\n type: TApplicationErrorType;\n messageCode?: string;\n }): IResolvedApplicationError {\n const { error, statusCode, message, type, messageCode } = opts;\n\n // Fallback for a FOREIGN error that sets its own code; an ApplicationError reports via `normalized`.\n const code =\n messageCode ??\n MessageCode.resolve('messageCode' in error ? (error.messageCode as string) : undefined);\n\n const normalized =\n 'normalized' in error\n ? (error.normalized as IResolvedApplicationError['normalized'])\n : { text: message, code, args: {} };\n\n return { statusCode, message, normalized, type };\n }\n\n private resolve(opts: { error: TThrown; isProduction: boolean }): IResolvedApplicationError {\n const { error, isProduction } = opts;\n const dbError = DatabaseErrorHandler.isDatabaseClientError({ error, isProduction });\n const type = this.classify({ error, dbError });\n\n switch (type) {\n case ApplicationErrorTypes.DATABASE_CLIENT: {\n return this.build({\n error,\n type,\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n // The fallback is unreachable today; it keeps the driver's raw text from ever surfacing.\n message: dbError.message ?? DEFAULT_INTERNAL_ERROR_MESSAGE,\n });\n }\n\n case ApplicationErrorTypes.DATABASE_RETRYABLE: {\n return this.build({\n error,\n type,\n statusCode: HTTP.ResultCodes.RS_4.Conflict,\n message: DATABASE_RETRYABLE_ERROR_MESSAGE,\n messageCode: DATABASE_RETRYABLE_ERROR_CODE,\n });\n }\n\n case ApplicationErrorTypes.INTENTIONAL: {\n return this.build({\n error,\n type,\n statusCode: this.readIntentionalStatus({ error }),\n message: error.message,\n });\n }\n\n default: {\n return this.build({\n error,\n type: ApplicationErrorTypes.UNEXPECTED,\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n // Never leak a raw message - it may carry SQL, schema names or connection details.\n message: isProduction ? DEFAULT_INTERNAL_ERROR_MESSAGE : error.message,\n });\n }\n }\n }\n\n /** A throw site may set `logLevel` via `getError`; anything unset or malformed logs at `error`. */\n private resolveLogLevel(opts: { error: TThrown }): TLogLevel {\n const candidate = (opts.error as { logLevel?: unknown }).logLevel;\n\n if (typeof candidate === 'string' && LogLevels.isValid(candidate)) {\n return candidate as TLogLevel;\n }\n\n return LogLevels.ERROR;\n }\n\n /** The one place a thrown error reaches the log - called once the status is known, so it carries it. */\n private logError(opts: {\n error: TThrown;\n context: Context;\n requestId: string;\n statusCode: number;\n messageCode: string;\n type?: TApplicationErrorType;\n }) {\n const { error, context, requestId, statusCode, messageCode, type } = opts;\n\n this.logger.log(\n this.resolveLogLevel({ error }),\n '[%s] REQUEST ERROR | %s | %s %s\\n%s',\n requestId,\n statusCode,\n context.req.method,\n context.req.url,\n this.formatError({\n error,\n // The default code means \"no code\" - logging it on every error would be a noise line.\n messageCode: messageCode === MessageCode.DEFAULT ? undefined : messageCode,\n extra: 'extra' in error ? (error.extra as Record<string, unknown>) : undefined,\n includeStack: true,\n // An intentional error still needs its throw site; it just does not need the caller chain behind it.\n maxStackFrames:\n type === ApplicationErrorTypes.UNEXPECTED\n ? this.unexpectedStackFrames\n : this.intentionalStackFrames,\n }),\n );\n }\n\n /** Only an intentional error's message is a catalog template; every other branch writes its own text, so it passes through as is. */\n private renderMessage(opts: {\n resolved: IResolvedApplicationError;\n isProduction: boolean;\n requestId: string;\n }): string {\n const { resolved, isProduction, requestId } = opts;\n\n if (resolved.type !== ApplicationErrorTypes.INTENTIONAL) {\n return resolved.message;\n }\n\n const { text, missing } = MessageTemplate.render({\n text: resolved.message,\n args: resolved.normalized.args,\n });\n\n // Production stays silent and renders what it can; anywhere else a missing arg is a throw site to fix.\n if (missing.length > 0 && !isProduction) {\n this.logger.warn(\n '[%s] MESSAGE PLACEHOLDER WITHOUT ARG | code: %s | keys: %s',\n requestId,\n resolved.normalized.code,\n missing.join(', '),\n );\n }\n\n return text;\n }\n\n /**\n * The `extra` a response carries. It is whatever a throw site attached, so it goes through the same redaction the log\n * line uses (always masking in production, whatever the logger switch says), and a server error (5xx) in production\n * carries none: the log has it, a client has no use for it.\n */\n private renderExtra(opts: { error: Error; statusCode: number; isProduction: boolean }): unknown {\n const { error, statusCode, isProduction } = opts;\n\n if (!('extra' in error) || error.extra === undefined) {\n return undefined;\n }\n\n if (isProduction && statusCode >= 500) {\n return this.pickCorrelationIds({ extra: error.extra });\n }\n\n const safe = RedactUtility.toJsonSafe({ value: error.extra, force: isProduction });\n\n // A value `context.json` would refuse (a BigInt) becomes text here, so the authored status survives it.\n try {\n // A nested Error keeps its `stack` through the redaction (the log wants it); a client in production does not get one.\n const text = JSON.stringify(safe, (key, entry: unknown) => {\n if (isProduction && key === 'stack') {\n return undefined;\n }\n\n return typeof entry === 'bigint' ? entry.toString() : entry;\n });\n\n return text === undefined ? undefined : JSON.parse(text);\n // eslint-disable-next-line venizia/no-silent-catch -- the marker returned below is the report: the response carries it where the value would have been\n } catch {\n return '[unrenderable]';\n }\n }\n\n /**\n * What a production server error still carries from `extra`: the correlation ids support needs, `requestId` and\n * `upstreamRequestIds`, and nothing else. Only short strings count (a list of them for the chain), so the allowance\n * cannot carry anything but an id.\n */\n private pickCorrelationIds(opts: { extra: unknown }): Record<string, unknown> | undefined {\n const { extra } = opts;\n\n if (typeof extra !== 'object' || extra === null) {\n return undefined;\n }\n\n const source = extra as Record<string, unknown>;\n const isId = (value: unknown): value is string =>\n typeof value === 'string' && value.length <= 128;\n const picked: Record<string, unknown> = {};\n\n if (isId(source.requestId)) {\n picked.requestId = source.requestId;\n }\n\n const chain = source.upstreamRequestIds;\n\n if (Array.isArray(chain) && chain.length <= 32 && chain.every(isId)) {\n picked.upstreamRequestIds = chain;\n }\n\n return Object.keys(picked).length > 0 ? picked : undefined;\n }\n\n /** The `args` a throw site passes to its message template are data the client may see; secret-shaped keys in them are masked in production, whatever the logger switch says. */\n private renderNormalized(opts: {\n normalized: IResolvedApplicationError['normalized'];\n isProduction: boolean;\n }): IResolvedApplicationError['normalized'] {\n const { normalized, isProduction } = opts;\n\n if (!isProduction || !normalized.args || Object.keys(normalized.args).length === 0) {\n return normalized;\n }\n\n return {\n ...normalized,\n args: RedactUtility.redactSecrets({\n value: normalized.args,\n force: true,\n }) as typeof normalized.args,\n };\n }\n\n value(): ErrorHandler {\n return async (error, context) => {\n const requestId = context.get(REQUEST_ID_KEY);\n const isProduction = this.isProduction({ context, error, requestId });\n\n if (error.name === 'ZodError') {\n const rs = ZodErrorHandler.formatZodError({\n isProduction,\n requestId,\n url: context.req.url,\n path: context.req.path,\n error,\n });\n\n this.logError({\n error,\n context,\n requestId,\n statusCode: rs.statusCode,\n messageCode: rs.response.normalized.code,\n });\n\n return context.json(\n this.withRootKey(rs.response),\n rs.statusCode as Parameters<typeof context.json>[1],\n );\n }\n\n const resolved = this.resolve({ error, isProduction });\n const { statusCode, normalized, type } = resolved;\n\n this.logError({ error, context, requestId, statusCode, messageCode: normalized.code, type });\n\n const rs = {\n message: this.renderMessage({ resolved, isProduction, requestId }),\n statusCode,\n normalized: this.renderNormalized({ normalized, isProduction }),\n requestId,\n extra: this.renderExtra({ error, statusCode, isProduction }),\n details: {\n url: context.req.url,\n path: context.req.path,\n stack: !isProduction ? error.stack : undefined,\n cause: !isProduction ? error.cause : undefined,\n },\n };\n\n return context.json(this.withRootKey(rs), statusCode as Parameters<typeof context.json>[1]);\n };\n }\n}\n"]}
1
+ {"version":3,"file":"app-error.middleware.js","sourceRoot":"","sources":["../../../../../src/base/middlewares/app-error/app-error.middleware.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,SAAS,EACT,WAAW,EACX,eAAe,GAChB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAIpE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,oBAAoB,EAAE,MAAM,oB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C,QAAQ,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;YAE7F,MAAM,EAAE,GAAG;gBACT,OAAO,EAAE,IAAI,CAAC,aAAa,CAAC,EAAE,QAAQ,EAAE,YAAY,EAAE,SAAS,EAAE,CAAC;gBAClE,UAAU;gBACV,UAAU,EAAE,IAAI,CAAC,gBAAgB,CAAC,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC;gBAC/D,SAAS;gBACT,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,CAAC;gBAC5D,OAAO,EAAE;oBACP,GAAG,EAAE,OAAO,CAAC,GAAG,CAAC,GAAG;oBACpB,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,IAAI;oBACtB,KAAK,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;oBAC9C,KAAK,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;iBAC/C;aACF,CAAC;YAEF,OAAO,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,UAAgD,CAAC,CAAC;QAC9F,CAAC,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { ILogger, TLogLevel } from '@venizia/ignis-helpers/core';\nimport type { TNullable } from '@venizia/ignis-helpers/common';\nimport {\n BaseHelper,\n EnvironmentNames,\n LogLevels,\n MessageCode,\n MessageTemplate,\n} from '@venizia/ignis-helpers/core';\nimport { HTTP, RedactUtility } from '@venizia/ignis-helpers/common';\nimport type { IProvider } from '@venizia/ignis-inversion';\nimport type { Context } from 'hono';\nimport type { ErrorHandler, HTTPResponseError } from 'hono/types';\nimport { REQUEST_ID_KEY } from '../common';\nimport { DatabaseErrorHandler } from './database.handler';\nimport {\n ApplicationErrorTypes,\n DATABASE_RETRYABLE_ERROR_CODE,\n DATABASE_RETRYABLE_ERROR_MESSAGE,\n} from './definition';\nimport type { IResolvedApplicationError, TApplicationErrorType } from './common';\nimport { ZodErrorHandler } from './zod.handler';\n\nconst DEFAULT_INTERNAL_ERROR_MESSAGE = 'Internal Server Error';\n\n/**\n * Set by `ApplicationError.fromUnknown` on an error it wrapped from a value with no usable HTTP status. Read by registry key, so\n * kernel and inversion share no export. Such an error carries a `statusCode` (500) like any `ApplicationError`, yet its message\n * came from a foreign value, so it is answered as UNEXPECTED: generic to the client in production.\n */\nconst UNEXPECTED_ERROR_MARKER = Symbol.for('@venizia/ignis-inversion:unexpected-error');\n\n/** An intentional error's throw site is still worth naming; its caller chain is framework plumbing, so it gets a smaller budget than an unexpected one. */\nconst DEFAULT_INTENTIONAL_STACK_FRAMES = 5;\nconst DEFAULT_UNEXPECTED_STACK_FRAMES = 10;\n\n/** How a thrown error is rendered into the log line. Must never throw - a throw inside the error handler turns a handled failure into an unhandled one. */\nexport type TErrorLogFormatter = (opts: {\n error: unknown;\n messageCode?: string;\n extra?: Record<string, unknown>;\n includeStack?: boolean;\n maxStackFrames?: number;\n}) => string;\n\ntype TThrown = Error | HTTPResponseError;\ntype TDatabaseClientError = ReturnType<typeof DatabaseErrorHandler.isDatabaseClientError>;\n\n/**\n * Renders a value into one log-safe fragment.\n *\n * Redaction is not optional here. This runs on `extra`, which is whatever a throw site chose to\n * attach - `getError({ extra: { apiKey } })` is a shape applications write - and in a Worker this\n * fragment lands in the browser console. `toJsonSafe` masks secret-shaped keys; a hand-rolled\n * `JSON.stringify` does not, and the server path has always redacted.\n *\n * The BigInt replacer stays: `toJsonSafe` leaves BigInt intact and `JSON.stringify` refuses it, so\n * without this a single BigInt would collapse the whole fragment to the marker below. Anything else\n * it refuses yields that marker rather than a throw - this is the last-resort error handler, where a\n * throw turns a handled failure into an unhandled one.\n */\nconst renderValue = (opts: { value: unknown }): string => {\n const { value } = opts;\n\n if (typeof value === 'string') {\n return value;\n }\n\n const safe = RedactUtility.toJsonSafe({ value });\n\n try {\n return JSON.stringify(safe) ?? String(value);\n } catch {\n // A replacer is 6x the cost of plain stringify and deopts every key, so it is installed only\n // once BigInt has actually thrown - the case it exists for, and the rare one.\n try {\n const rendered = JSON.stringify(safe, (_key, entry: unknown) =>\n typeof entry === 'bigint' ? entry.toString() : entry,\n );\n\n return rendered ?? String(value);\n // eslint-disable-next-line venizia/no-silent-catch -- the marker returned below is the report; the only thing lost is the unrenderable value's text in the log line\n } catch {\n // Not a swallowed failure: this marker IS the report, and it lands in the log line the caller\n // is building.\n return '[unrenderable]';\n }\n }\n};\n\n/**\n * Hono `onError`: ZodError -> 422, DB client error -> 400, retryable conflict -> 409, `getError` ->\n * its own status, else 500. Browser-pure: the two reads that need a host - the ambient environment\n * name and the error formatter - are constructor OPTIONS, not methods to subclass.\n *\n * They were hooks once, and three subclasses existed to answer them and nothing else. A class seam\n * is also unreachable from application code, so the browser example had to fake the environment with\n * a Hono middleware assigning `context.env`. `@venizia/ignis`'s `AppErrorMiddleware` now just\n * supplies `process.env.NODE_ENV` and `ErrorPrettier` as options.\n */\nexport class BaseAppErrorMiddleware extends BaseHelper implements IProvider<ErrorHandler> {\n private rootKey: TNullable<string>;\n private intentionalStackFrames: number;\n private unexpectedStackFrames: number;\n\n /**\n * How this host reads its ambient environment name, and the ONE option that says whether it has\n * one at all: absent means it does not (a browser), so an unresolved name is by design; present\n * but returning `undefined` means a host that should have one is misconfigured. Either way\n * {@link isProduction} fails closed.\n *\n * A function, not a string: `process.env.NODE_ENV` has to be read per request, since a test - and\n * a `--env-file` reload - can change it after the middleware is built.\n */\n private readonly environment?: () => string | undefined;\n\n /** Replaces {@link renderErrorForLog} - `@venizia/ignis` passes `ErrorPrettier`, which reaches `node:util` and so cannot live here. */\n private readonly formatErrorOverride?: TErrorLogFormatter;\n\n constructor(opts?: {\n logger?: ILogger;\n rootKey?: string;\n intentionalStackFrames?: number;\n unexpectedStackFrames?: number;\n environment?: () => string | undefined;\n formatError?: TErrorLogFormatter;\n }) {\n // `new.target`, not a literal: a subclass logs under its own name, so `@venizia/ignis`'s\n // `AppErrorMiddleware` keeps the scope it has always logged under.\n super({ scope: new.target.name });\n\n this.rootKey = opts?.rootKey;\n this.intentionalStackFrames = opts?.intentionalStackFrames ?? DEFAULT_INTENTIONAL_STACK_FRAMES;\n this.unexpectedStackFrames = opts?.unexpectedStackFrames ?? DEFAULT_UNEXPECTED_STACK_FRAMES;\n this.environment = opts?.environment;\n this.formatErrorOverride = opts?.formatError;\n\n if (opts?.logger) {\n this.logger = opts.logger;\n }\n }\n\n /** Renders a thrown error for the log, through the `formatError` option when one was given. */\n protected formatError(opts: {\n error: unknown;\n messageCode?: string;\n extra?: Record<string, unknown>;\n includeStack?: boolean;\n maxStackFrames?: number;\n }): string {\n return (this.formatErrorOverride ?? ((o) => this.renderErrorForLog(o)))(opts);\n }\n\n /**\n * The default log rendering: pure and deliberately small, so the whole middleware stays\n * browser-pure.\n *\n * Must never throw, cycles included: a throw inside the error handler turns a handled failure\n * into an unhandled one.\n */\n private renderErrorForLog(opts: {\n error: unknown;\n messageCode?: string;\n extra?: Record<string, unknown>;\n includeStack?: boolean;\n maxStackFrames?: number;\n }): string {\n const { error, messageCode, extra, includeStack = true, maxStackFrames } = opts;\n const thrown = error as Partial<Error> | null | undefined;\n const lines: Array<string> = [];\n\n if (typeof thrown?.name === 'string') {\n lines.push(`name: ${thrown.name}`);\n }\n\n lines.push(\n `message: ${typeof thrown?.message === 'string' ? thrown.message : renderValue({ value: error })}`,\n );\n\n if (messageCode) {\n lines.push(`code: ${messageCode}`);\n }\n\n if (extra && Object.keys(extra).length > 0) {\n lines.push(`extra: ${renderValue({ value: extra })}`);\n }\n\n if (includeStack && typeof thrown?.stack === 'string') {\n const frames = thrown.stack.split('\\n').filter((line) => line.trimStart().startsWith('at '));\n const capped = maxStackFrames === undefined ? frames : frames.slice(0, maxStackFrames);\n\n if (capped.length > 0) {\n lines.push(`stack:\\n${capped.join('\\n')}`);\n }\n }\n\n return lines.map((line) => `- ${line}`).join('\\n');\n }\n\n private withRootKey(payload: object) {\n return this.rootKey ? { [this.rootKey]: payload } : payload;\n }\n\n /** Fail-closed: an unset or unrecognized env is production. */\n private isProduction(opts: { context: Context; error: TThrown; requestId: string }): boolean {\n const { context, error, requestId } = opts;\n const env = [context.env?.NODE_ENV, this.environment?.()].find(Boolean);\n\n if (!env) {\n // Only a host that HAS an ambient environment can be misconfigured about it. In a browser the\n // absence is by design, and shouting it at error level on every request buries the error the\n // reader is actually looking at. Both paths still sanitize.\n if (this.environment) {\n this.logger.error(\n '[%s] INVALID ENV IDENTIFIER | env: %s | path: %s | method: %s | url: %s\\n%s',\n requestId,\n env,\n context.req.path,\n context.req.method,\n context.req.url,\n this.formatError({ error }),\n );\n } else {\n this.logger.debug(\n '[%s] No ambient environment - sanitizing as production | path: %s | set NODE_ENV on the Hono env binding to opt out',\n requestId,\n context.req.path,\n );\n }\n\n return true;\n }\n\n return !EnvironmentNames.DEVELOPMENT_ENVS.has(env.toLowerCase());\n }\n\n private classify(opts: { error: TThrown; dbError: TDatabaseClientError }): TApplicationErrorType {\n const { error, dbError } = opts;\n\n if (dbError.isClientError) {\n return ApplicationErrorTypes.DATABASE_CLIENT;\n }\n\n if (DatabaseErrorHandler.isRetryableDatabaseError({ error })) {\n return ApplicationErrorTypes.DATABASE_RETRYABLE;\n }\n\n if (UNEXPECTED_ERROR_MARKER in error) {\n return ApplicationErrorTypes.UNEXPECTED;\n }\n\n if ('statusCode' in error || this.readClientErrorStatus({ error }) !== undefined) {\n return ApplicationErrorTypes.INTENTIONAL;\n }\n\n return ApplicationErrorTypes.UNEXPECTED;\n }\n\n /** Hono's `HTTPException` carries `status`, not `statusCode`. Only a 4xx is the caller's fault; a 5xx stays unexpected, so its message is sanitized. */\n private readClientErrorStatus(opts: { error: TThrown }): number | undefined {\n const { error } = opts;\n\n if (!('getResponse' in error) || !('status' in error) || typeof error.status !== 'number') {\n return undefined;\n }\n\n const isClientError =\n error.status >= HTTP.ResultCodes.RS_4.BadRequest &&\n error.status < HTTP.ResultCodes.RS_5.InternalServerError;\n\n return isClientError ? error.status : undefined;\n }\n\n /** `getError` sets `statusCode`, and it wins when a foreign error carries both. Neither usable is a 500. */\n private readIntentionalStatus(opts: { error: TThrown }): number {\n const { error } = opts;\n\n if ('statusCode' in error && typeof error.statusCode === 'number') {\n return error.statusCode;\n }\n\n return this.readClientErrorStatus({ error }) ?? HTTP.ResultCodes.RS_5.InternalServerError;\n }\n\n /** An ApplicationError's `normalized` is authoritative - a `transform` may have reworded `text`. */\n private build(opts: {\n error: TThrown;\n statusCode: number;\n message: string;\n type: TApplicationErrorType;\n messageCode?: string;\n }): IResolvedApplicationError {\n const { error, statusCode, message, type, messageCode } = opts;\n\n // Fallback for a FOREIGN error that sets its own code; an ApplicationError reports via `normalized`.\n const code =\n messageCode ??\n MessageCode.resolve('messageCode' in error ? (error.messageCode as string) : undefined);\n\n // An error wrapped from a foreign value keeps that value's text in `normalized`: the response must carry the answer chosen\n // here (generic in production), never the wrapped text.\n const normalized =\n 'normalized' in error && !(UNEXPECTED_ERROR_MARKER in error)\n ? (error.normalized as IResolvedApplicationError['normalized'])\n : { text: message, code, args: {} };\n\n return { statusCode, message, normalized, type };\n }\n\n private resolve(opts: { error: TThrown; isProduction: boolean }): IResolvedApplicationError {\n const { error, isProduction } = opts;\n const dbError = DatabaseErrorHandler.isDatabaseClientError({ error, isProduction });\n const type = this.classify({ error, dbError });\n\n switch (type) {\n case ApplicationErrorTypes.DATABASE_CLIENT: {\n return this.build({\n error,\n type,\n statusCode: HTTP.ResultCodes.RS_4.BadRequest,\n // The fallback is unreachable today; it keeps the driver's raw text from ever surfacing.\n message: dbError.message ?? DEFAULT_INTERNAL_ERROR_MESSAGE,\n });\n }\n\n case ApplicationErrorTypes.DATABASE_RETRYABLE: {\n return this.build({\n error,\n type,\n statusCode: HTTP.ResultCodes.RS_4.Conflict,\n message: DATABASE_RETRYABLE_ERROR_MESSAGE,\n messageCode: DATABASE_RETRYABLE_ERROR_CODE,\n });\n }\n\n case ApplicationErrorTypes.INTENTIONAL: {\n return this.build({\n error,\n type,\n statusCode: this.readIntentionalStatus({ error }),\n message: error.message,\n });\n }\n\n default: {\n return this.build({\n error,\n type: ApplicationErrorTypes.UNEXPECTED,\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n // Never leak a raw message - it may carry SQL, schema names or connection details.\n message: isProduction ? DEFAULT_INTERNAL_ERROR_MESSAGE : error.message,\n });\n }\n }\n }\n\n /** A throw site may set `logLevel` via `getError`; anything unset or malformed logs at `error`. */\n private resolveLogLevel(opts: { error: TThrown }): TLogLevel {\n const candidate = (opts.error as { logLevel?: unknown }).logLevel;\n\n if (typeof candidate === 'string' && LogLevels.isValid(candidate)) {\n return candidate as TLogLevel;\n }\n\n return LogLevels.ERROR;\n }\n\n /** The one place a thrown error reaches the log - called once the status is known, so it carries it. */\n private logError(opts: {\n error: TThrown;\n context: Context;\n requestId: string;\n statusCode: number;\n messageCode: string;\n type?: TApplicationErrorType;\n }) {\n const { error, context, requestId, statusCode, messageCode, type } = opts;\n\n this.logger.log(\n this.resolveLogLevel({ error }),\n '[%s] REQUEST ERROR | %s | %s %s\\n%s',\n requestId,\n statusCode,\n context.req.method,\n context.req.url,\n this.formatError({\n error,\n // The default code means \"no code\" - logging it on every error would be a noise line.\n messageCode: messageCode === MessageCode.DEFAULT ? undefined : messageCode,\n extra: 'extra' in error ? (error.extra as Record<string, unknown>) : undefined,\n includeStack: true,\n // An intentional error still needs its throw site; it just does not need the caller chain behind it.\n maxStackFrames:\n type === ApplicationErrorTypes.UNEXPECTED\n ? this.unexpectedStackFrames\n : this.intentionalStackFrames,\n }),\n );\n }\n\n /** Only an intentional error's message is a catalog template; every other branch writes its own text, so it passes through as is. */\n private renderMessage(opts: {\n resolved: IResolvedApplicationError;\n isProduction: boolean;\n requestId: string;\n }): string {\n const { resolved, isProduction, requestId } = opts;\n\n if (resolved.type !== ApplicationErrorTypes.INTENTIONAL) {\n return resolved.message;\n }\n\n const { text, missing } = MessageTemplate.render({\n text: resolved.message,\n args: resolved.normalized.args,\n });\n\n // Production stays silent and renders what it can; anywhere else a missing arg is a throw site to fix.\n if (missing.length > 0 && !isProduction) {\n this.logger.warn(\n '[%s] MESSAGE PLACEHOLDER WITHOUT ARG | code: %s | keys: %s',\n requestId,\n resolved.normalized.code,\n missing.join(', '),\n );\n }\n\n return text;\n }\n\n /**\n * The `extra` a response carries. It is whatever a throw site attached, so it goes through the same redaction the log\n * line uses (always masking in production, whatever the logger switch says), and a server error (5xx) in production\n * carries none: the log has it, a client has no use for it.\n */\n private renderExtra(opts: { error: Error; statusCode: number; isProduction: boolean }): unknown {\n const { error, statusCode, isProduction } = opts;\n\n if (!('extra' in error) || error.extra === undefined) {\n return undefined;\n }\n\n if (isProduction && statusCode >= 500) {\n return this.pickCorrelationIds({ extra: error.extra });\n }\n\n const safe = RedactUtility.toJsonSafe({ value: error.extra, force: isProduction });\n\n // A value `context.json` would refuse (a BigInt) becomes text here, so the authored status survives it.\n try {\n // A nested Error keeps its `stack` through the redaction (the log wants it); a client in production does not get one.\n const text = JSON.stringify(safe, (key, entry: unknown) => {\n if (isProduction && key === 'stack') {\n return undefined;\n }\n\n return typeof entry === 'bigint' ? entry.toString() : entry;\n });\n\n return text === undefined ? undefined : JSON.parse(text);\n // eslint-disable-next-line venizia/no-silent-catch -- the marker returned below is the report: the response carries it where the value would have been\n } catch {\n return '[unrenderable]';\n }\n }\n\n /**\n * What a production server error still carries from `extra`: the correlation ids support needs, `requestId` and\n * `upstreamRequestIds`, and nothing else. Only short strings count (a list of them for the chain), so the allowance\n * cannot carry anything but an id.\n */\n private pickCorrelationIds(opts: { extra: unknown }): Record<string, unknown> | undefined {\n const { extra } = opts;\n\n if (typeof extra !== 'object' || extra === null) {\n return undefined;\n }\n\n const source = extra as Record<string, unknown>;\n const isId = (value: unknown): value is string =>\n typeof value === 'string' && value.length <= 128;\n const picked: Record<string, unknown> = {};\n\n if (isId(source.requestId)) {\n picked.requestId = source.requestId;\n }\n\n const chain = source.upstreamRequestIds;\n\n if (Array.isArray(chain) && chain.length <= 32 && chain.every(isId)) {\n picked.upstreamRequestIds = chain;\n }\n\n return Object.keys(picked).length > 0 ? picked : undefined;\n }\n\n /** The `args` a throw site passes to its message template are data the client may see; secret-shaped keys in them are masked in production, whatever the logger switch says. */\n private renderNormalized(opts: {\n normalized: IResolvedApplicationError['normalized'];\n isProduction: boolean;\n }): IResolvedApplicationError['normalized'] {\n const { normalized, isProduction } = opts;\n\n if (!isProduction || !normalized.args || Object.keys(normalized.args).length === 0) {\n return normalized;\n }\n\n return {\n ...normalized,\n args: RedactUtility.redactSecrets({\n value: normalized.args,\n force: true,\n }) as typeof normalized.args,\n };\n }\n\n value(): ErrorHandler {\n return async (error, context) => {\n const requestId = context.get(REQUEST_ID_KEY);\n const isProduction = this.isProduction({ context, error, requestId });\n\n if (error.name === 'ZodError') {\n const rs = ZodErrorHandler.formatZodError({\n isProduction,\n requestId,\n url: context.req.url,\n path: context.req.path,\n error,\n });\n\n this.logError({\n error,\n context,\n requestId,\n statusCode: rs.statusCode,\n messageCode: rs.response.normalized.code,\n });\n\n return context.json(\n this.withRootKey(rs.response),\n rs.statusCode as Parameters<typeof context.json>[1],\n );\n }\n\n const resolved = this.resolve({ error, isProduction });\n const { statusCode, normalized, type } = resolved;\n\n this.logError({ error, context, requestId, statusCode, messageCode: normalized.code, type });\n\n const rs = {\n message: this.renderMessage({ resolved, isProduction, requestId }),\n statusCode,\n normalized: this.renderNormalized({ normalized, isProduction }),\n requestId,\n extra: this.renderExtra({ error, statusCode, isProduction }),\n details: {\n url: context.req.url,\n path: context.req.path,\n stack: !isProduction ? error.stack : undefined,\n cause: !isProduction ? error.cause : undefined,\n },\n };\n\n return context.json(this.withRootKey(rs), statusCode as Parameters<typeof context.json>[1]);\n };\n }\n}\n"]}
@@ -1,13 +1,15 @@
1
1
  import type { TConstValue } from '@venizia/ignis-helpers/common';
2
2
  import type { ApplicationErrorTypes } from '../definition.js';
3
- export interface IDatabaseError extends Error {
4
- code?: string;
5
- cause?: {
6
- code?: string;
7
- detail?: string;
8
- table?: string;
9
- constraint?: string;
10
- };
3
+ /** A Postgres error as every driver reports it, under one set of names. Only `code` is always there; the rest is what the server sent for that error. */
4
+ export interface IPostgresError {
5
+ /** The 5-character SQLSTATE (`23505`, `40P01`, ...); compare it with `PostgresErrorCodes`. */
6
+ code: string;
7
+ constraint?: string;
8
+ detail?: string;
9
+ table?: string;
10
+ column?: string;
11
+ schema?: string;
12
+ message?: string;
11
13
  }
12
14
  export interface IZodIssueLike {
13
15
  path: Array<string | number>;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/base/middlewares/app-error/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport type { ApplicationErrorTypes } from '../definition';\n\nexport interface IDatabaseError extends Error {\n code?: string;\n cause?: {\n code?: string;\n detail?: string;\n table?: string;\n constraint?: string;\n };\n}\n\nexport interface IZodIssueLike {\n path: Array<string | number>;\n message: string;\n code?: string;\n params?: Record<string, unknown>;\n expected?: unknown;\n received?: unknown;\n}\n\nexport type TApplicationErrorType = TConstValue<typeof ApplicationErrorTypes>;\n\nexport interface IResolvedApplicationError {\n statusCode: number;\n message: string;\n normalized: { text: string; code: string; args: Record<string, unknown> };\n /** Drives whether the log carries a stack - only an UNEXPECTED failure needs one. */\n type: TApplicationErrorType;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../src/base/middlewares/app-error/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { TConstValue } from '@venizia/ignis-helpers/common';\nimport type { ApplicationErrorTypes } from '../definition';\n\n/** A Postgres error as every driver reports it, under one set of names. Only `code` is always there; the rest is what the server sent for that error. */\nexport interface IPostgresError {\n /** The 5-character SQLSTATE (`23505`, `40P01`, ...); compare it with `PostgresErrorCodes`. */\n code: string;\n constraint?: string;\n detail?: string;\n table?: string;\n column?: string;\n schema?: string;\n message?: string;\n}\n\nexport interface IZodIssueLike {\n path: Array<string | number>;\n message: string;\n code?: string;\n params?: Record<string, unknown>;\n expected?: unknown;\n received?: unknown;\n}\n\nexport type TApplicationErrorType = TConstValue<typeof ApplicationErrorTypes>;\n\nexport interface IResolvedApplicationError {\n statusCode: number;\n message: string;\n normalized: { text: string; code: string; args: Record<string, unknown> };\n /** Drives whether the log carries a stack - only an UNEXPECTED failure needs one. */\n type: TApplicationErrorType;\n}\n"]}
@@ -1,15 +1,16 @@
1
1
  import { DATABASE_CLIENT_ERROR_FALLBACK_MESSAGE, DATABASE_CLIENT_ERROR_MESSAGES, POSTGRES_CLIENT_ERROR_CLASSES, POSTGRES_RETRYABLE_ERROR_CODES, } from './definition.js';
2
+ import { PostgresErrors } from './postgres-errors.js';
2
3
  export class DatabaseErrorHandler {
3
4
  /** True for a database error caused by the request (SQLSTATE class 22/23/44) -> HTTP 400; in production the detail/table/constraint context is suppressed so no row values or schema internals leak. */
4
5
  static isDatabaseClientError(opts) {
5
6
  const { error, isProduction } = opts;
6
- const dbError = error;
7
- const cause = dbError.cause;
8
- const code = [dbError.code, cause?.code].find(Boolean);
9
- // Only request-caused SQLSTATE classes are client errors; a missing or non-string code (e.g. a gRPC numeric one) is non-client and must never crash this last-resort handler.
10
- if (typeof code !== 'string' || !POSTGRES_CLIENT_ERROR_CLASSES.includes(code.slice(0, 2))) {
7
+ // A value without a SQLSTATE `code` (a gRPC numeric one, `ECONNRESET`) is not a Postgres error.
8
+ const pgError = PostgresErrors.find({ error });
9
+ // Only request-caused SQLSTATE classes are client errors.
10
+ if (!pgError || !POSTGRES_CLIENT_ERROR_CLASSES.includes(pgError.code.slice(0, 2))) {
11
11
  return { isClientError: false };
12
12
  }
13
+ const { code } = pgError;
13
14
  const baseMessage = DATABASE_CLIENT_ERROR_MESSAGES[code] ?? DATABASE_CLIENT_ERROR_FALLBACK_MESSAGE;
14
15
  // In production expose ONLY the generic base message: `detail` can echo row values and `table`/`constraint` reveal schema internals.
15
16
  if (isProduction) {
@@ -17,14 +18,14 @@ export class DatabaseErrorHandler {
17
18
  }
18
19
  // Non-production: append driver-provided context to aid debugging.
19
20
  const lines = [baseMessage];
20
- if (cause?.detail) {
21
- lines.push(`Detail: ${cause.detail}`);
21
+ if (pgError.detail) {
22
+ lines.push(`Detail: ${pgError.detail}`);
22
23
  }
23
- if (cause?.table) {
24
- lines.push(`Table: ${cause.table}`);
24
+ if (pgError.table) {
25
+ lines.push(`Table: ${pgError.table}`);
25
26
  }
26
- if (cause?.constraint) {
27
- lines.push(`Constraint: ${cause.constraint}`);
27
+ if (pgError.constraint) {
28
+ lines.push(`Constraint: ${pgError.constraint}`);
28
29
  }
29
30
  return {
30
31
  isClientError: true,
@@ -33,9 +34,8 @@ export class DatabaseErrorHandler {
33
34
  }
34
35
  /** True for a transient, retryable transaction conflict (serialization failure / deadlock - SQLSTATE 40001 / 40P01) -> HTTP 409: the client can retry the same request. */
35
36
  static isRetryableDatabaseError(opts) {
36
- const dbError = opts.error;
37
- const code = [dbError.code, dbError.cause?.code].find(Boolean);
38
- return typeof code === 'string' && POSTGRES_RETRYABLE_ERROR_CODES.includes(code);
37
+ const pgError = PostgresErrors.find({ error: opts.error });
38
+ return pgError !== undefined && POSTGRES_RETRYABLE_ERROR_CODES.includes(pgError.code);
39
39
  }
40
40
  }
41
41
  //# sourceMappingURL=database.handler.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"database.handler.js","sourceRoot":"","sources":["../../../../../src/base/middlewares/app-error/database.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sCAAsC,EACtC,8BAA8B,EAC9B,6BAA6B,EAC7B,8BAA8B,GAC/B,MAAM,cAAc,CAAC;AAGtB,MAAM,OAAO,oBAAoB;IAC/B,wMAAwM;IACxM,MA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I,CAAC;SAC1B,CAAC;IACJ,CAAC;IAED,2KAA2K;IAC3K,MAAM,CAAC,wBAAwB,CAAC,IAAsB;QACpD,MAAM,OAAO,GAAG,IAAI,CAAC,KAAuB,CAAC;QAC7C,MAAM,IAAI,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QAE/D,OAAO,OAAO,IAAI,KAAK,QAAQ,IAAI,8BAA8B,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IACnF,CAAC;CACF","sourcesContent":["import {\n DATABASE_CLIENT_ERROR_FALLBACK_MESSAGE,\n DATABASE_CLIENT_ERROR_MESSAGES,\n POSTGRES_CLIENT_ERROR_CLASSES,\n POSTGRES_RETRYABLE_ERROR_CODES,\n} from './definition';\nimport type { IDatabaseError } from './common';\n\nexport class DatabaseErrorHandler {\n /** True for a database error caused by the request (SQLSTATE class 22/23/44) -> HTTP 400; in production the detail/table/constraint context is suppressed so no row values or schema internals leak. */\n static isDatabaseClientError(opts: { error: Error; isProduction: boolean }): {\n isClientError: boolean;\n message?: string;\n } {\n const { error, isProduction } = opts;\n const dbError = error as IDatabaseError;\n const cause = dbError.cause;\n const code = [dbError.code, cause?.code].find(Boolean);\n\n // Only request-caused SQLSTATE classes are client errors; a missing or non-string code (e.g. a gRPC numeric one) is non-client and must never crash this last-resort handler.\n if (typeof code !== 'string' || !POSTGRES_CLIENT_ERROR_CLASSES.includes(code.slice(0, 2))) {\n return { isClientError: false };\n }\n\n const baseMessage =\n DATABASE_CLIENT_ERROR_MESSAGES[code] ?? DATABASE_CLIENT_ERROR_FALLBACK_MESSAGE;\n\n // In production expose ONLY the generic base message: `detail` can echo row values and `table`/`constraint` reveal schema internals.\n if (isProduction) {\n return { isClientError: true, message: baseMessage };\n }\n\n // Non-production: append driver-provided context to aid debugging.\n const lines = [baseMessage];\n\n if (cause?.detail) {\n lines.push(`Detail: ${cause.detail}`);\n }\n\n if (cause?.table) {\n lines.push(`Table: ${cause.table}`);\n }\n\n if (cause?.constraint) {\n lines.push(`Constraint: ${cause.constraint}`);\n }\n\n return {\n isClientError: true,\n message: lines.join('\\n'),\n };\n }\n\n /** True for a transient, retryable transaction conflict (serialization failure / deadlock - SQLSTATE 40001 / 40P01) -> HTTP 409: the client can retry the same request. */\n static isRetryableDatabaseError(opts: { error: Error }): boolean {\n const dbError = opts.error as IDatabaseError;\n const code = [dbError.code, dbError.cause?.code].find(Boolean);\n\n return typeof code === 'string' && POSTGRES_RETRYABLE_ERROR_CODES.includes(code);\n }\n}\n"]}
1
+ {"version":3,"file":"database.handler.js","sourceRoot":"","sources":["../../../../../src/base/middlewares/app-error/database.handler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sCAAsC,EACtC,8BAA8B,EAC9B,6BAA6B,EAC7B,8BAA8B,GAC/B,MAAM,cAAc,CAAC;AACtB,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnD,MAAM,OAAO,oBAAoB;IAC/B,wMAAwM;IACxM,MAAM,CAAC,qBAAqB,CAAC,IAA6C;QAIxE,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC;QACrC,gGAAgG;QAChG,MAAM,OAAO,GAAG,cAAc,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAE/C,0DAA0D;QAC1D,IAAI,CAAC,OAAO,IAAI,CAAC,6BAA6B,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAClF,OAAO,EAAE,aAAa,EAAE,KAAK,EAAE,CAAC;QAClC,CAAC;QAED,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC;QAEzB,MAAM,WAAW,GACf,8BAA8B,CAAC,IAAI,CAAC,IAAI,sCAAsC,CAAC;QAEjF,qIAAqI;QACrI,IAAI,YAAY,EAAE,CAAC;YACjB,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,WAAW,EAAE,CAAC;QACvD,CAAC;QAED,mEAAmE;QACnE,MAAM,KAAK,GAAG,CAAC,WAAW,CAAC,CAAC;QAE5B,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;YACnB,KAAK,CAAC,IAAI,CAAC,WAAW,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC1C,CAAC;QAED,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;YAClB,KAAK,CAAC,IAAI,CAAC,UAAU,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;QACxC,CAAC;QAED,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;YACvB,KAAK,CAAC,IAAI,CAAC,eAAe,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QAClD,CAAC;QAED,OAAO;YACL,aAAa,EAAE,IAAI;YACnB,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;SAC1B,CAAC;IACJ,CAAC;IAED,2KAA2K;IAC3K,MAAM,CAAC,wBAAwB,CAAC,IAAsB;QACpD,MAAM,OAAO,GAAG,cAAc,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAE3D,OAAO,OAAO,KAAK,SAAS,IAAI,8BAA8B,CAAC,QAAQ,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACxF,CAAC;CACF","sourcesContent":["import {\n DATABASE_CLIENT_ERROR_FALLBACK_MESSAGE,\n DATABASE_CLIENT_ERROR_MESSAGES,\n POSTGRES_CLIENT_ERROR_CLASSES,\n POSTGRES_RETRYABLE_ERROR_CODES,\n} from './definition';\nimport { PostgresErrors } from './postgres-errors';\n\nexport class DatabaseErrorHandler {\n /** True for a database error caused by the request (SQLSTATE class 22/23/44) -> HTTP 400; in production the detail/table/constraint context is suppressed so no row values or schema internals leak. */\n static isDatabaseClientError(opts: { error: Error; isProduction: boolean }): {\n isClientError: boolean;\n message?: string;\n } {\n const { error, isProduction } = opts;\n // A value without a SQLSTATE `code` (a gRPC numeric one, `ECONNRESET`) is not a Postgres error.\n const pgError = PostgresErrors.find({ error });\n\n // Only request-caused SQLSTATE classes are client errors.\n if (!pgError || !POSTGRES_CLIENT_ERROR_CLASSES.includes(pgError.code.slice(0, 2))) {\n return { isClientError: false };\n }\n\n const { code } = pgError;\n\n const baseMessage =\n DATABASE_CLIENT_ERROR_MESSAGES[code] ?? DATABASE_CLIENT_ERROR_FALLBACK_MESSAGE;\n\n // In production expose ONLY the generic base message: `detail` can echo row values and `table`/`constraint` reveal schema internals.\n if (isProduction) {\n return { isClientError: true, message: baseMessage };\n }\n\n // Non-production: append driver-provided context to aid debugging.\n const lines = [baseMessage];\n\n if (pgError.detail) {\n lines.push(`Detail: ${pgError.detail}`);\n }\n\n if (pgError.table) {\n lines.push(`Table: ${pgError.table}`);\n }\n\n if (pgError.constraint) {\n lines.push(`Constraint: ${pgError.constraint}`);\n }\n\n return {\n isClientError: true,\n message: lines.join('\\n'),\n };\n }\n\n /** True for a transient, retryable transaction conflict (serialization failure / deadlock - SQLSTATE 40001 / 40P01) -> HTTP 409: the client can retry the same request. */\n static isRetryableDatabaseError(opts: { error: Error }): boolean {\n const pgError = PostgresErrors.find({ error: opts.error });\n\n return pgError !== undefined && POSTGRES_RETRYABLE_ERROR_CODES.includes(pgError.code);\n }\n}\n"]}
@@ -1,3 +1,5 @@
1
1
  export * from './app-error.middleware.js';
2
2
  export { PostgresErrorCodes } from './definition.js';
3
+ export { PostgresErrors } from './postgres-errors.js';
4
+ export type { IPostgresError } from './common/index.js';
3
5
  //# sourceMappingURL=index.d.ts.map
@@ -1,3 +1,4 @@
1
1
  export * from './app-error.middleware.js';
2
2
  export { PostgresErrorCodes } from './definition.js';
3
+ export { PostgresErrors } from './postgres-errors.js';
3
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/base/middlewares/app-error/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC","sourcesContent":["export * from './app-error.middleware';\nexport { PostgresErrorCodes } from './definition';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/base/middlewares/app-error/index.ts"],"names":[],"mappings":"AAAA,cAAc,wBAAwB,CAAC;AACvC,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC","sourcesContent":["export * from './app-error.middleware';\nexport { PostgresErrorCodes } from './definition';\nexport { PostgresErrors } from './postgres-errors';\nexport type { IPostgresError } from './common';\n"]}
@@ -0,0 +1,20 @@
1
+ import type { IPostgresError } from './common/index.js';
2
+ /** Finds the Postgres error in a thrown value, through the `cause` chain an ORM builds around a driver error. The error handler uses it; so can your code. */
3
+ export declare class PostgresErrors {
4
+ /** How many `cause` hops the walk follows: the thrown error is hop 0, so an error 10 hops down is found and one 11 hops down is not. */
5
+ static readonly MAX_DEPTH = 10;
6
+ /** Reads one property and never throws: a getter that throws, or a Proxy trap that does, reads as `undefined`. */
7
+ private static read;
8
+ /** The first spelling of a field that holds a string, or `undefined`. */
9
+ private static readString;
10
+ /** Normalizes one driver error into the result type, or `undefined` when its `code` is not a SQLSTATE. */
11
+ private static normalize;
12
+ /**
13
+ * Finds the Postgres error in a thrown value, looking through `cause` (an ORM wraps the driver error, sometimes more than once). The outermost error with a SQLSTATE `code` wins.
14
+ * Never throws: a value that is not an object, a cycle, a getter that throws and a Proxy all end in `undefined`.
15
+ */
16
+ static find(opts: {
17
+ error: unknown;
18
+ }): IPostgresError | undefined;
19
+ }
20
+ //# sourceMappingURL=postgres-errors.d.ts.map
@@ -0,0 +1,74 @@
1
+ /** A SQLSTATE is five characters of digits and upper-case letters (Postgres appendix A); `ECONNRESET`, a gRPC number or a lower-case word is not one. */
2
+ const SQLSTATE_PATTERN = /^[0-9A-Z]{5}$/;
3
+ /** The driver spellings of each optional field, in the order tried: node-postgres and PGlite use the first, postgres-js the second. */
4
+ const FIELD_SPELLINGS = {
5
+ constraint: ['constraint', 'constraint_name'],
6
+ detail: ['detail'],
7
+ table: ['table', 'table_name'],
8
+ column: ['column', 'column_name'],
9
+ schema: ['schema', 'schema_name'],
10
+ message: ['message'],
11
+ };
12
+ /** Finds the Postgres error in a thrown value, through the `cause` chain an ORM builds around a driver error. The error handler uses it; so can your code. */
13
+ export class PostgresErrors {
14
+ /** How many `cause` hops the walk follows: the thrown error is hop 0, so an error 10 hops down is found and one 11 hops down is not. */
15
+ static { this.MAX_DEPTH = 10; }
16
+ /** Reads one property and never throws: a getter that throws, or a Proxy trap that does, reads as `undefined`. */
17
+ static read(opts) {
18
+ try {
19
+ return Reflect.get(opts.target, opts.key);
20
+ // eslint-disable-next-line venizia/no-silent-catch -- a hostile getter or Proxy is the input this helper exists to survive; the caller treats the property as absent
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ /** The first spelling of a field that holds a string, or `undefined`. */
27
+ static readString(opts) {
28
+ for (const key of opts.spellings) {
29
+ const value = PostgresErrors.read({ target: opts.target, key });
30
+ if (typeof value === 'string') {
31
+ return value;
32
+ }
33
+ }
34
+ return undefined;
35
+ }
36
+ /** Normalizes one driver error into the result type, or `undefined` when its `code` is not a SQLSTATE. */
37
+ static normalize(opts) {
38
+ const { target } = opts;
39
+ const code = PostgresErrors.read({ target, key: 'code' });
40
+ if (typeof code !== 'string' || !SQLSTATE_PATTERN.test(code)) {
41
+ return undefined;
42
+ }
43
+ const result = { code };
44
+ // Only the fields the driver set: an absent field stays absent rather than becoming `undefined`.
45
+ for (const [name, spellings] of Object.entries(FIELD_SPELLINGS)) {
46
+ const value = PostgresErrors.readString({ target, spellings });
47
+ if (value !== undefined) {
48
+ Reflect.set(result, name, value);
49
+ }
50
+ }
51
+ return result;
52
+ }
53
+ /**
54
+ * Finds the Postgres error in a thrown value, looking through `cause` (an ORM wraps the driver error, sometimes more than once). The outermost error with a SQLSTATE `code` wins.
55
+ * Never throws: a value that is not an object, a cycle, a getter that throws and a Proxy all end in `undefined`.
56
+ */
57
+ static find(opts) {
58
+ const visited = new Set();
59
+ let current = opts.error;
60
+ for (let depth = 0; depth <= PostgresErrors.MAX_DEPTH; depth += 1) {
61
+ if (typeof current !== 'object' || current === null || visited.has(current)) {
62
+ return undefined;
63
+ }
64
+ visited.add(current);
65
+ const found = PostgresErrors.normalize({ target: current });
66
+ if (found) {
67
+ return found;
68
+ }
69
+ current = PostgresErrors.read({ target: current, key: 'cause' });
70
+ }
71
+ return undefined;
72
+ }
73
+ }
74
+ //# sourceMappingURL=postgres-errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-errors.js","sourceRoot":"","sources":["../../../../../src/base/middlewares/app-error/postgres-errors.ts"],"names":[],"mappings":"AAEA,yJAAyJ;AACzJ,MAAM,gBAAgB,GAAG,eAAe,CAAC;AAEzC,uIAAuI;AACvI,MAAM,eAAe,GAAqE;IACxF,UAAU,EAAE,CAAC,YAAY,EAAE,iBAAiB,CAAC;IAC7C,MAAM,EAAE,CAAC,QAAQ,CAAC;IAClB,KAAK,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC;IAC9B,MAAM,EAAE,CAAC,QAAQ,EAAE,aAAa,CAAC;IACjC,MAAM,EAAE,CAAC,QAAQ,EAAE,aAAa,CAAC;IACjC,OAAO,EAAE,CAAC,SAAS,CAAC;CACrB,CAAC;AAEF,8JAA8J;AAC9J,MAAM,OAAO,cAAc;IACzB,wIAAwI;aACxH,cAAS,GAAG,EAAE,CAAC;IAE/B,kHAAkH;IAC1G,MAAM,CAAC,IAAI,CAAC,IAAqC;QACvD,IAAI,CAAC;YACH,OAAO,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC;YAC1C,qK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,CAAC,IAAI,CAAC,IAAwB;QAClC,MAAM,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;QAClC,IAAI,OAAO,GAAY,IAAI,CAAC,KAAK,CAAC;QAElC,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,IAAI,cAAc,CAAC,SAAS,EAAE,KAAK,IAAI,CAAC,EAAE,CAAC;YAClE,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC;gBAC5E,OAAO,SAAS,CAAC;YACnB,CAAC;YAED,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;YAErB,MAAM,KAAK,GAAG,cAAc,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;YAE5D,IAAI,KAAK,EAAE,CAAC;gBACV,OAAO,KAAK,CAAC;YACf,CAAC;YAED,OAAO,GAAG,cAAc,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC;QACnE,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC","sourcesContent":["import type { IPostgresError } from './common';\n\n/** A SQLSTATE is five characters of digits and upper-case letters (Postgres appendix A); `ECONNRESET`, a gRPC number or a lower-case word is not one. */\nconst SQLSTATE_PATTERN = /^[0-9A-Z]{5}$/;\n\n/** The driver spellings of each optional field, in the order tried: node-postgres and PGlite use the first, postgres-js the second. */\nconst FIELD_SPELLINGS: Record<Exclude<keyof IPostgresError, 'code'>, readonly string[]> = {\n constraint: ['constraint', 'constraint_name'],\n detail: ['detail'],\n table: ['table', 'table_name'],\n column: ['column', 'column_name'],\n schema: ['schema', 'schema_name'],\n message: ['message'],\n};\n\n/** Finds the Postgres error in a thrown value, through the `cause` chain an ORM builds around a driver error. The error handler uses it; so can your code. */\nexport class PostgresErrors {\n /** How many `cause` hops the walk follows: the thrown error is hop 0, so an error 10 hops down is found and one 11 hops down is not. */\n static readonly MAX_DEPTH = 10;\n\n /** Reads one property and never throws: a getter that throws, or a Proxy trap that does, reads as `undefined`. */\n private static read(opts: { target: object; key: string }): unknown {\n try {\n return Reflect.get(opts.target, opts.key);\n // eslint-disable-next-line venizia/no-silent-catch -- a hostile getter or Proxy is the input this helper exists to survive; the caller treats the property as absent\n } catch {\n return undefined;\n }\n }\n\n /** The first spelling of a field that holds a string, or `undefined`. */\n private static readString(opts: {\n target: object;\n spellings: readonly string[];\n }): string | undefined {\n for (const key of opts.spellings) {\n const value = PostgresErrors.read({ target: opts.target, key });\n\n if (typeof value === 'string') {\n return value;\n }\n }\n\n return undefined;\n }\n\n /** Normalizes one driver error into the result type, or `undefined` when its `code` is not a SQLSTATE. */\n private static normalize(opts: { target: object }): IPostgresError | undefined {\n const { target } = opts;\n const code = PostgresErrors.read({ target, key: 'code' });\n\n if (typeof code !== 'string' || !SQLSTATE_PATTERN.test(code)) {\n return undefined;\n }\n\n const result: IPostgresError = { code };\n\n // Only the fields the driver set: an absent field stays absent rather than becoming `undefined`.\n for (const [name, spellings] of Object.entries(FIELD_SPELLINGS)) {\n const value = PostgresErrors.readString({ target, spellings });\n\n if (value !== undefined) {\n Reflect.set(result, name, value);\n }\n }\n\n return result;\n }\n\n /**\n * Finds the Postgres error in a thrown value, looking through `cause` (an ORM wraps the driver error, sometimes more than once). The outermost error with a SQLSTATE `code` wins.\n * Never throws: a value that is not an object, a cycle, a getter that throws and a Proxy all end in `undefined`.\n */\n static find(opts: { error: unknown }): IPostgresError | undefined {\n const visited = new Set<object>();\n let current: unknown = opts.error;\n\n for (let depth = 0; depth <= PostgresErrors.MAX_DEPTH; depth += 1) {\n if (typeof current !== 'object' || current === null || visited.has(current)) {\n return undefined;\n }\n\n visited.add(current);\n\n const found = PostgresErrors.normalize({ target: current });\n\n if (found) {\n return found;\n }\n\n current = PostgresErrors.read({ target: current, key: 'cause' });\n }\n\n return undefined;\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"]}