remult 3.5.0-next.1 → 3.5.0-next.2

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 (36) hide show
  1. package/esm/remult-knex/index.js +29 -6
  2. package/esm/server/remult-api-server.js +13 -5
  3. package/esm/src/buildRestDataProvider.js +4 -4
  4. package/esm/src/context.js +1 -1
  5. package/esm/src/data-providers/array-entity-data-provider.js +4 -4
  6. package/esm/src/data-providers/rest-data-provider-using-fetch.js +11 -4
  7. package/esm/src/filter/filter-consumer-bridge-to-sql-request.js +35 -4
  8. package/esm/src/filter/filter-interfaces.js +18 -4
  9. package/esm/src/remult-proxy.js +12 -0
  10. package/esm/src/remult-static.js +1 -0
  11. package/esm/src/remult3/RepositoryImplementation.js +24 -0
  12. package/esm/src/remult3/remult3.js +2 -0
  13. package/esm/src/server-action.js +43 -14
  14. package/index.d.ts +3 -2
  15. package/package.json +1 -1
  16. package/remult-knex/index.js +29 -6
  17. package/server/remult-api-server.d.ts +16 -0
  18. package/server/remult-api-server.js +18 -11
  19. package/src/buildRestDataProvider.d.ts +1 -1
  20. package/src/buildRestDataProvider.js +5 -5
  21. package/src/context.js +1 -1
  22. package/src/data-providers/array-entity-data-provider.js +4 -4
  23. package/src/data-providers/rest-data-provider-using-fetch.d.ts +1 -1
  24. package/src/data-providers/rest-data-provider-using-fetch.js +10 -3
  25. package/src/filter/filter-consumer-bridge-to-sql-request.d.ts +8 -0
  26. package/src/filter/filter-consumer-bridge-to-sql-request.js +58 -19
  27. package/src/filter/filter-interfaces.js +19 -2
  28. package/src/remult-proxy.js +28 -0
  29. package/src/remult-static.d.ts +2 -0
  30. package/src/remult-static.js +1 -0
  31. package/src/remult3/RepositoryImplementation.d.ts +7 -0
  32. package/src/remult3/RepositoryImplementation.js +51 -0
  33. package/src/remult3/remult3.d.ts +62 -4
  34. package/src/remult3/remult3.js +2 -0
  35. package/src/server-action.d.ts +34 -2
  36. package/src/server-action.js +195 -115
@@ -173,6 +173,34 @@ var RemultProxy = /** @class */ (function () {
173
173
  .remultFactory())
174
174
  .repo.apply(_a, tslib_1.__spreadArray([], tslib_1.__read(args), false)).findId(a, b);
175
175
  },
176
+ _a.findIdOrThrow = function (a, b) {
177
+ var _a;
178
+ return (_a = self
179
+ .remultFactory())
180
+ .repo.apply(_a, tslib_1.__spreadArray([], tslib_1.__read(args), false)).findIdOrThrow(a, b);
181
+ },
182
+ _a.findFirstOrThrow = function () {
183
+ var _a, _b;
184
+ var args2 = [];
185
+ for (var _i = 0; _i < arguments.length; _i++) {
186
+ args2[_i] = arguments[_i];
187
+ }
188
+ return (_a = (_b = self
189
+ .remultFactory())
190
+ .repo.apply(_b, tslib_1.__spreadArray([], tslib_1.__read(args), false)))
191
+ .findFirstOrThrow.apply(_a, tslib_1.__spreadArray([], tslib_1.__read(args2), false));
192
+ },
193
+ _a.findOneOrThrow = function () {
194
+ var _a, _b;
195
+ var args2 = [];
196
+ for (var _i = 0; _i < arguments.length; _i++) {
197
+ args2[_i] = arguments[_i];
198
+ }
199
+ return (_a = (_b = self
200
+ .remultFactory())
201
+ .repo.apply(_b, tslib_1.__spreadArray([], tslib_1.__read(args), false)))
202
+ .findOneOrThrow.apply(_a, tslib_1.__spreadArray([], tslib_1.__read(args2), false));
203
+ },
176
204
  //@ts-ignore
177
205
  _a.toJson = function (json) {
178
206
  var _a;
@@ -2,6 +2,7 @@ import type { ClassType } from '../classType.js';
2
2
  import type { ClassHelper, Remult, RemultAsyncLocalStorage } from './context.js';
3
3
  import type { DataProvider } from './data-interfaces.js';
4
4
  import type { columnInfo } from './remult3/columnInfo.js';
5
+ import type { BackendMethodSerializer } from './server-action.js';
5
6
  import type { NullSort } from './sort.js';
6
7
  export declare const remultStatic: {
7
8
  defaultRemultFactory: () => Remult;
@@ -25,6 +26,7 @@ export declare const remultStatic: {
25
26
  nullSort: typeof NullSort;
26
27
  defaultIdFactory: () => string;
27
28
  defaultDataProvider: () => Promise<DataProvider | undefined>;
29
+ backendMethodSerializer: BackendMethodSerializer | undefined;
28
30
  };
29
31
  export declare function defaultFactory(): Remult;
30
32
  export declare function resetFactory(): void;
@@ -30,6 +30,7 @@ var x = {
30
30
  defaultDataProvider: function () {
31
31
  return undefined;
32
32
  },
33
+ backendMethodSerializer: undefined,
33
34
  };
34
35
  if ((typeof process !== 'undefined' &&
35
36
  process.env['IGNORE_GLOBAL_REMULT_IN_TESTS']) ||
@@ -22,6 +22,10 @@ export declare class RepositoryImplementation<entityType> implements Repository<
22
22
  message: string;
23
23
  httpStatusCode: number;
24
24
  };
25
+ _noMatchError(): {
26
+ message: string;
27
+ httpStatusCode: number;
28
+ };
25
29
  [getInternalKey](): this;
26
30
  _createAfterFilter(orderBy: EntityOrderBy<entityType>, lastRow: entityType): Promise<EntityFilter<entityType>>;
27
31
  relations(item: entityType): RepositoryRelations<entityType>;
@@ -90,6 +94,9 @@ export declare class RepositoryImplementation<entityType> implements Repository<
90
94
  create(item?: Partial<MembersOnly<entityType>>): entityType;
91
95
  _fixTypes(item: any): Promise<any>;
92
96
  findId(id: any, options?: FindFirstOptionsBase<entityType>): Promise<entityType | undefined | null>;
97
+ findIdOrThrow(id: any, options?: FindFirstOptionsBase<entityType>): Promise<entityType>;
98
+ findFirstOrThrow(where?: EntityFilter<entityType>, options?: FindFirstOptions<entityType>): Promise<entityType>;
99
+ findOneOrThrow(options?: FindFirstOptions<entityType>): Promise<entityType>;
93
100
  _translateWhereToFilter(where?: EntityFilter<entityType>): Promise<Filter>;
94
101
  }
95
102
  export type EntityOptionsFactory = (remult: Remult) => EntityOptions;
@@ -73,6 +73,12 @@ var RepositoryImplementation = /** @class */ (function () {
73
73
  httpStatusCode: 404,
74
74
  };
75
75
  };
76
+ RepositoryImplementation.prototype._noMatchError = function () {
77
+ return {
78
+ message: "no row matches the filter in entity ".concat(this.metadata.key),
79
+ httpStatusCode: 404,
80
+ };
81
+ };
76
82
  RepositoryImplementation.prototype[repository_internals_js_1.getInternalKey] = function () {
77
83
  return this;
78
84
  };
@@ -1742,6 +1748,51 @@ var RepositoryImplementation = /** @class */ (function () {
1742
1748
  throw new Error('id can be either number or string, but got: ' + typeof id);
1743
1749
  return this.findFirst({}, tslib_1.__assign(tslib_1.__assign({}, options), { where: this.metadata.idMetadata.getIdFilter(id) }), true);
1744
1750
  };
1751
+ RepositoryImplementation.prototype.findIdOrThrow = function (id, options) {
1752
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1753
+ var row;
1754
+ return tslib_1.__generator(this, function (_a) {
1755
+ switch (_a.label) {
1756
+ case 0: return [4 /*yield*/, this.findId(id, options)];
1757
+ case 1:
1758
+ row = _a.sent();
1759
+ if (!row)
1760
+ throw new data_interfaces_js_1.EntityError(this._notFoundError(id));
1761
+ return [2 /*return*/, row];
1762
+ }
1763
+ });
1764
+ });
1765
+ };
1766
+ RepositoryImplementation.prototype.findFirstOrThrow = function (where, options) {
1767
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1768
+ var row;
1769
+ return tslib_1.__generator(this, function (_a) {
1770
+ switch (_a.label) {
1771
+ case 0: return [4 /*yield*/, this.findFirst(where, options)];
1772
+ case 1:
1773
+ row = _a.sent();
1774
+ if (!row)
1775
+ throw new data_interfaces_js_1.EntityError(this._noMatchError());
1776
+ return [2 /*return*/, row];
1777
+ }
1778
+ });
1779
+ });
1780
+ };
1781
+ RepositoryImplementation.prototype.findOneOrThrow = function (options) {
1782
+ return tslib_1.__awaiter(this, void 0, void 0, function () {
1783
+ var row;
1784
+ return tslib_1.__generator(this, function (_a) {
1785
+ switch (_a.label) {
1786
+ case 0: return [4 /*yield*/, this.findOne(options)];
1787
+ case 1:
1788
+ row = _a.sent();
1789
+ if (!row)
1790
+ throw new data_interfaces_js_1.EntityError(this._noMatchError());
1791
+ return [2 /*return*/, row];
1792
+ }
1793
+ });
1794
+ });
1795
+ };
1745
1796
  RepositoryImplementation.prototype._translateWhereToFilter = function (where) {
1746
1797
  return tslib_1.__awaiter(this, void 0, void 0, function () {
1747
1798
  var safeWhere, z, z, _a, r;
@@ -258,15 +258,40 @@ export interface EntityMetadata<entityType = unknown> {
258
258
  */
259
259
  readonly idMetadata: IdMetadata<entityType>;
260
260
  }
261
+ declare const notAFieldMarker: unique symbol;
262
+ /**
263
+ * Marks one property as not a field, e.g. a getter computed from other fields. It's left out of
264
+ * `where`, `orderBy`, `insert`, `fields` and the other field types. Types only.
265
+ *
266
+ * The marker goes on the property, not on the value's class, so the same class can still be
267
+ * stored as a real field elsewhere. A plain `T` still assigns to it, so no casts are needed.
268
+ *
269
+ * @example
270
+ * \@Entity('orders')
271
+ * class Order {
272
+ * \@Fields.integer() priceCents = 0
273
+ * \@Fields.string() priceCurrency = 'USD'
274
+ * get price(): NotAField<Money> {
275
+ * return new Money(this.priceCents, this.priceCurrency)
276
+ * }
277
+ * }
278
+ *
279
+ * // Type error. Without NotAField this typechecks and throws "field not found".
280
+ * repo(Order).find({ where: { price: new Money(100, 'USD') } })
281
+ */
282
+ export type NotAField<T> = T & {
283
+ readonly [notAFieldMarker]?: true;
284
+ };
285
+ type IsNotAField<V> = 0 extends 1 & V ? false : [NonNullable<V>] extends [never] ? false : typeof notAFieldMarker extends keyof NonNullable<V> ? {} extends Pick<NonNullable<V>, typeof notAFieldMarker> ? true : false : false;
261
286
  export declare type MembersOnly<T> = {
262
- [K in keyof Omit<T, keyof EntityBase> as T[K] extends Function ? never : K extends string ? K : never]: T[K];
287
+ [K in keyof Omit<T, keyof EntityBase> as T[K] extends Function ? never : IsNotAField<T[K]> extends true ? never : K extends string ? K : never]: T[K];
263
288
  };
264
289
  export declare type idType<entityType> = entityType extends {
265
290
  id?: infer U;
266
291
  } ? U extends string ? string : U extends number ? number : string | number : string | number;
267
292
  export type NumericKeys<T> = {
268
- [K in keyof T]: T[K] extends number | undefined | null ? K : never;
269
- }[keyof T];
293
+ [K in keyof MembersOnly<T>]: T[K] extends number | undefined | null ? K : never;
294
+ }[keyof MembersOnly<T>];
270
295
  /**
271
296
  * Options for performing aggregation on an entity in the repository.
272
297
  *
@@ -420,6 +445,21 @@ export interface Repository<entityType> {
420
445
  findOne(options?: FindFirstOptions<entityType>): Promise<entityType | undefined>;
421
446
  /** returns the items that matches the id. If id is undefined | null, returns null */
422
447
  findId(id: idType<entityType>, options?: FindFirstOptionsBase<entityType>): Promise<entityType | undefined | null>;
448
+ /** returns the item that matches the id, and throws an `EntityError` with `httpStatusCode` 404 if no item matches
449
+ * @example
450
+ * const task = await taskRepo.findIdOrThrow(id)
451
+ */
452
+ findIdOrThrow(id: idType<entityType>, options?: FindFirstOptionsBase<entityType>): Promise<entityType>;
453
+ /** returns the first item that matches the `where` condition, and throws an `EntityError` with `httpStatusCode` 404 if no item matches
454
+ * @example
455
+ * await taskRepo.findFirstOrThrow({ completed: false })
456
+ */
457
+ findFirstOrThrow(where?: EntityFilter<entityType>, options?: FindFirstOptions<entityType>): Promise<entityType>;
458
+ /** returns the first item that matches the `where` condition, and throws an `EntityError` with `httpStatusCode` 404 if no item matches
459
+ * @example
460
+ * await taskRepo.findOneOrThrow({ where: { completed: false } })
461
+ */
462
+ findOneOrThrow(options?: FindFirstOptions<entityType>): Promise<entityType>;
423
463
  /**
424
464
  * Performs an aggregation on the repository's entity type based on the specified options.
425
465
  *
@@ -766,11 +806,26 @@ export interface FindOptions<entityType> extends FindOptionsBase<entityType> {
766
806
  export declare type EntityOrderBy<entityType> = {
767
807
  [Properties in keyof Partial<MembersOnly<entityType>>]?: 'asc' | 'desc';
768
808
  };
809
+ /**
810
+ * Fields of a type added to this interface accept `$gt`, `$gte`, `$lt` and
811
+ * `$lte` in an {@link EntityFilter}. The in-memory and JSON providers compare
812
+ * `valueConverter.toJson` output with `<`/`>`, so it has to sort like the
813
+ * values, e.g. `Temporal.Instant.toString()` drops trailing zeros and sorts
814
+ * `00:00:00Z` after `00:00:00.5Z`.
815
+ * @example
816
+ * declare module 'remult' {
817
+ * interface ComparableTypes {
818
+ * instant: Temporal.Instant
819
+ * }
820
+ * }
821
+ */
822
+ export interface ComparableTypes {
823
+ }
769
824
  /**Used to filter the desired result set
770
825
  * @see [EntityFilter](http://remult.dev/docs/entityFilter.html)
771
826
  */
772
827
  export declare type EntityFilter<entityType> = {
773
- [Properties in keyof Partial<MembersOnly<entityType>>]?: (Partial<entityType>[Properties] extends number | Date | undefined | null ? ComparisonValueFilter<Partial<entityType>[Properties]> : Partial<entityType>[Properties] extends string | undefined ? Partial<entityType>[Properties] | (ContainsStringValueFilter & ComparisonValueFilter<Partial<entityType>[Properties]>) : Partial<entityType>[Properties] extends boolean | undefined | null ? ValueFilter<boolean> : Partial<entityType>[Properties] extends {
828
+ [Properties in keyof Partial<MembersOnly<entityType>>]?: (Partial<entityType>[Properties] extends number | Date | ComparableTypes[keyof ComparableTypes] | undefined | null ? ComparisonValueFilter<Partial<entityType>[Properties]> : Partial<entityType>[Properties] extends string | undefined ? Partial<entityType>[Properties] | (ContainsStringValueFilter & ComparisonValueFilter<Partial<entityType>[Properties]>) : Partial<entityType>[Properties] extends boolean | undefined | null ? ValueFilter<boolean> : Partial<entityType>[Properties] extends {
774
829
  id?: string | number;
775
830
  } | undefined ? IdFilter<Partial<entityType>[Properties]> : ValueFilter<Partial<entityType>[Properties]>) | ContainsStringValueFilter;
776
831
  } & {
@@ -1233,4 +1288,7 @@ export declare const flags: {
1233
1288
  liveQueryKeepAliveMs: number;
1234
1289
  /** Version poll while SSE is stale */
1235
1290
  liveQueryPollWhenStaleMs: number;
1291
+ /** Client calls reject with an `EntityError` instead of a plain object. On by default in the next major. */
1292
+ clientErrorsAsEntityError: boolean;
1236
1293
  };
1294
+ export {};
@@ -25,6 +25,8 @@ exports.flags = {
25
25
  liveQueryKeepAliveMs: 30000,
26
26
  /** Version poll while SSE is stale */
27
27
  liveQueryPollWhenStaleMs: 1000,
28
+ /** Client calls reject with an `EntityError` instead of a plain object. On by default in the next major. */
29
+ clientErrorsAsEntityError: false,
28
30
  };
29
31
  /*p1 - issues in https://stackblitz.com/edit/demo-allow-delete-based-on-other-entity:
30
32
  - don't like the ensure schema
@@ -15,7 +15,7 @@ export declare abstract class Action<inParam, outParam> implements ActionInterfa
15
15
  constructor(actionUrl: string, queue: boolean, allowed: AllowedForInstance<any>);
16
16
  static apiUrlForJobStatus: string;
17
17
  run(pIn: inParam, baseUrl?: string, http?: RestDataProviderHttpProvider): Promise<outParam>;
18
- doWork: (args: any[], self: any, baseUrl?: string, http?: RestDataProviderHttpProvider) => Promise<any>;
18
+ doWork: (args: any[], self: any, caller?: Remult) => Promise<any>;
19
19
  protected abstract execute(info: inParam, req: Remult, res: DataApiResponse): Promise<outParam>;
20
20
  __register(reg: (url: string, queue: boolean, allowed: AllowedForInstance<any>, what: (data: any, req: Remult, res: DataApiResponse) => void) => void): void;
21
21
  }
@@ -51,6 +51,28 @@ export interface BackendMethodOptions<type> {
51
51
  blockUser?: boolean;
52
52
  paramTypes?: any[] | (() => any[]);
53
53
  }
54
+ /**
55
+ * Sends a backend method's argument list through `args` and its return value through `result`.
56
+ * An `EntityError` thrown from either on the backend reaches the caller.
57
+ */
58
+ export interface BackendMethodSerializer {
59
+ args: BackendMethodValueSerializer;
60
+ result: BackendMethodValueSerializer;
61
+ }
62
+ /**
63
+ * Turns a value into JSON and back. superjson and oRPC's `StandardRPCSerializer` both fit.
64
+ * Either method may return a promise.
65
+ */
66
+ export interface BackendMethodValueSerializer {
67
+ serialize(value: unknown, context: BackendMethodSerializerContext): unknown | Promise<unknown>;
68
+ deserialize(value: unknown, context: BackendMethodSerializerContext): unknown | Promise<unknown>;
69
+ }
70
+ export interface BackendMethodSerializerContext {
71
+ /** The `Remult` making the call, so a serializer can rebuild entities with `remult.repo(...)`. */
72
+ remult: Remult;
73
+ /** The options passed to `@BackendMethod`, so a serializer can read settings added to them. */
74
+ options: BackendMethodOptions<unknown>;
75
+ }
54
76
  export declare function Controller(key: string): (target: any, context?: any) => any;
55
77
  export interface ClassMethodDecoratorContextStub<This = unknown, Value extends (this: This, ...args: any) => any = (this: This, ...args: any) => any> {
56
78
  readonly kind: 'method';
@@ -78,6 +100,16 @@ export interface ClassMethodDecoratorContextStub<This = unknown, Value extends (
78
100
  * ```
79
101
  */
80
102
  export declare function BackendMethod<type = unknown>(options: BackendMethodOptions<type>): (target: any, context: ClassMethodDecoratorContextStub<type> | string, descriptor?: any) => any;
103
+ export declare namespace BackendMethod {
104
+ /**
105
+ * Sends every backend method's arguments and return value through this serializer. Set it in a
106
+ * file that both the frontend and the backend import, or calls break.
107
+ * @example
108
+ * import superjson from 'superjson'
109
+ * BackendMethod.serializer = { args: superjson, result: superjson }
110
+ */
111
+ let serializer: BackendMethodSerializer | undefined;
112
+ }
81
113
  export interface jobWasQueuedResult {
82
114
  queuedJobId?: string;
83
115
  }
@@ -96,7 +128,7 @@ export declare function prepareArgsToSend(types: any[], args: any[]): any[];
96
128
  export declare function prepareReceivedArgs(types: any[], args: any[], remult: Remult, ds: DataProvider, res: DataApiResponse): Promise<any[]>;
97
129
  export declare const classBackendMethodsArray: unique symbol;
98
130
  export interface ActionInterface {
99
- doWork: (args: any[], self: any, baseUrl?: string, http?: RestDataProviderHttpProvider) => Promise<any>;
131
+ doWork: (args: any[], self: any, caller?: Remult) => Promise<any>;
100
132
  __register(reg: (url: string, queue: boolean, allowed: AllowedForInstance<any>, what: (data: any, req: Remult, res: DataApiResponse) => void) => void): void;
101
133
  }
102
134
  export {};