@tstdl/base 0.93.61 → 0.93.64

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 (101) hide show
  1. package/ai/genkit/helpers.d.ts +10 -0
  2. package/ai/genkit/helpers.js +14 -0
  3. package/ai/genkit/index.d.ts +2 -0
  4. package/ai/genkit/index.js +2 -0
  5. package/ai/genkit/module.d.ts +35 -0
  6. package/ai/genkit/module.js +56 -0
  7. package/ai/index.d.ts +1 -0
  8. package/ai/index.js +1 -0
  9. package/ai/prompts/format.d.ts +15 -0
  10. package/ai/prompts/format.js +17 -0
  11. package/ai/prompts/index.d.ts +3 -0
  12. package/ai/prompts/index.js +3 -0
  13. package/ai/prompts/instructions-formatter.d.ts +25 -0
  14. package/ai/prompts/instructions-formatter.js +166 -0
  15. package/ai/prompts/instructions.d.ts +3 -0
  16. package/ai/prompts/instructions.js +8 -0
  17. package/document-management/api/document-management.api.d.ts +8 -8
  18. package/document-management/models/document-assignment-scope.model.d.ts +3 -4
  19. package/document-management/models/document-assignment-scope.model.js +5 -9
  20. package/document-management/models/document-assignment-task.model.d.ts +3 -4
  21. package/document-management/models/document-assignment-task.model.js +4 -8
  22. package/document-management/models/document-category.model.d.ts +3 -4
  23. package/document-management/models/document-category.model.js +4 -8
  24. package/document-management/models/document-collection-assignment.model.d.ts +2 -3
  25. package/document-management/models/document-collection-assignment.model.js +4 -9
  26. package/document-management/models/document-collection.model.d.ts +3 -4
  27. package/document-management/models/document-collection.model.js +4 -8
  28. package/document-management/models/document-property-value.model.d.ts +3 -4
  29. package/document-management/models/document-property-value.model.js +5 -9
  30. package/document-management/models/document-property.model.d.ts +3 -4
  31. package/document-management/models/document-property.model.js +3 -7
  32. package/document-management/models/document-request-collection-assignment.model.d.ts +3 -4
  33. package/document-management/models/document-request-collection-assignment.model.js +5 -9
  34. package/document-management/models/document-request-template.d.ts +2 -3
  35. package/document-management/models/document-request-template.js +4 -9
  36. package/document-management/models/document-request.model.d.ts +3 -4
  37. package/document-management/models/document-request.model.js +5 -9
  38. package/document-management/models/document-requests-template.d.ts +2 -3
  39. package/document-management/models/document-requests-template.js +2 -7
  40. package/document-management/models/document-tag-assignment.model.d.ts +3 -4
  41. package/document-management/models/document-tag-assignment.model.js +5 -9
  42. package/document-management/models/document-tag.model.d.ts +3 -4
  43. package/document-management/models/document-tag.model.js +3 -7
  44. package/document-management/models/document-type-property.model.d.ts +2 -3
  45. package/document-management/models/document-type-property.model.js +4 -9
  46. package/document-management/models/document-type-validation.model.d.ts +2 -3
  47. package/document-management/models/document-type-validation.model.js +4 -9
  48. package/document-management/models/document-type.model.d.ts +3 -4
  49. package/document-management/models/document-type.model.js +4 -8
  50. package/document-management/models/document-validation-definition.model.d.ts +3 -4
  51. package/document-management/models/document-validation-definition.model.js +3 -7
  52. package/document-management/models/document-validation-execution-related-document.model.d.ts +3 -4
  53. package/document-management/models/document-validation-execution-related-document.model.js +5 -9
  54. package/document-management/models/document-validation-execution.model.d.ts +3 -4
  55. package/document-management/models/document-validation-execution.model.js +5 -9
  56. package/document-management/models/document-workflow.model.d.ts +3 -4
  57. package/document-management/models/document-workflow.model.js +4 -8
  58. package/document-management/models/document.model.d.ts +3 -4
  59. package/document-management/models/document.model.js +4 -8
  60. package/document-management/server/drizzle/0001_lyrical_wong.sql +123 -0
  61. package/document-management/server/drizzle/meta/0001_snapshot.json +2728 -0
  62. package/document-management/server/drizzle/meta/_journal.json +7 -0
  63. package/document-management/server/services/document-category-type.service.d.ts +6 -6
  64. package/document-management/server/services/document-category-type.service.js +6 -6
  65. package/document-management/server/services/document-file.service.d.ts +2 -0
  66. package/document-management/server/services/document-file.service.js +10 -9
  67. package/document-management/server/services/document-management-ai.service.d.ts +1 -0
  68. package/document-management/server/services/document-management-ai.service.js +268 -135
  69. package/document-management/server/services/document-management.service.d.ts +2 -2
  70. package/document-management/server/services/document-property.service.d.ts +4 -4
  71. package/document-management/server/services/document-property.service.js +3 -3
  72. package/document-management/server/services/document-request.service.d.ts +2 -2
  73. package/document-management/server/services/document-request.service.js +1 -1
  74. package/document-management/server/services/document-tag.service.d.ts +1 -1
  75. package/document-management/server/services/document-tag.service.js +2 -2
  76. package/document-management/server/services/document-validation.service.js +6 -6
  77. package/document-management/server/services/document.service.js +2 -7
  78. package/document-management/service-models/document-management.view-model.d.ts +1 -1
  79. package/document-management/service-models/document-management.view-model.js +1 -1
  80. package/document-management/service-models/document.service-model.d.ts +4 -4
  81. package/document-management/service-models/enriched/enriched-document-category.view.d.ts +1 -1
  82. package/document-management/service-models/enriched/enriched-document-type.view.d.ts +1 -1
  83. package/examples/document-management/main.js +6 -0
  84. package/json-path/json-path.js +1 -1
  85. package/orm/decorators.d.ts +18 -7
  86. package/orm/decorators.js +10 -2
  87. package/orm/entity.d.ts +2 -2
  88. package/orm/entity.js +2 -0
  89. package/orm/server/drizzle/schema-converter.d.ts +3 -3
  90. package/orm/server/drizzle/schema-converter.js +22 -5
  91. package/orm/server/repository.js +4 -6
  92. package/package.json +11 -7
  93. package/pdf/utils.js +1 -1
  94. package/schema/converters/zod-converter.d.ts +1 -1
  95. package/schema/converters/zod-converter.js +2 -13
  96. package/schema/converters/zod-v3-converter.d.ts +3 -3
  97. package/utils/file-reader.d.ts +0 -1
  98. package/utils/file-reader.js +4 -7
  99. package/utils/object/object.d.ts +4 -2
  100. package/utils/object/object.js +30 -21
  101. package/utils/stream/from-promise.js +2 -2
@@ -56,9 +56,9 @@ let DocumentValidationService = DocumentValidationService_1 = class DocumentVali
56
56
  throw new BadRequestError('Document has no type');
57
57
  }
58
58
  const workflow = await this.#documentWorkflowService.initiateWorkflow(document.tenantId, documentId, DocumentWorkflowStep.Validation);
59
- const typeValidations = await this.#documentTypeValidationService.loadManyByQuery({ tenantId: { $or: [null, tenantId] }, typeId: document.typeId });
59
+ const typeValidations = await this.#documentTypeValidationService.loadManyByQuery({ tenantId, typeId: document.typeId });
60
60
  for (const typeValidation of typeValidations) {
61
- const validationDefinition = await this.#validationDefinitionService.loadByQuery({ tenantId: { $or: [null, tenantId] }, id: typeValidation.validationId });
61
+ const validationDefinition = await this.#validationDefinitionService.loadByQuery({ tenantId, id: typeValidation.validationId });
62
62
  const execution = await this.#validationExecutionService.insert({
63
63
  tenantId: document.tenantId,
64
64
  definitionId: validationDefinition.id,
@@ -95,15 +95,15 @@ let DocumentValidationService = DocumentValidationService_1 = class DocumentVali
95
95
  }
96
96
  const [documentCollections, documentTypeProperties, type] = await Promise.all([
97
97
  this.#documentCollectionAssignmentRepository.loadManyByQuery({ tenantId, documentId: document.id }),
98
- this.#documentTypePropertyService.loadManyByQuery({ tenantId: { $or: [null, tenantId] }, typeId: document.typeId }),
99
- this.#documentTypeService.loadByQuery({ tenantId: { $or: [null, tenantId] }, id: document.typeId }),
98
+ this.#documentTypePropertyService.loadManyByQuery({ tenantId, typeId: document.typeId }),
99
+ this.#documentTypeService.loadByQuery({ tenantId, id: document.typeId }),
100
100
  ]);
101
101
  const documentCollectionIds = getEntityIds(documentCollections);
102
102
  const documentPropertyIds = getEntityIds(documentTypeProperties);
103
103
  const [collections, category, properties, propertyValues] = await Promise.all([
104
104
  this.#documentManagementService.loadManyByQuery({ tenantId, id: { $in: documentCollectionIds } }),
105
- this.#documentCategoryService.loadByQuery({ tenantId: { $or: [null, tenantId] }, id: type.categoryId }),
106
- this.#documentPropertyService.loadManyByQuery({ tenantId: { $or: [null, tenantId] }, id: { $in: documentPropertyIds } }),
105
+ this.#documentCategoryService.loadByQuery({ tenantId, id: type.categoryId }),
106
+ this.#documentPropertyService.loadManyByQuery({ tenantId, id: { $in: documentPropertyIds } }),
107
107
  this.#documentPropertyValueService.loadManyByQuery({ tenantId, documentId: document.id }),
108
108
  ]);
109
109
  return {
@@ -16,8 +16,8 @@ import { toArray } from '../../../utils/array/index.js';
16
16
  import { objectKeys } from '../../../utils/object/object.js';
17
17
  import { readableStreamFromPromise } from '../../../utils/stream/from-promise.js';
18
18
  import { tryIgnoreLogAsync } from '../../../utils/try-ignore.js';
19
- import { isDefined, isNotReadableStream, isNotUint8Array, isString, isUndefined } from '../../../utils/type-guards.js';
20
- import { Document, DocumentApproval, DocumentAssignmentScope, DocumentAssignmentTask, DocumentType, DocumentWorkflowStep } from '../../models/index.js';
19
+ import { isDefined, isNotReadableStream, isNotUint8Array, isUndefined } from '../../../utils/type-guards.js';
20
+ import { Document, DocumentApproval, DocumentAssignmentScope, DocumentAssignmentTask, DocumentWorkflowStep } from '../../models/index.js';
21
21
  import { DocumentCollectionService } from './document-collection.service.js';
22
22
  import { DocumentFileService } from './document-file.service.js';
23
23
  import { DocumentManagementObservationService } from './document-management-observation.service.js';
@@ -33,7 +33,6 @@ let DocumentService = DocumentService_1 = class DocumentService extends Transact
33
33
  #workflowService = injectTransactional(DocumentWorkflowService);
34
34
  #documentPropertyService = injectTransactional(DocumentPropertyService);
35
35
  #collectionService = injectTransactional(DocumentCollectionService);
36
- #documentTypeRepository = injectRepository(DocumentType);
37
36
  #documentAssignmentTaskRepository = injectRepository(DocumentAssignmentTask);
38
37
  #documentAssignmentScopeRepository = injectRepository(DocumentAssignmentScope);
39
38
  #observationService = inject(DocumentManagementObservationService);
@@ -42,10 +41,6 @@ let DocumentService = DocumentService_1 = class DocumentService extends Transact
42
41
  async create(tenantId, { typeId, title, subtitle, date, summary, tags, approval, comment, originalFileName, assignment, properties, metadata }, contentSource, { createUserId }) {
43
42
  const document = await this.transaction(async (tx) => {
44
43
  const isUpload = isNotUint8Array(contentSource) && isNotReadableStream(contentSource);
45
- if (isString(typeId)) {
46
- // verify that the type exists for the tenant
47
- await this.#documentTypeRepository.loadByQuery({ tenantId: { $or: [null, tenantId] }, id: typeId });
48
- }
49
44
  const document = await this.repository.withTransaction(tx).insert({
50
45
  tenantId,
51
46
  typeId: typeId ?? null,
@@ -40,7 +40,7 @@ export declare class DocumentRequestView extends DocumentRequest {
40
40
  }
41
41
  export declare class DocumentPropertyView implements TypedOmit<DocumentProperty, 'metadata'> {
42
42
  id: string;
43
- tenantId: string | null;
43
+ tenantId: string;
44
44
  label: string;
45
45
  dataType: DocumentPropertyDataType;
46
46
  typeIds: string[];
@@ -144,7 +144,7 @@ __decorate([
144
144
  ], DocumentPropertyView.prototype, "id", void 0);
145
145
  __decorate([
146
146
  StringProperty({ nullable: true }),
147
- __metadata("design:type", Object)
147
+ __metadata("design:type", String)
148
148
  ], DocumentPropertyView.prototype, "tenantId", void 0);
149
149
  __decorate([
150
150
  StringProperty(),
@@ -20,10 +20,10 @@ export declare const updateDocumentCollectionsParametersSchema: import("../../sc
20
20
  }>;
21
21
  export declare const createDocumentParametersSchema: import("../../schema/index.js").ObjectSchema<{
22
22
  date?: import("../../orm/index.js").NumericDate | null | undefined;
23
+ summary?: string | null | undefined;
23
24
  title?: string | null | undefined;
24
25
  typeId?: import("../../orm/index.js").Uuid | null | undefined;
25
26
  subtitle?: string | null | undefined;
26
- summary?: string | null | undefined;
27
27
  comment?: string | null | undefined;
28
28
  approval?: import("../models/document.model.js").DocumentApproval | undefined;
29
29
  originalFileName?: string | null | undefined;
@@ -97,7 +97,7 @@ export declare const createDocumentRequestsTemplateParametersSchema: import("../
97
97
  export declare const updateDocumentRequestsTemplateParametersSchema: import("../../schema/index.js").ObjectSchema<{
98
98
  id: import("../../orm/index.js").IsPrimaryKey<import("../../orm/index.js").HasDefault<import("../../orm/index.js").Uuid>>;
99
99
  description?: string | null | undefined;
100
- tenantId?: string | null | undefined;
100
+ tenantId?: import("../../orm/index.js").Uuid | undefined;
101
101
  label?: string | undefined;
102
102
  metadata?: Partial<{
103
103
  attributes: import("../../orm/index.js").HasDefault<import("../../orm/index.js").Json<import("../../orm/index.js").EntityMetadataAttributes>>;
@@ -126,7 +126,7 @@ export declare const createDocumentRequestTemplateParametersSchema: import("../.
126
126
  }>;
127
127
  export declare const updateDocumentRequestTemplateParametersSchema: import("../../schema/index.js").ObjectSchema<{
128
128
  id: import("../../orm/index.js").IsPrimaryKey<import("../../orm/index.js").HasDefault<import("../../orm/index.js").Uuid>>;
129
- tenantId?: string | null | undefined;
129
+ tenantId?: import("../../orm/index.js").Uuid | undefined;
130
130
  typeId?: import("../../orm/index.js").Uuid | undefined;
131
131
  comment?: string | null | undefined;
132
132
  metadata?: Partial<{
@@ -181,8 +181,8 @@ export declare const setDocumentPropertiesParametersSchema: import("../../schema
181
181
  documentId: string;
182
182
  }>;
183
183
  export declare const createDocumentCategoryParametersSchema: import("../../schema/index.js").ObjectSchema<{
184
- parentId: import("../../orm/index.js").Uuid | null;
185
184
  label: string;
185
+ parentId: import("../../orm/index.js").Uuid | null;
186
186
  metadata?: Partial<{
187
187
  attributes: import("../../orm/index.js").HasDefault<import("../../orm/index.js").Json<import("../../orm/index.js").EntityMetadataAttributes>>;
188
188
  }> | undefined;
@@ -6,7 +6,7 @@ import type { EnrichedDocument } from './enriched-document.view.js';
6
6
  export declare class EnrichedDocumentCategory implements TypedOmit<DocumentCategory, 'parentId' | 'metadata'> {
7
7
  #private;
8
8
  readonly id: string;
9
- readonly tenantId: string | null;
9
+ readonly tenantId: string;
10
10
  readonly label: string;
11
11
  readonly parent: EnrichedDocumentCategory | null;
12
12
  readonly helper: {
@@ -6,7 +6,7 @@ import type { EnrichedDocumentManagementData } from './enriched-document-managem
6
6
  export declare class EnrichedDocumentType implements TypedOmit<DocumentType, 'categoryId' | 'metadata'> {
7
7
  #private;
8
8
  readonly id: string;
9
- readonly tenantId: string | null;
9
+ readonly tenantId: string;
10
10
  readonly label: string;
11
11
  readonly category: EnrichedDocumentCategory;
12
12
  readonly helper: {
@@ -5,6 +5,7 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  return c > 3 && r && Object.defineProperty(target, key, r), r;
6
6
  };
7
7
  import '../../polyfills.js';
8
+ import { configureGenkit } from '../../ai/genkit/module.js';
8
9
  import { configureAiService } from '../../ai/index.js';
9
10
  import { MockApiRequestTokenProvider } from '../../api/server/api-request-token.provider.js';
10
11
  import { configureApiServer } from '../../api/server/module.js';
@@ -88,6 +89,11 @@ async function bootstrap() {
88
89
  configurePostgresQueue();
89
90
  configureLocalMessageBus();
90
91
  configureDefaultSignalsImplementation();
92
+ configureGenkit({
93
+ gemini: {
94
+ apiKey: config.ai.apiKey,
95
+ },
96
+ });
91
97
  configureOrm({
92
98
  connection: {
93
99
  host: config.database.host,
@@ -1,7 +1,7 @@
1
1
  import { isIterable } from '../utils/iterable-helpers/is-iterable.js';
2
2
  import { assertDefinedPass, isArray, isDefined, isString, isSymbol, isUndefined } from '../utils/type-guards.js';
3
3
  const numberPattern = /^\d+$/u;
4
- const parsePattern = /(?:(?:^|\.)(?<dot>[^.[]+))|(?<root>^\$)|\[(?:(?:'(?<bracket>.+?)')|(?<index>\d+)|(?:Symbol\((?<symbol>.*)\)))\]|(?<error>.+?)/ug;
4
+ const parsePattern = /(?:(?:^|\.)(?<dot>[^.[]+))|(?<root>^\$)|\[(?:(?:['"](?<bracket>.+?)['"])|(?<index>\d+)|(?:Symbol\((?<symbol>.*)\)))\]|(?<error>.+?)/ug;
5
5
  export class JsonPath {
6
6
  _options;
7
7
  _path;
@@ -63,10 +63,8 @@ export type OrmColumnReflectionData = {
63
63
  type: AbstractConstructor;
64
64
  prefix?: string | null;
65
65
  };
66
- references?: {
67
- target: () => EntityType;
68
- targetColumn?: TargetColumnPath<any>;
69
- }[];
66
+ references?: ReferenceReflectionData[];
67
+ tenantReference?: TypedOmit<ReferenceReflectionData, 'excludeTenant'>[];
70
68
  paradeField?: ParadeFieldOptions;
71
69
  tsVector?: TsVectorOptions<any>;
72
70
  encrypted?: boolean;
@@ -75,6 +73,11 @@ export type OrmColumnReflectionData = {
75
73
  mode: 'soft' | 'hard';
76
74
  };
77
75
  };
76
+ type ReferenceReflectionData<T extends AnyEntity = AnyEntity> = {
77
+ target: () => EntityType<T>;
78
+ targetColumn?: TargetColumnPath<T>;
79
+ excludeTenant?: boolean;
80
+ };
78
81
  /**
79
82
  * Reflection data for unique constraints.
80
83
  */
@@ -236,8 +239,17 @@ export declare function PrimaryKeyProperty(): PropertyDecorator;
236
239
  * Define a foreign key relationship.
237
240
  * @param type A function returning the referenced entity type.
238
241
  */
239
- export declare function References(target: () => EntityType): PropertyDecorator;
240
- export declare function References<T extends AnyEntity>(target: () => EntityType<T>, targetColumn?: TargetColumnPath<T>): PropertyDecorator;
242
+ export declare function Reference<T extends AnyEntity>(target: () => EntityType<T>, targetColumn?: TargetColumnPath<T>): PropertyDecorator;
243
+ export declare function Reference<T extends AnyEntity>(target: () => EntityType, options?: TypedOmit<ReferenceReflectionData<T>, 'target'>): PropertyDecorator;
244
+ export {
245
+ /** @deprecated use {@link Reference} instead. */
246
+ Reference as References };
247
+ /**
248
+ * Define a foreign key relationship.
249
+ * @param type A function returning the referenced entity type.
250
+ */
251
+ export declare function TenantReference(target: () => EntityType): PropertyDecorator;
252
+ export declare function TenantReference<T extends AnyEntity>(target: () => EntityType<T>, targetColumn?: TargetColumnPath<T>): PropertyDecorator;
241
253
  /**
242
254
  * Define a table check constraint.
243
255
  * @template T The entity type.
@@ -375,4 +387,3 @@ export declare function ParadeIndex<T extends BaseEntity>(options: ParadeIndexRe
375
387
  export declare function ParadeIndex(options?: ParadeFieldOptions): PropertyDecorator;
376
388
  export declare function ParadeCompoundIndex<T extends BaseEntity>(alias: string, compoundColumns: ParadeIndexCompoundColumnColumnsProvider<T>, options?: TypedOmit<ParadeFieldOptions, 'alias'>): ClassDecorator;
377
389
  export declare function ParadeExpressionIndex<T extends BaseEntity>(alias: string, expression: ParadeIndexExpressionProvider<T>, options?: TypedOmit<ParadeFieldOptions, 'alias'>): ClassDecorator;
378
- export {};
package/orm/decorators.js CHANGED
@@ -68,8 +68,16 @@ export function Column(options) {
68
68
  export function PrimaryKeyProperty() {
69
69
  return createColumnDecorator({ primaryKey: true });
70
70
  }
71
- export function References(target, targetColumn) {
72
- return createColumnDecorator({ references: [{ target, targetColumn }] });
71
+ export function Reference(target, targetColumnOrOptions) {
72
+ const targetColumn = (isString(targetColumnOrOptions) ? targetColumnOrOptions : targetColumnOrOptions?.targetColumn);
73
+ const options = isString(targetColumnOrOptions) ? undefined : targetColumnOrOptions;
74
+ return createColumnDecorator({ references: [{ target, targetColumn, excludeTenant: options?.excludeTenant }] });
75
+ }
76
+ export {
77
+ /** @deprecated use {@link Reference} instead. */
78
+ Reference as References };
79
+ export function TenantReference(target, targetColumn) {
80
+ return createColumnDecorator({ tenantReference: [{ target, targetColumn: targetColumn }] });
73
81
  }
74
82
  /**
75
83
  * Define a table check constraint.
package/orm/entity.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import type { Type } from '../types/index.js';
1
+ import type { AbstractType } from '../types/index.js';
2
2
  import type { Embedded, HasDefault, IsPrimaryKey, Json, Timestamp, Uuid } from './types.js';
3
3
  /**
4
4
  * Represents the type (constructor) of an entity, potentially holding an entity name.
5
5
  * @template T - The entity class type.
6
6
  */
7
- export interface EntityType<T extends BaseEntity = BaseEntity | Entity> extends Type<T> {
7
+ export interface EntityType<T extends BaseEntity = BaseEntity | Entity> extends AbstractType<T> {
8
8
  readonly entityName?: string;
9
9
  }
10
10
  export type AnyEntity = BaseEntity | Entity;
package/orm/entity.js CHANGED
@@ -81,6 +81,7 @@ export class TenantEntity extends Entity {
81
81
  tenantId;
82
82
  }
83
83
  __decorate([
84
+ PrimaryKeyProperty(),
84
85
  UuidProperty(),
85
86
  __metadata("design:type", String)
86
87
  ], TenantEntity.prototype, "tenantId", void 0);
@@ -88,6 +89,7 @@ export class TenantBaseEntity extends BaseEntity {
88
89
  tenantId;
89
90
  }
90
91
  __decorate([
92
+ PrimaryKeyProperty(),
91
93
  UuidProperty(),
92
94
  __metadata("design:type", String)
93
95
  ], TenantBaseEntity.prototype, "tenantId", void 0);
@@ -1,9 +1,9 @@
1
1
  import { type PgEnum, type PgSchema, type PgTableWithColumns } from 'drizzle-orm/pg-core';
2
- import type { AbstractConstructor, Enumeration } from '../../../types/index.js';
3
- import type { EntityType } from '../../entity.js';
2
+ import type { Enumeration } from '../../../types/index.js';
3
+ import { type EntityType } from '../../entity.js';
4
4
  import type { ColumnDefinition, ColumnDefinitionsMap, PgTableFromType } from '../types.js';
5
5
  type ConverterContext = {
6
- type: AbstractConstructor;
6
+ type: EntityType;
7
7
  property: string;
8
8
  };
9
9
  export declare const getDrizzleTableFromType: typeof _getDrizzleTableFromType;
@@ -11,11 +11,13 @@ import { compareByValueSelectionToOrder, orderRest } from '../../../utils/compar
11
11
  import { decodeText, encodeUtf8 } from '../../../utils/encoding.js';
12
12
  import { enumValues } from '../../../utils/enum.js';
13
13
  import { memoize, memoizeSingle } from '../../../utils/function/memoize.js';
14
+ import { typeExtends } from '../../../utils/index.js';
14
15
  import { compileDereferencer } from '../../../utils/object/dereference.js';
15
16
  import { fromEntries, mapObjectKeysToSnakeCase, objectEntries } from '../../../utils/object/object.js';
16
17
  import { assertDefined, assertDefinedPass, isArray, isDefined, isNotNull, isNotNullOrUndefined, isNull, isString, isUndefined } from '../../../utils/type-guards.js';
17
18
  import { resolveValueOrProvider } from '../../../utils/value-or-provider.js';
18
19
  import { bytea, numericDate, timestamp, tsvector } from '../../data-types/index.js';
20
+ import { TenantBaseEntity, TenantEntity } from '../../entity.js';
19
21
  import { getEnumName } from '../../enums.js';
20
22
  import { JsonSchema, NumericDateSchema, NumericSchema, TimestampSchema, TsVectorSchema, UuidSchema } from '../../schemas/index.js';
21
23
  import { decryptBytes, encryptBytes } from '../encryption.js';
@@ -87,7 +89,9 @@ export function _getDrizzleTableFromType(type, fallbackSchemaName) {
87
89
  return builder;
88
90
  }
89
91
  function buildPrimaryKey(table) {
90
- const columns = primaryKeyColumnDefinitions.map((columnDefinition) => table[columnDefinition.name]);
92
+ const columns = primaryKeyColumnDefinitions
93
+ .toSorted(compareByValueSelectionToOrder(['tenantId', 'id', orderRest], (columnDefinition) => columnDefinition.name))
94
+ .map((columnDefinition) => table[columnDefinition.name]);
91
95
  return primaryKey({
92
96
  name: mergedTableReflectionData.compoundPrimaryKeyName ?? getPrimaryKeyName(tableName, columns, { naming: mergedTableReflectionData.compoundPrimaryKeyNaming }),
93
97
  columns,
@@ -185,6 +189,17 @@ export function _getDrizzleTableFromType(type, fallbackSchemaName) {
185
189
  }
186
190
  return buildIndex(table, indexData, columnDefinition.name);
187
191
  }).filter(isDefined)),
192
+ ...columnDefinitions.flatMap((columnDefinition) => {
193
+ return columnDefinition.reflectionData?.tenantReference?.map((tenantReferenceData) => {
194
+ const foreignTable = getDrizzleTableFromType(tenantReferenceData.target(), dbSchema.schemaName);
195
+ const nonTenantColumn = tenantReferenceData.targetColumn ?? 'id';
196
+ return foreignKey({
197
+ name: getForeignKeyName(tableName, [nonTenantColumn]),
198
+ columns: [getColumn(table, 'tenantId'), getColumn(table, columnDefinition.name)],
199
+ foreignColumns: [getColumn(foreignTable, 'tenantId'), getColumn(foreignTable, nonTenantColumn)],
200
+ });
201
+ }) ?? [];
202
+ }),
188
203
  ...tableReflectionDatas.flatMap((tableReflectionData) => {
189
204
  return tableReflectionData.foreignKeys?.map((foreignKeyData) => {
190
205
  const foreignTable = getDrizzleTableFromType(foreignKeyData.target(), dbSchema.schemaName);
@@ -283,14 +298,16 @@ function getPostgresColumn(tableName, columnName, dbSchema, propertySchema, refl
283
298
  if ((reflectionData.primaryKey == true) && (options.skipPrimaryKey != true)) {
284
299
  column = column.primaryKey();
285
300
  }
286
- for (const { target, targetColumn } of reflectionData.references ?? []) {
301
+ for (const { target, targetColumn, excludeTenant } of reflectionData.references ?? []) {
287
302
  column = column.references(() => {
288
- const targetTable = getDrizzleTableFromType(target(), dbSchema.schemaName);
303
+ const targetType = target();
304
+ if ((excludeTenant != true) && (typeExtends(context.type, TenantBaseEntity) || typeExtends(context.type, TenantEntity)) && (typeExtends(targetType, TenantBaseEntity) || typeExtends(targetType, TenantEntity))) {
305
+ throw new Error(`${context.type.entityName ?? context.type.name} references ${targetType.entityName ?? targetType.name} via ${targetColumn ?? 'id'} without tenantId. This may lead to data integrity issues. Use \`@TenantReference()\` or set \`excludeTenant: true\` in the Reference decorator options to avoid this warning.`);
306
+ }
307
+ const targetTable = getDrizzleTableFromType(targetType, dbSchema.schemaName);
289
308
  return targetTable[(targetColumn ?? 'id')];
290
309
  });
291
310
  }
292
- if (isDefined(reflectionData.references)) {
293
- }
294
311
  return column;
295
312
  }
296
313
  function getPostgresBaseColumn(columnName, dbSchema, schema, reflectionData, context) {
@@ -11,12 +11,11 @@ import { NotFoundError } from '../../errors/not-found.error.js';
11
11
  import { Singleton } from '../../injector/decorators.js';
12
12
  import { inject, injectArgument } from '../../injector/inject.js';
13
13
  import { afterResolve, resolveArgumentType } from '../../injector/interfaces.js';
14
- import { Schema } from '../../schema/schema.js';
15
14
  import { distinct, toArray } from '../../utils/array/array.js';
16
15
  import { mapAsync } from '../../utils/async-iterable-helpers/map.js';
17
16
  import { toArrayAsync } from '../../utils/async-iterable-helpers/to-array.js';
18
17
  import { importSymmetricKey } from '../../utils/cryptography.js';
19
- import { fromDeepObjectEntries, fromEntries, objectEntries } from '../../utils/object/object.js';
18
+ import { assignDeep, fromEntries, objectEntries } from '../../utils/object/object.js';
20
19
  import { toSnakeCase } from '../../utils/string/index.js';
21
20
  import { cancelableTimeout } from '../../utils/timing.js';
22
21
  import { tryIgnoreAsync } from '../../utils/try-ignore.js';
@@ -1073,14 +1072,13 @@ let EntityRepository = class EntityRepository extends Transactional {
1073
1072
  return await toArrayAsync(mapAsync(columns, async (column) => await this._mapToEntity(column, transformContext)));
1074
1073
  }
1075
1074
  async _mapToEntity(columns, transformContext) {
1076
- const entries = [];
1075
+ const entity = new this.type();
1077
1076
  for (const def of this.#columnDefinitions) {
1078
1077
  const rawValue = columns[def.name];
1079
1078
  const transformed = await def.fromDatabase(rawValue, transformContext);
1080
- entries.push([def.objectPath, transformed]); // eslint-disable-line @typescript-eslint/no-unsafe-argument
1079
+ assignDeep(entity, def.objectPath, transformed);
1081
1080
  }
1082
- const obj = fromDeepObjectEntries(entries);
1083
- return Schema.parse(this.type, obj);
1081
+ return entity;
1084
1082
  }
1085
1083
  async _mapManyToColumns(objects, transformContext) {
1086
1084
  return await toArrayAsync(mapAsync(objects, async (obj) => await this._mapToColumns(obj, transformContext)));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tstdl/base",
3
- "version": "0.93.61",
3
+ "version": "0.93.64",
4
4
  "author": "Patrick Hein",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -37,6 +37,7 @@
37
37
  "./supports": "./supports.js",
38
38
  "./tokens": "./tokens.js",
39
39
  "./ai": "./ai/index.js",
40
+ "./ai/genkit": "./ai/genkit/index.js",
40
41
  "./api": "./api/index.js",
41
42
  "./api/client": "./api/client/index.js",
42
43
  "./api/server": "./api/server/index.js",
@@ -138,18 +139,21 @@
138
139
  "type-fest": "^5.3"
139
140
  },
140
141
  "peerDependencies": {
141
- "@google-cloud/storage": "^7.17",
142
- "@google/genai": "^1.30",
142
+ "@genkit-ai/google-genai": "^1.25",
143
+ "@google-cloud/storage": "^7.18",
144
+ "@google/genai": "^1.32",
145
+ "@toon-format/toon": "^2.1.0",
143
146
  "@tstdl/angular": "^0.93",
144
147
  "@zxcvbn-ts/core": "^3.0",
145
148
  "@zxcvbn-ts/language-common": "^3.0",
146
149
  "@zxcvbn-ts/language-de": "^3.0",
147
150
  "@zxcvbn-ts/language-en": "^3.0",
148
- "drizzle-orm": "^0.44",
151
+ "drizzle-orm": "^0.45",
149
152
  "file-type": "^21.1",
153
+ "genkit": "^1.25",
150
154
  "handlebars": "^4.7",
151
155
  "minio": "^8.0",
152
- "mjml": "^4.17",
156
+ "mjml": "^4.18",
153
157
  "nodemailer": "^7.0",
154
158
  "pg": "^8.16",
155
159
  "playwright": "^1.57",
@@ -158,7 +162,7 @@
158
162
  "sharp": "^0.34",
159
163
  "undici": "^7.16",
160
164
  "urlpattern-polyfill": "^10.1",
161
- "zod": "^4.1"
165
+ "zod": "^3.25"
162
166
  },
163
167
  "peerDependenciesMeta": {
164
168
  "@tstdl/angular": {
@@ -182,7 +186,7 @@
182
186
  "typedoc-plugin-markdown": "4.9",
183
187
  "typedoc-plugin-missing-exports": "4.1",
184
188
  "typescript": "5.9",
185
- "typescript-eslint": "8.48"
189
+ "typescript-eslint": "8.49"
186
190
  },
187
191
  "overrides": {
188
192
  "drizzle-kit": {
package/pdf/utils.js CHANGED
@@ -149,5 +149,5 @@ export async function pdfToImage(file, page, size, format) {
149
149
  if (isNotString(file)) {
150
150
  process.autoWrite(file);
151
151
  }
152
- return process.readOutputBytes();
152
+ return await process.readOutputBytes();
153
153
  }
@@ -1,4 +1,4 @@
1
- import { z } from 'zod';
1
+ import { z } from 'zod/v4';
2
2
  import type { SchemaTestable } from '../schema.js';
3
3
  export type SchemaConversionOptions = {
4
4
  /** Default coerce option if not specified in schema */
@@ -1,11 +1,11 @@
1
1
  import { match, P } from 'ts-pattern';
2
- import { z } from 'zod';
2
+ import { z } from 'zod/v4';
3
3
  import { NotSupportedError } from '../../errors/not-supported.error.js';
4
4
  import { JsonPath } from '../../json-path/json-path.js';
5
5
  import { objectEntries, objectKeys } from '../../utils/object/object.js';
6
6
  import { isArray, isInstanceOf, isNotNull, isNumber, isString } from '../../utils/type-guards.js';
7
7
  import { SchemaError } from '../schema.error.js';
8
- import { any, AnySchema, ArraySchema, BigIntSchema, BooleanSchema, ConstraintSchema, DateSchema, DefaultSchema, DeferredSchema, EnumerationSchema, FunctionSchema, InstanceSchema, LiteralSchema, NeverSchema, NullableSchema, NumberSchema, ObjectSchema, OneOrManySchema, OptionalSchema, ReadableStreamSchema, RegExpSchema, StringSchema, SymbolSchema, TransformSchema, Uint8ArraySchema, UnionSchema, UnknownSchema } from '../schemas/index.js';
8
+ import { any, AnySchema, ArraySchema, BigIntSchema, BooleanSchema, ConstraintSchema, DateSchema, DefaultSchema, DeferredSchema, EnumerationSchema, InstanceSchema, LiteralSchema, NeverSchema, NullableSchema, NumberSchema, ObjectSchema, OneOrManySchema, OptionalSchema, ReadableStreamSchema, RegExpSchema, StringSchema, SymbolSchema, TransformSchema, Uint8ArraySchema, UnionSchema, UnknownSchema } from '../schemas/index.js';
9
9
  import { schemaTestableToSchema } from '../testable.js';
10
10
  export function convertToZodSchema(testable, options) {
11
11
  const schema = schemaTestableToSchema(testable);
@@ -143,17 +143,6 @@ function convertToZodSchemaBase(schema, options) {
143
143
  // enumeration is either EnumerationObject or string-only EnumerationArray, both is fine for z.enum
144
144
  // using `as`, as z.enum is overloaded and only one type per overload
145
145
  return z.enum(s.enumeration);
146
- })
147
- .with(P.instanceOf(FunctionSchema), (s) => {
148
- let zodSchema = z.function();
149
- if (isNotNull(s.parameterSchemas)) {
150
- const args = s.parameterSchemas.map((parameterSchema) => convertToZodSchemaBase(parameterSchema, options));
151
- zodSchema = zodSchema.input(...args);
152
- }
153
- if (isNotNull(s.returnValueSchema)) {
154
- zodSchema = zodSchema.output(convertToZodSchemaBase(s.returnValueSchema, options));
155
- }
156
- return zodSchema;
157
146
  })
158
147
  .with(P.instanceOf(DefaultSchema), (s) => convertToZodSchemaBase(s.schema, options).default(s.defaultValue))
159
148
  .with(P.instanceOf(TransformSchema), (s) => convertToZodSchemaBase(s.schema, options).transform((input) => s.transformFn(input)))
@@ -1,4 +1,4 @@
1
- import { z, type ZodTypeDef } from 'zod/v3';
1
+ import { type ZodObject, type ZodType, type ZodTypeDef } from 'zod/v3';
2
2
  import type { Record } from '../../types/types.js';
3
3
  import type { SchemaTestable } from '../schema.js';
4
4
  import { ObjectSchema } from '../schemas/index.js';
@@ -9,5 +9,5 @@ export type SchemaConversionOptions = {
9
9
  mask?: boolean;
10
10
  };
11
11
  /** WARNING: *DOES NOT* cover all schemas and options. Meant for usage in schema generators like genkit, not for full schema testing in APIs etc. */
12
- export declare function convertToZodV3Schema<T extends Record>(testable: ObjectSchema<T>, options?: SchemaConversionOptions): z.ZodObject<any, any, any, T>;
13
- export declare function convertToZodV3Schema<O, I = unknown>(testable: SchemaTestable<O>, options?: SchemaConversionOptions): z.ZodType<O, ZodTypeDef, I>;
12
+ export declare function convertToZodV3Schema<T extends Record>(testable: ObjectSchema<T>, options?: SchemaConversionOptions): ZodObject<any, any, any, T>;
13
+ export declare function convertToZodV3Schema<O, I = unknown>(testable: SchemaTestable<O>, options?: SchemaConversionOptions): ZodType<O, ZodTypeDef, I>;
@@ -1,4 +1,3 @@
1
1
  export declare function readAsText(blob: Blob, encoding?: string): Promise<string>;
2
2
  export declare function readAsArrayBuffer(blob: Blob): Promise<ArrayBuffer>;
3
- export declare function readAsBinaryString(blob: Blob): Promise<string>;
4
3
  export declare function readAsDataUrl(blob: Blob): Promise<string>;
@@ -1,18 +1,15 @@
1
1
  import { DetailsError } from '../errors/details.error.js';
2
2
  export async function readAsText(blob, encoding) {
3
- return setup((reader) => reader.readAsText(blob, encoding));
3
+ return await setup((reader) => reader.readAsText(blob, encoding));
4
4
  }
5
5
  export async function readAsArrayBuffer(blob) {
6
- return setup((reader) => reader.readAsArrayBuffer(blob));
7
- }
8
- export async function readAsBinaryString(blob) {
9
- return setup((reader) => reader.readAsBinaryString(blob));
6
+ return await setup((reader) => reader.readAsArrayBuffer(blob));
10
7
  }
11
8
  export async function readAsDataUrl(blob) {
12
- return setup((reader) => reader.readAsDataURL(blob));
9
+ return await setup((reader) => reader.readAsDataURL(blob));
13
10
  }
14
11
  async function setup(dispatcher) {
15
- return new Promise((resolve, reject) => {
12
+ return await new Promise((resolve, reject) => {
16
13
  const reader = new FileReader();
17
14
  reader.onload = () => resolve(reader.result);
18
15
  reader.onerror = () => reject(new DetailsError(reader.error.message, reader.error));
@@ -30,6 +30,8 @@ export declare function filterNullishObjectProperties<T extends ObjectLiteral>(o
30
30
  export declare function copyObjectProperties<T extends ObjectLiteral>(source: T, target: T): void;
31
31
  export declare function getGetter<T extends ObjectLiteral, U extends keyof T>(obj: T, property: U, bind: boolean): () => T[U];
32
32
  export declare function deepObjectEntries(object: ObjectLiteral, keepInnerObjects?: boolean, prefix?: string): [string, any][];
33
+ export declare function assignDeep(target: object, path: JsonPathInput, value: any): void;
34
+ export declare function assignDeepObjectEntries(target: object, entries: readonly (readonly [JsonPathInput, any])[]): void;
33
35
  export declare function fromDeepObjectEntries(entries: readonly (readonly [JsonPathInput, any])[]): ObjectLiteral;
34
- export declare function omit<T extends Record, K extends keyof T>(object: T, ...keys: K[]): SimplifyObject<Omit<T, K>>;
35
- export declare function pick<T extends Record, K extends keyof T>(object: T, ...keys: K[]): SimplifyObject<Pick<T, K>>;
36
+ export declare function omit<T extends Record, K extends keyof T>(object: T, keys: K[]): SimplifyObject<Omit<T, K>>;
37
+ export declare function pick<T extends Record, K extends keyof T>(object: T, keys: K[]): SimplifyObject<Pick<T, K>>;