vsrepo 1.2.7 → 1.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Tipos literais que representam os códigos de erro internos da biblioteca.
2
+ * Literal types representing the internal error codes of the library.
3
3
  */
4
4
  export type VSRepoErrorType =
5
5
  | 'VSREPO_CONFIG'
@@ -8,18 +8,18 @@ export type VSRepoErrorType =
8
8
  | 'VSREPO_RUNTIME';
9
9
 
10
10
  /**
11
- * Classe base para todos os erros lançados pelo Virtual Schema Repository.
11
+ * Base class for all errors thrown by the VSRepository.
12
12
  */
13
13
  export declare abstract class VSRepoError extends Error {
14
- /** Código interno usado para identificar a categoria do erro. */
14
+ /** Internal code used to identify the error category. */
15
15
  abstract readonly type: VSRepoErrorType;
16
16
 
17
17
  constructor(message: string, type: VSRepoErrorType);
18
18
  }
19
19
 
20
20
  /**
21
- * Lançado quando uma configuração inválida ou uma inconsistência de
22
- * configuração é detectada antes ou durante a inicialização do repositório.
21
+ * Thrown when an invalid configuration or a configuration inconsistency
22
+ * is detected before or during repository initialization.
23
23
  */
24
24
  export declare class VSRepoConfigError extends VSRepoError {
25
25
  readonly type: 'VSREPO_CONFIG';
@@ -27,8 +27,8 @@ export declare class VSRepoConfigError extends VSRepoError {
27
27
  }
28
28
 
29
29
  /**
30
- * Lançado quando a injeção da instância do Prisma falha ou quando o
31
- * repositório não pode ser finalizado por meio de `.build()`.
30
+ * Thrown when the Prisma instance injection fails or when the
31
+ * build configuration is incorrect in the `.build()`.
32
32
  */
33
33
  export declare class VSRepoBuildError extends VSRepoError {
34
34
  readonly type: 'VSREPO_BUILD';
@@ -36,8 +36,8 @@ export declare class VSRepoBuildError extends VSRepoError {
36
36
  }
37
37
 
38
38
  /**
39
- * Lançado quando ocorre um erro ao injetar novos métodos no repositório
40
- * por meio de `.extend()`.
39
+ * Thrown when an error occurs while injecting new methods into the repository
40
+ * via `.extend()`.
41
41
  */
42
42
  export declare class VSRepoExtendError extends VSRepoError {
43
43
  readonly type: 'VSREPO_EXTEND';
@@ -45,8 +45,8 @@ export declare class VSRepoExtendError extends VSRepoError {
45
45
  }
46
46
 
47
47
  /**
48
- * Lançado quando operações dinâmicas falham em tempo de execução, como
49
- * quando argumentos inválidos são passados para métodos.
48
+ * Thrown when dynamic operations fail at runtime, such as
49
+ * when invalid arguments are passed to methods.
50
50
  */
51
51
  export declare class VSRepoRuntimeError extends VSRepoError {
52
52
  readonly type: 'VSREPO_RUNTIME';
@@ -2,8 +2,8 @@ import { Prisma, PrismaClient } from '../generated/prisma/client';
2
2
  import { Decimal, JsonValue } from '@prisma/client/runtime/client';
3
3
 
4
4
  /**
5
- * Achata uma interseção de tipos em um único objeto,
6
- * evitando o erro "union type too complex to represent" do TypeScript.
5
+ * Flattens a type intersection into a single object,
6
+ * avoiding the TypeScript "union type too complex to represent" error.
7
7
  */
8
8
  type Simplify<T> = { [K in keyof T]: T[K] } & {};
9
9
 
@@ -16,17 +16,17 @@ type WidenField<T> =
16
16
  T;
17
17
 
18
18
  /**
19
- * Instância completa do Prisma Client usada para construir repositories.
19
+ * Full Prisma Client instance used to build repositories.
20
20
  */
21
21
  export type DbClient = PrismaClient;
22
22
 
23
23
  /**
24
- * Cliente transacional do Prisma retornado por `prisma.$transaction`.
24
+ * Prisma transactional client returned by `prisma.$transaction`.
25
25
  */
26
26
  export type DbTransaction = Prisma.TransactionClient;
27
27
 
28
28
  /**
29
- * Aceita tanto o cliente principal do Prisma quanto um cliente de transação.
29
+ * Accepts either the main Prisma client or a transaction client.
30
30
  */
31
31
  export type ClientOrTransaction = DbClient | DbTransaction;
32
32
 
@@ -37,32 +37,32 @@ type OrderPattern = {
37
37
  };
38
38
 
39
39
  /**
40
- * Opções de paginação aceitas pelos métodos com sufixo `Paginated`.
40
+ * Pagination options accepted by methods with the `Paginated` suffix.
41
41
  *
42
- * @template TCursor Tipo do cursor usado pelo modelo Prisma.
42
+ * @template TCursor Type of the cursor used by the Prisma model.
43
43
  */
44
44
  export type PaginationOptions<TCursor = unknown> = {
45
- /** Quantidade de registros a ignorar. */
45
+ /** Number of records to skip. */
46
46
  skip?: number;
47
- /** Quantidade máxima de registros retornados. */
47
+ /** Maximum number of records to return. */
48
48
  take?: number;
49
- /** Cursor tipado para paginação baseada em posição. */
49
+ /** Typed cursor for position-based pagination. */
50
50
  cursor?: TCursor;
51
51
  };
52
52
 
53
53
  /**
54
- * Ordenação aceita pelos métodos do repository.
54
+ * Ordering accepted by repository methods.
55
55
  *
56
- * Pode ser uma única ordenação ou uma lista de ordenações encadeadas.
56
+ * Can be a single ordering or a list of chained orderings.
57
57
  */
58
58
  export type OrderOptions = OrderPattern | OrderPattern[];
59
59
 
60
60
  /**
61
- * Modo de visibilidade para registros com soft-delete.
61
+ * Visibility mode for records with soft-delete.
62
62
  *
63
- * - `"active"` — retorna apenas registros não removidos (padrão).
64
- * - `"removed"` — retorna apenas registros removidos.
65
- * - `"all"` — retorna todos os registros, independentemente do status.
63
+ * - `"active"` — returns only non-deleted records (default).
64
+ * - `"removed"` — returns only deleted records.
65
+ * - `"all"` — returns all records regardless of their status.
66
66
  */
67
67
  export type SeeMode = 'active' | 'removed' | 'all';
68
68
 
@@ -239,41 +239,41 @@ type CleanFields<R extends string> =
239
239
  R extends `${infer F}SkipDuplicates` ? F : R;
240
240
 
241
241
  /**
242
- * Opções adicionais aceitas pelos métodos do repository.
242
+ * Additional options accepted by repository methods.
243
243
  *
244
- * @template S Chaves disponíveis em `selectModels`.
244
+ * @template S Available keys in `selectModels`.
245
245
  */
246
246
  export type MethodOptions<S> = {
247
247
  /**
248
- * Select model a ser aplicado na operação.
248
+ * Select model to apply to the operation.
249
249
  *
250
- * @note Use `false` para retornar o payload completo do Prisma, sem select.
250
+ * @note Use `false` to return the full Prisma payload without a select.
251
251
  */
252
252
  selectModel?: S | false;
253
253
  /**
254
- * Cliente Prisma ou transação que deve executar a operação.
254
+ * Prisma client or transaction to use for the operation.
255
255
  */
256
256
  db?: ClientOrTransaction;
257
257
  /**
258
- * Modo de visibilidade para registros com soft-delete.
258
+ * Visibility mode for records with soft-delete.
259
259
  *
260
- * Só tem efeito se `softRemovekName` estiver configurado no repository.
260
+ * Only takes effect if `softRemovekName` is configured on the repository.
261
261
  *
262
- * - `"active"` — retorna apenas registros não removidos (padrão).
263
- * - `"removed"` — retorna apenas registros removidos.
264
- * - `"all"` — retorna todos os registros, ignorando o status de remoção.
262
+ * - `"active"` — returns only non-deleted records (default).
263
+ * - `"removed"` — returns only deleted records.
264
+ * - `"all"` — returns all records, ignoring deletion status.
265
265
  */
266
266
  see?: SeeMode;
267
267
  };
268
268
 
269
269
  /**
270
- * Versão de `MethodOptions` derivada diretamente de uma instância configurada de `VSRepository`.
270
+ * Version of `MethodOptions` derived directly from a configured `VSRepository` instance.
271
271
  *
272
- * @template TRepo Instância de `VSRepository` configurada (use `typeof meuVSRepo`).
272
+ * @template TRepo Configured `VSRepository` instance (use `typeof myVSRepo`).
273
273
  *
274
274
  * @example
275
- * const usuarioVSRepo = setupVSRepo<Usuario, "usuario">()(config);
276
- * type Opts = MethodOptionsModel<typeof usuarioVSRepo>;
275
+ * const userVSRepo = setupVSRepo<User, "user">()(config);
276
+ * type Opts = MethodOptionsModel<typeof userVSRepo>;
277
277
  */
278
278
  export type MethodOptionsModel<TRepo> =
279
279
  TRepo extends VSRepository<any, any, infer Config>
@@ -335,7 +335,7 @@ type ExtractPatternBase<K extends string> =
335
335
  type MethodFactory<T, M extends Prisma.ModelName, K extends string, SelectModels, DefaultSelect extends keyof SelectModels | false, I, MethodConf> =
336
336
  K extends `findWhere${string}`
337
337
  ? {
338
- /** @deprecated Use findOneWhere em seu lugar. */
338
+ /** @deprecated Use findOneWhere instead. */
339
339
  <S extends keyof SelectModels | false = DefaultSelect>(...args: [...ExtractFields<T, CleanFields<ExtractPatternBase<K>>, I>, ...ExtraArgs<GetMappedMethod<K, MethodConf>, ExtractPatternBase<K>, I>, options?: MethodOptions<S>]): Promise<ResolveReturnType<GetMappedMethod<K, MethodConf>, SelectedModel<M, S, SelectModels>>>;
340
340
  }
341
341
  : MethodFn<GetMappedMethod<K, MethodConf>, T, M, ExtractPatternBase<K>, SelectModels, DefaultSelect, I>;
@@ -377,148 +377,148 @@ type DynamicMethods<T, M extends Prisma.ModelName, Config, I> = Config extends {
377
377
  : {};
378
378
 
379
379
  /**
380
- * Agrupa os principais tipos de input do Prisma derivados de um modelo.
380
+ * Groups the main Prisma input types derived from a model.
381
381
  *
382
- * @template M Nome do modelo Prisma.
382
+ * @template M Prisma model name.
383
383
  */
384
384
  export type PrismaModelInputs<M extends Prisma.ModelName> = {
385
- /** Tipo do argumento `select` usado em consultas do modelo. */
385
+ /** Type of the `select` argument used in model queries. */
386
386
  select: Prisma.TypeMap['model'][M]['operations']['findMany']['args']['select'];
387
- /** Tipo do `data` usado em `create`. */
387
+ /** Type of the `data` used in `create`. */
388
388
  createInput: Prisma.TypeMap['model'][M]['operations']['create']['args']['data'];
389
- /** Tipo do `data` usado em `createMany`. */
389
+ /** Type of the `data` used in `createMany`. */
390
390
  createManyInput: Prisma.TypeMap['model'][M]['operations']['createMany']['args']['data'];
391
- /** Tipo do `data` usado em `update`. */
391
+ /** Type of the `data` used in `update`. */
392
392
  updateInput: Prisma.TypeMap['model'][M]['operations']['update']['args']['data'];
393
- /** Tipo do `data` usado em `updateMany`. */
393
+ /** Type of the `data` used in `updateMany`. */
394
394
  updateManyInput: Prisma.TypeMap['model'][M]['operations']['updateMany']['args']['data'];
395
- /** Tipo do `where` usado nas buscas do modelo. */
395
+ /** Type of the `where` used in model queries. */
396
396
  whereInput: Prisma.TypeMap['model'][M]['operations']['findMany']['args']['where'];
397
- /** Tipo do `orderBy` usado nas buscas do modelo. */
397
+ /** Type of the `orderBy` used in model queries. */
398
398
  orderByInput: Prisma.TypeMap['model'][M]['operations']['findMany']['args']['orderBy'];
399
- /** Tipo do cursor usado nas buscas do modelo. */
399
+ /** Type of the cursor used in model queries. */
400
400
  cursorInput: Prisma.TypeMap['model'][M]['operations']['findMany']['args']['cursor'];
401
- /** Tipo do payload `create` usado em `upsert`. */
401
+ /** Type of the `create` payload used in `upsert`. */
402
402
  upsertCreateInput: Prisma.TypeMap['model'][M]['operations']['upsert']['args']['create'];
403
- /** Tipo do payload `update` usado em `upsert`. */
403
+ /** Type of the `update` payload used in `upsert`. */
404
404
  upsertUpdateInput: Prisma.TypeMap['model'][M]['operations']['upsert']['args']['update'];
405
405
  };
406
406
 
407
407
  /**
408
- * Tipo do objeto `select` de um modelo Prisma.
408
+ * Type of the `select` object of a Prisma model.
409
409
  */
410
410
  export type SelectModel<M extends Prisma.ModelName> = PrismaModelInputs<M>['select'];
411
411
 
412
412
  /**
413
- * Mapa de selects nomeados e reutilizáveis para um modelo Prisma.
413
+ * Map of named, reusable selects for a Prisma model.
414
414
  */
415
415
  export type SelectModels<M extends Prisma.ModelName> = Record<string, SelectModel<M>>;
416
416
 
417
417
  /**
418
- * Tipo do objeto `where` de um modelo Prisma.
418
+ * Type of the `where` object of a Prisma model.
419
419
  */
420
420
  export type WhereModel<M extends Prisma.ModelName> = PrismaModelInputs<M>['whereInput'];
421
421
 
422
422
  /**
423
- * Tipo do objeto `orderBy` de um modelo Prisma.
423
+ * Type of the `orderBy` object of a Prisma model.
424
424
  */
425
425
  export type OrdenationModel<M extends Prisma.ModelName> = PrismaModelInputs<M>['orderByInput'];
426
426
 
427
427
  /**
428
- * Opções de paginação com cursor tipado para um modelo Prisma.
428
+ * Pagination options with typed cursor for a Prisma model.
429
429
  */
430
430
  export type PaginationModel<M extends Prisma.ModelName> = PaginationOptions<PrismaModelInputs<M>['cursorInput']>;
431
431
 
432
432
  /**
433
- * Payload base usado para criar um registro no `save`/`upsert` do modelo.
433
+ * Base payload used to create a record in the model's `save`/`upsert`.
434
434
  */
435
435
  export type ModelUpsertInput<M extends Prisma.ModelName> = PrismaModelInputs<M>['upsertCreateInput'];
436
436
 
437
437
  /**
438
- * Configuração de um método dinâmico definido em `methods`.
438
+ * Configuration for a dynamic method defined in `methods`.
439
439
  *
440
- * @template M Nome do modelo Prisma.
441
- * @template SelectModels Mapa de select models disponíveis no repository.
440
+ * @template M Prisma model name.
441
+ * @template SelectModels Map of select models available in the repository.
442
442
  */
443
443
  export type MethodConfig<M extends Prisma.ModelName, SelectModels = any> = {
444
- /** Define se o método será exposto no repository. */
444
+ /** Defines whether the method will be exposed on the repository. */
445
445
  readonly map: boolean;
446
- /** Sobrescreve o `defaultSelectModel` apenas para este método. */
446
+ /** Overrides `defaultSelectModel` for this method only. */
447
447
  readonly selectModel?: string | false;
448
- /** Controla se o método combina (`extending`) ou sobrescreve (`overwrite`) o `requiredWhere`. */
448
+ /** Controls whether the method combines (`extending`) or overwrites (`overwrite`) the `requiredWhere`. */
449
449
  readonly whereType?: 'overwrite' | 'extending';
450
- /** Redireciona a lógica para outro padrão de método válido. */
450
+ /** Redirects the logic to another valid method pattern. */
451
451
  readonly proxyTo?: ValidMethodPatterns;
452
- /** Adiciona um `where` extra além do `requiredWhere`. */
452
+ /** Adds an extra `where` on top of `requiredWhere`. */
453
453
  readonly pushWhere?: WhereModel<M>;
454
454
  /**
455
- * Define se `findBy` retorna um item (`one`) ou uma lista (`list`).
456
- * @deprecated Use `findOneBy` se quiser retornar um único resultado.
455
+ * Defines whether `findBy` returns a single item (`one`) or a list (`list`).
456
+ * @deprecated Use `findOneBy` if you want to return a single result.
457
457
  */
458
458
  readonly fbMode?: 'one' | 'list';
459
- /** Injeta uma ordenação fixa automaticamente na query. */
459
+ /** Injects a fixed ordering automatically into the query. */
460
460
  readonly injectOrdenation?: OrdenationModel<M>;
461
- /** Injeta uma paginação fixa automaticamente na query. */
461
+ /** Injects a fixed pagination automatically into the query. */
462
462
  readonly injectPagination?: PaginationModel<M>;
463
463
  };
464
464
 
465
465
  type BaseMethodConfig<TSelectKeys extends PropertyKey = string> = {
466
- /** Ativa ou desativa o método base no `build`. */
466
+ /** Enables or disables the base method in the `build`. */
467
467
  active?: boolean;
468
- /** Select model padrão usado pelo método base. */
468
+ /** Default select model used by the base method. */
469
469
  defaultSelect?: TSelectKeys;
470
- /** Ignora o `requiredWhere`. */
470
+ /** Ignores the `requiredWhere`. */
471
471
  ignoreRequiredWhere?: boolean;
472
472
  };
473
473
 
474
474
  /**
475
- * Configuração aplicada durante o `.build(prisma, config?)`.
475
+ * Configuration applied during `.build(prisma, config?)`.
476
476
  *
477
- * @template TSelectKeys Chaves válidas de `selectModels`.
477
+ * @template TSelectKeys Valid keys of `selectModels`.
478
478
  */
479
479
  export type BuildConfig<TSelectKeys extends PropertyKey = string> = {
480
480
  /**
481
- * Congela o objeto final do repository com `Object.freeze`.
482
- * @deprecated Não tem mais efeito prático na nova versão — o freeze é sempre aplicado.
481
+ * Freezes the final repository object with `Object.freeze`.
482
+ * @deprecated No longer has any practical effect in the next version — freeze will be always applied.
483
483
  */
484
484
  freeze?: boolean;
485
- /** Exibe logs internos de funcionamento no console. */
485
+ /** Prints internal working logs to the console. */
486
486
  showWorking?: boolean;
487
- /** Personaliza o comportamento dos métodos base automáticos. */
487
+ /** Customizes the behavior of the automatic base methods. */
488
488
  baseMethods?: {
489
- /** Configuração do método `get`. */
489
+ /** Configuration for the `get` method. */
490
490
  get?: BaseMethodConfig<TSelectKeys>;
491
- /** Configuração do método `getOrThrow`. */
491
+ /** Configuration for the `getOrThrow` method. */
492
492
  getOrThrow?: BaseMethodConfig<TSelectKeys>;
493
- /** Configuração do método `getList` (busca por lista de PKs). */
493
+ /** Configuration for the `getList` method (fetch by list of PKs). */
494
494
  getList?: BaseMethodConfig<TSelectKeys>;
495
- /** Configuração do método `remove`. */
495
+ /** Configuration for the `remove` method. */
496
496
  remove?: BaseMethodConfig<TSelectKeys>;
497
- /** Configuração do método `save`. */
497
+ /** Configuration for the `save` method. */
498
498
  save?: BaseMethodConfig<TSelectKeys>;
499
- /** Configuração do método `patch`. */
499
+ /** Configuration for the `patch` method. */
500
500
  patch?: BaseMethodConfig<TSelectKeys>;
501
- /** Configuração do método `merge`. */
501
+ /** Configuration for the `merge` method. */
502
502
  merge?: BaseMethodConfig<TSelectKeys>;
503
- /** Configuração do método `removeList` (exclusão em lote). Não aceita select. */
503
+ /** Configuration for the `removeList` method (batch deletion). Does not accept select. */
504
504
  removeList?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
505
- /** Configuração do método `getAll` (listagem total). */
505
+ /** Configuration for the `getAll` method (full listing). */
506
506
  getAll?: BaseMethodConfig<TSelectKeys>;
507
- /** Configuração do método `total` (contagem). Não aceita select. */
507
+ /** Configuration for the `total` method (count). Does not accept select. */
508
508
  total?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
509
- /** Configuração do método `has` (verificação de existência). Não aceita select. */
509
+ /** Configuration for the `has` method (existence check). Does not accept select. */
510
510
  has?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
511
- /** Configuração do método `saveList` (salvar em lote via transação). */
511
+ /** Configuration for the `saveList` method (batch save via transaction). */
512
512
  saveList?: BaseMethodConfig<TSelectKeys>;
513
- /** Configuração do método `patchList` (atualizar em lote via transação). */
513
+ /** Configuration for the `patchList` method (batch update via transaction). */
514
514
  patchList?: BaseMethodConfig<TSelectKeys>;
515
- /** Configuração do método `softRemove`. Só existe se `softRemovekName` estiver configurado. */
515
+ /** Configuration for the `softRemove` method. Only available if `softRemovekName` is configured. */
516
516
  softRemove?: BaseMethodConfig<TSelectKeys>;
517
- /** Configuração do método `softRemoveList`. Não aceita select. Só existe se `softRemovekName` estiver configurado. */
517
+ /** Configuration for the `softRemoveList` method. Does not accept select. Only available if `softRemovekName` is configured. */
518
518
  softRemoveList?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
519
- /** Configuração do método `restore`. Só existe se `softRemovekName` estiver configurado. */
519
+ /** Configuration for the `restore` method. Only available if `softRemovekName` is configured. */
520
520
  restore?: BaseMethodConfig<TSelectKeys>;
521
- /** Configuração do método `restoreList`. Não aceita select. Só existe se `softRemovekName` estiver configurado. */
521
+ /** Configuration for the `restoreList` method. Does not accept select. Only available if `softRemovekName` is configured. */
522
522
  restoreList?: Omit<BaseMethodConfig<TSelectKeys>, 'defaultSelect'>;
523
523
  };
524
524
  };
@@ -541,11 +541,11 @@ type ResolveCurrentReturn<M extends Prisma.ModelName, Models, S, D> =
541
541
  ? ([D] extends [never] ? FullModelType<M> : SelectedModel<M, D, Models>)
542
542
  : SelectedModel<M, S, Models>;
543
543
 
544
- // ─── helpers reutilizados dentro do tipo mapeado ────────────────────────────
545
- // ─── tipos de payload para relações ─────────────────────────────────────────
544
+ // ─── helpers reused within the mapped type ───────────────────────────────────
545
+ // ─── relation payload types ──────────────────────────────────────────────────
546
546
 
547
547
  /**
548
- * Versão distributiva de `Omit`, preservando unions ao remover propriedades.
548
+ * Distributive version of `Omit`, preserving unions when removing properties.
549
549
  */
550
550
  type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
551
551
  type ExtractUnionProp<T, K extends PropertyKey> = T extends any ? (K extends keyof T ? T[K] : never) : never;
@@ -564,18 +564,18 @@ type RelationPayload<TField, TRelationConfig, M extends Prisma.ModelName, K exte
564
564
  type TransformCreatePayload<U, T, M extends Prisma.ModelName, TRelations> =
565
565
  Omit<U, keyof TRelations> &
566
566
  {
567
- // Campos que são OBRIGATÓRIOS nesta ramificação específica da união do Prisma
567
+ // Fields that are REQUIRED in this specific branch of the Prisma union
568
568
  [K in Extract<keyof TRelations, keyof U> as {} extends Pick<U, K> ? never : K]:
569
569
  K extends keyof T ? RelationPayload<T[K], TRelations[K], M, K> : never;
570
570
  } &
571
571
  {
572
- // Campos que são OPCIONAIS nesta ramificação ou que não pertencem originalmente a ela
572
+ // Fields that are OPTIONAL in this branch or do not originally belong to it
573
573
  [K in keyof TRelations as K extends keyof U ? ({} extends Pick<U, K> ? K : never) : K]?:
574
574
  K extends keyof T ? RelationPayload<T[K], TRelations[K], M, K> : never;
575
575
  };
576
576
 
577
577
  /**
578
- * Payload aceito pelo `save` quando o repository possui relações configuradas.
578
+ * Payload accepted by `save` when the repository has configured relations.
579
579
  */
580
580
  type UpsertWithRelations<T, M extends Prisma.ModelName, TRelations> =
581
581
  ModelUpsertInput<M> extends infer U
@@ -602,7 +602,7 @@ type RelationUpdatePayload<TField, TRelationConfig, M extends Prisma.ModelName,
602
602
  : never;
603
603
 
604
604
  /**
605
- * Payload aceito pelo `patch` quando o repository possui relações configuradas.
605
+ * Payload accepted by `patch` when the repository has configured relations.
606
606
  */
607
607
  type UpdateWithRelations<T, M extends Prisma.ModelName, TRelations> =
608
608
  DistributiveOmit<PrismaModelInputs<M>['updateInput'], keyof TRelations> & {
@@ -610,7 +610,7 @@ type UpdateWithRelations<T, M extends Prisma.ModelName, TRelations> =
610
610
  };
611
611
 
612
612
  /**
613
- * Extrai o tipo de payload do método `save` a partir de uma instância de VSRepository configurada.
613
+ * Extracts the payload type of the `save` method from a configured VSRepository instance.
614
614
  */
615
615
  export type SaveObject<TInput, TRepo> =
616
616
  TRepo extends VSRepository<infer T, infer M, infer Config>
@@ -624,7 +624,7 @@ export type SaveObject<TInput, TRepo> =
624
624
  : never;
625
625
 
626
626
  /**
627
- * Extrai o tipo de payload do método `patch` a partir de uma instância de VSRepository configurada.
627
+ * Extracts the payload type of the `patch` method from a configured VSRepository instance.
628
628
  */
629
629
  export type PatchObject<TInput, TRepo> =
630
630
  TRepo extends VSRepository<infer T, infer M, infer Config>
@@ -645,7 +645,7 @@ type _Def<Config> = ExtractDefaultSelect<Config>;
645
645
  type _Rel<Config> = ExtractRelations<Config>;
646
646
  type _Soft<Config> = ExtractSoftRemovekName<Config>;
647
647
 
648
- // ─── tipo mapeado refatorado — otimizado para o compilador TS ────────────────
648
+ // ─── refactored mapped type — optimized for the TS compiler ──────────────────
649
649
 
650
650
  type AllBaseMethods<
651
651
  T,
@@ -659,55 +659,55 @@ type AllBaseMethods<
659
659
  TSoftKey = _Soft<Config>,
660
660
  I = PrismaModelInputs<M>
661
661
  > = {
662
- /** Busca um registro pela chave primária (PK). */
662
+ /** Fetches a record by its primary key (PK). */
663
663
  get: <S extends keyof TSelects | false = _DS<Config, C, 'get', TSelects>>(
664
664
  pk: _Pk<T, Config>, options?: MethodOptions<S>
665
665
  ) => Promise<_Ret<M, TSelects, S, TDefault> | null>;
666
666
 
667
- /** Busca um registro pela PK e lança `VSRepoRuntimeError` se não encontrado. */
667
+ /** Fetches a record by PK and throws `VSRepoRuntimeError` if not found. */
668
668
  getOrThrow: <S extends keyof TSelects | false = _DS<Config, C, 'getOrThrow', TSelects>>(
669
669
  pk: _Pk<T, Config>, options?: MethodOptions<S>
670
670
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
671
671
 
672
- /** Busca múltiplos registros por uma lista de chaves primárias (PKs). */
672
+ /** Fetches multiple records by a list of primary keys (PKs). */
673
673
  getList: <S extends keyof TSelects | false = _DS<Config, C, 'getList', TSelects>>(
674
674
  pks: _Pk<T, Config>[], options?: MethodOptions<S>
675
675
  ) => Promise<_Ret<M, TSelects, S, TDefault>[]>;
676
676
 
677
- /** Remove um registro identificado pela chave primária (PK). */
677
+ /** Deletes a record identified by its primary key (PK). */
678
678
  remove: <S extends keyof TSelects | false = _DS<Config, C, 'remove', TSelects>>(
679
679
  pk: _Pk<T, Config>, options?: MethodOptions<S>
680
680
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
681
681
 
682
- /** Insere ou atualiza (upsert) um registro. */
682
+ /** Inserts or updates (upsert) a record. */
683
683
  save: <S extends keyof TSelects | false = _DS<Config, C, 'save', TSelects>>(
684
684
  obj: UpsertWithRelations<T, M, TRelations>, options?: MethodOptions<S>
685
685
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
686
686
 
687
- /** Salva um array de objetos em uma única transação automática. */
687
+ /** Saves an array of objects in a single automatic transaction. */
688
688
  saveList: <S extends keyof TSelects | false = _DS<Config, C, 'saveList', TSelects>>(
689
689
  objs: UpsertWithRelations<T, M, TRelations>[], options?: Omit<MethodOptions<S>, 'db'> & { db?: DbTransaction }
690
690
  ) => Promise<_Ret<M, TSelects, S, TDefault>[]>;
691
691
 
692
- /** Atualiza parcialmente (patch) um registro existente pela chave primária (PK). */
692
+ /** Partially updates (patch) an existing record by its primary key (PK). */
693
693
  patch: <S extends keyof TSelects | false = _DS<Config, C, 'patch', TSelects>>(
694
694
  pk: _Pk<T, Config>, obj: UpdateWithRelations<T, M, TRelations>, options?: MethodOptions<S>
695
695
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
696
696
 
697
- /** Atualiza parcialmente múltiplos registros via tuplas `[pk, obj]` em transação automática. */
697
+ /** Partially updates multiple records via `[pk, obj]` tuples in an automatic transaction. */
698
698
  patchList: <S extends keyof TSelects | false = _DS<Config, C, 'patchList', TSelects>>(
699
699
  tuples: [pk: _Pk<T, Config>, obj: UpdateWithRelations<T, M, TRelations>][], options?: Omit<MethodOptions<S>, 'db'> & { db?: DbTransaction }
700
700
  ) => Promise<_Ret<M, TSelects, S, TDefault>[]>;
701
701
 
702
- /** Busca um registro pela PK e faz deep merge com o objeto fornecido **em memória**. */
702
+ /** Fetches a record by PK and deep-merges it with the provided object **in memory**. */
703
703
  merge: <S extends keyof TSelects | false = _DS<Config, C, 'merge', TSelects>>(
704
704
  pk: _Pk<T, Config>, obj: UpdateWithRelations<T, M, TRelations>, options?: MethodOptions<S>
705
705
  ) => Promise<_Ret<M, TSelects, S, TDefault> | null>;
706
706
 
707
- /** Remove múltiplos registros pelas suas chaves primárias. */
707
+ /** Deletes multiple records by their primary keys. */
708
708
  removeList: (pks: _Pk<T, Config>[], options?: { db?: ClientOrTransaction }) => Promise<{ count: number }>;
709
709
 
710
- /** Busca todos os registros (respeita `requiredWhere` quando aplicado). */
710
+ /** Fetches all records (respects `requiredWhere` when set). */
711
711
  getAll: <S extends keyof TSelects | false = _DS<Config, C, 'getAll', TSelects>>(
712
712
  options?: MethodOptions<S> & {
713
713
  pagination?: PaginationOptions<I extends { cursorInput: infer Curs } ? Curs : unknown>;
@@ -715,26 +715,26 @@ type AllBaseMethods<
715
715
  }
716
716
  ) => Promise<_Ret<M, TSelects, S, TDefault>[]>;
717
717
 
718
- /** Retorna a quantidade total de registros. */
718
+ /** Returns the total number of records. */
719
719
  total: (options?: { db?: ClientOrTransaction; see?: SeeMode }) => Promise<number>;
720
720
 
721
- /** Verifica se um registro existe pela chave primária (PK). */
721
+ /** Checks whether a record exists by its primary key (PK). */
722
722
  has: (pk: _Pk<T, Config>, options?: { db?: ClientOrTransaction; see?: SeeMode }) => Promise<boolean>;
723
723
 
724
- /** Marca um registro como removido (soft-delete). */
724
+ /** Marks a record as deleted (soft-delete). */
725
725
  softRemove: <S extends keyof TSelects | false = _DS<Config, C, 'softRemove', TSelects>>(
726
726
  pk: _Pk<T, Config>, options?: Omit<MethodOptions<S>, 'see'>
727
727
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
728
728
 
729
- /** Marca múltiplos registros como removidos (soft-delete) em lote. */
729
+ /** Marks multiple records as deleted (soft-delete) in batch. */
730
730
  softRemoveList: (pks: _Pk<T, Config>[], options?: { db?: ClientOrTransaction }) => Promise<{ count: number }>;
731
731
 
732
- /** Restaura um registro marcado como removido (soft-delete). */
732
+ /** Restores a record previously marked as deleted (soft-delete). */
733
733
  restore: <S extends keyof TSelects | false = _DS<Config, C, 'restore', TSelects>>(
734
734
  pk: _Pk<T, Config>, options?: Omit<MethodOptions<S>, 'see'>
735
735
  ) => Promise<_Ret<M, TSelects, S, TDefault>>;
736
736
 
737
- /** Restaura múltiplos registros marcados como removidos (soft-delete) em lote. */
737
+ /** Restores multiple records previously marked as deleted (soft-delete) in batch. */
738
738
  restoreList: (pks: _Pk<T, Config>[], options?: { db?: ClientOrTransaction }) => Promise<{ count: number }>;
739
739
  };
740
740
 
@@ -772,56 +772,56 @@ type InjectedBaseMethods<
772
772
 
773
773
 
774
774
  /**
775
- * Configuração de relação para One-to-Many ou Many-to-Many.
775
+ * Relation configuration for One-to-Many or Many-to-Many.
776
776
  *
777
- * @template TItem O tipo da entidade relacionada.
777
+ * @template TItem Type of the related entity.
778
778
  */
779
779
  export type ManyRelationConfig<TItem> = {
780
- /** A chave primária (Primary Key) da entidade relacionada. */
780
+ /** Primary key of the related entity. */
781
781
  pk: keyof TItem;
782
- /** Tipo de relação: `otm` (One-to-Many) ou `mtm` (Many-to-Many). */
782
+ /** Relation type: `otm` (One-to-Many) or `mtm` (Many-to-Many). */
783
783
  mode: 'otm' | 'mtm';
784
- /** Comportamento de mutação: `set` (substitui tudo) ou `add` (adiciona aos existentes). */
784
+ /** Mutation behavior: `set` (replaces all) or `add` (appends to existing). */
785
785
  restriction: 'set' | 'add';
786
786
  };
787
787
 
788
788
  /**
789
- * Configuração de relação One-to-One.
789
+ * One-to-One relation configuration.
790
790
  *
791
- * @template TItem O tipo da entidade relacionada.
791
+ * @template TItem Type of the related entity.
792
792
  */
793
793
  export type OneToOneRelationConfig<TItem> = {
794
- /** A chave primária (Primary Key) da entidade relacionada. */
794
+ /** Primary key of the related entity. */
795
795
  pk: keyof TItem;
796
- /** Tipo de relação: `oto` (One-to-One). */
796
+ /** Relation type: `oto` (One-to-One). */
797
797
  mode: 'oto';
798
- /** Comportamento de mutação permitido para salvar. */
798
+ /** Allowed mutation behavior for saving. */
799
799
  restriction: 'set' | 'add';
800
800
  };
801
801
 
802
802
  /**
803
- * Configuração de relação Many-to-One.
803
+ * Many-to-One relation configuration.
804
804
  *
805
- * @template TItem O tipo da entidade relacionada.
805
+ * @template TItem Type of the related entity.
806
806
  */
807
807
  export type ManyToOneRelationConfig<TItem> = {
808
- /** A chave primária (Primary Key) da entidade relacionada. */
808
+ /** Primary key of the related entity. */
809
809
  pk: keyof TItem;
810
- /** Tipo de relação: `mto` (Many-to-One). */
810
+ /** Relation type: `mto` (Many-to-One). */
811
811
  mode: 'mto';
812
- /** Comportamento de mutação permitido para salvar. */
812
+ /** Allowed mutation behavior for saving. */
813
813
  restriction: 'set' | 'add';
814
814
  /**
815
- * Habilita a possibilidade de desvincular a relação, tornando a chave estrangeira nula.
816
- * @deprecated Use `nullable` (com letras minúsculas) em vez de `nullAble`.
815
+ * Enables the ability to unlink the relation, setting the foreign key to null.
816
+ * @deprecated Use `nullable` (lowercase) instead of `nullAble`.
817
817
  */
818
818
  nullAble?: boolean;
819
- /** Habilita a possibilidade de desvincular a relação, tornando a chave estrangeira nula. */
819
+ /** Enables the ability to unlink the relation, setting the foreign key to null. */
820
820
  nullable?: boolean;
821
821
  };
822
822
 
823
823
  /**
824
- * Infere automaticamente a configuração de relação possível a partir de um campo.
824
+ * Automatically infers the possible relation configuration from a field.
825
825
  */
826
826
  export type ExtractRelationConfig<TField> = NonNullable<TField> extends infer NonNull
827
827
  ? NonNull extends Date | Buffer | Uint8Array | Decimal | JsonValue ? never
@@ -831,7 +831,7 @@ export type ExtractRelationConfig<TField> = NonNullable<TField> extends infer No
831
831
  : never;
832
832
 
833
833
  /**
834
- * Mapa das relações configuráveis de um tipo de entidade.
834
+ * Map of configurable relations for an entity type.
835
835
  */
836
836
  export type RepositoryRelations<T> = {
837
837
  [K in keyof T as ExtractRelationConfig<T[K]> extends never ? never : K]?: ExtractRelationConfig<T[K]>;
@@ -840,21 +840,15 @@ export type RepositoryRelations<T> = {
840
840
  type AnySelect<M extends Prisma.ModelName> = Prisma.TypeMap['model'][M]['operations']['findMany']['args']['select'];
841
841
 
842
842
  /**
843
- * Configuração principal usada em `setupVSRepo<T, M>()(config)`.
843
+ * Main configuration used in `setupVSRepo<T, M>()(config)`.
844
844
  *
845
- * @template T Tipo da entidade manipulada pelo repository.
846
- * @template M Nome do modelo Prisma.
847
- * @template SM Mapa de select models nomeados.
845
+ * @template T Type of the entity managed by the repository.
846
+ * @template M Prisma model name.
847
+ * @template SM Map of named select models.
848
848
  */
849
849
  export type RepoConfig<T, M extends Prisma.ModelName, SM extends Record<string, AnySelect<M>> = Record<string, AnySelect<M>>> = {
850
850
  tableName: Uncapitalize<M>;
851
851
  pkName: keyof T;
852
- /**
853
- * Nome do campo `DateTime` usado para soft-delete.
854
- *
855
- * Quando configurado, habilita os métodos `softRemove`, `softRemoveList`, `restore` e `restoreList`.
856
- * O campo **deve** ser do tipo `DateTime` no schema do Prisma — o VSRepository valida isso no `build`.
857
- */
858
852
  softRemovekName?: keyof T & string;
859
853
  selectModels?: SM;
860
854
  defaultSelectModel?: Extract<keyof SM, string>;
@@ -864,43 +858,43 @@ export type RepoConfig<T, M extends Prisma.ModelName, SM extends Record<string,
864
858
  };
865
859
 
866
860
  /**
867
- * Tipo final retornado por `.build(prisma)`.
861
+ * Final type returned by `.build(prisma)`.
868
862
  *
869
- * Combina métodos dinâmicos, métodos base e extensões personalizadas.
863
+ * Combines dynamic methods, base methods, and custom extensions.
870
864
  */
871
865
  type BuiltRepository<T extends object, M extends Prisma.ModelName, Config extends RepoConfig<T, M, any>, C extends BuildConfig<any> | undefined> = {
872
866
  /**
873
- * Estende o repository com métodos personalizados sem perder a tipagem.
867
+ * Extends the repository with custom methods without losing type inference.
874
868
  */
875
869
  extend<E>(extensionFunc: (repo: BuiltRepository<T, M, Config, C>) => E): BuiltRepository<T, M, Config, C> & E;
876
870
 
877
871
  /**
878
- * Instância do Prisma Client passada no `build`.
872
+ * The Prisma Client instance passed to `build`.
879
873
  */
880
874
  readonly prisma: DbClient;
881
875
  } & DynamicMethods<T, M, Config, PrismaModelInputs<M>> & InjectedBaseMethods<T, M, Config, C>;
882
876
 
883
877
  /**
884
- * Fábrica tipada de repositories baseada na configuração do modelo Prisma.
878
+ * Typed repository factory based on the Prisma model configuration.
885
879
  */
886
880
  export declare class VSRepository<T extends object, M extends Prisma.ModelName, const Config extends RepoConfig<T, M, any> = RepoConfig<T, M, any>> {
887
- /** Configuração original informada no `setupVSRepo`. */
881
+ /** Original configuration provided to `setupVSRepo`. */
888
882
  readonly config: Config;
889
883
  /**
890
- * Cria uma instância configurável de `VSRepository`.
884
+ * Creates a configurable instance of `VSRepository`.
891
885
  */
892
886
  constructor(config: Config);
893
887
  /**
894
- * Constrói o repository final com os métodos base e dinâmicos.
888
+ * Builds the final repository with base and dynamic methods.
895
889
  */
896
890
  build<C extends BuildConfig<keyof ExtractSelectModels<Config>>>(prisma: DbClient, config?: C): BuiltRepository<T, M, Config, C>;
897
891
  vsrepocache: never;
898
892
  }
899
893
 
900
894
  /**
901
- * Infere o tipo de um repository já configurado a partir de uma instância de `VSRepository`.
895
+ * Infers the type of an already-configured repository from a `VSRepository` instance.
902
896
  *
903
- * Também permite informar manualmente o `BuildConfig` e o tipo de extensões.
897
+ * Also allows manually providing the `BuildConfig` and extensions type.
904
898
  */
905
899
  export type RepositoryOf<TRepo, C extends BuildConfig<any> | undefined = undefined, E = unknown> =
906
900
  TRepo extends VSRepository<infer T, infer M, infer Config>
@@ -908,16 +902,58 @@ export type RepositoryOf<TRepo, C extends BuildConfig<any> | undefined = undefin
908
902
  : never;
909
903
 
910
904
  /**
911
- * Tipo utilitário usado para validar a configuração de um repository em tempo de compilação.
905
+ * Utility type used to validate a repository configuration at compile time.
912
906
  */
913
907
  export type ValidateRepoConfig<T extends object, M extends Prisma.ModelName, Config> = {
908
+ /**
909
+ * Name of the table mapped by Prisma (usually uncapitalized).
910
+ */
914
911
  tableName: Uncapitalize<M>;
912
+
913
+ /**
914
+ * Name of the field that represents the entity's primary key (Primary Key).
915
+ */
915
916
  pkName: keyof T;
917
+
918
+ /**
919
+ * Name of the `DateTime` field used for soft-delete.
920
+ *
921
+ * When configured, enables the `softRemove`, `softRemoveList`, `restore`, and `restoreList` methods.
922
+ * The field **must** be of type `DateTime` in the Prisma schema — VSRepository validates this during `build`.
923
+ */
916
924
  softRemovekName?: keyof T & string;
925
+
926
+ /**
927
+ * Defines named and reusable data projections (selects).
928
+ * Allows creating different views of the same entity (e.g., `public`, `minimal`, `internal`).
929
+ */
917
930
  selectModels?: SelectModels<M>;
931
+
932
+ /**
933
+ * Defines which select (a key from `selectModels`) will be used automatically
934
+ * when none is specified in the method call.
935
+ * It is highly recommended to define it whenever `selectModels` are used.
936
+ */
918
937
  defaultSelectModel?: string;
938
+
939
+ /**
940
+ * Defines global filters that will be automatically applied to all repository queries.
941
+ * Useful for tenant isolation (multi-tenancy) or base restrictions (e.g., `isActive: true`).
942
+ */
919
943
  requiredWhere?: WhereModel<M>;
944
+
945
+ /**
946
+ * Configures automatic relation management.
947
+ * When configured, allows the `save`, `saveList`, `patch`, and `patchList` methods
948
+ * to automatically handle linking, creation, or cascading deletion of related records.
949
+ */
920
950
  relations?: RepositoryRelations<T>;
951
+
952
+ /**
953
+ * Definition of dynamic repository methods.
954
+ * Behaviors and return types are automatically inferred from the method's name
955
+ * (e.g., `findOneByEmail`, `findManyPaginated`) or proxied via the `proxyTo` property.
956
+ */
921
957
  methods?: {
922
958
  [K in keyof (Config extends { methods: infer Meth } ? Meth : {})]: K extends string
923
959
  ? MethodConfig<M, Config extends { selectModels: infer SM } ? SM : any> & (K extends ValidMethodPatterns ? {} : { proxyTo: ValidMethodPatterns })
@@ -926,8 +962,8 @@ export type ValidateRepoConfig<T extends object, M extends Prisma.ModelName, Con
926
962
  };
927
963
 
928
964
  /**
929
- * Função para inicializar e configurar o `repository`.
930
- * As configurações passadas nele são as que serão lidas ao executar o `.build()`.
965
+ * Function to initialize and configure the `repository`.
966
+ * The configuration passed here is what will be read when `.build()` is called.
931
967
  */
932
968
  export declare function setupVSRepo<T extends object, M extends Prisma.ModelName>(): <
933
969
  const SM extends Record<string, SelectModel<M>>,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vsrepo",
3
- "version": "1.2.7",
3
+ "version": "1.2.8",
4
4
  "description": "Uma biblioteca de repository pattern para Prisma",
5
5
  "homepage": "https://github.com/jaobrabo123/VSRepository#readme",
6
6
  "repository": {