@mikro-orm/core 7.0.0-dev.220 → 7.0.0-dev.222

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.
@@ -354,7 +354,8 @@ export class ObjectHydrator extends Hydrator {
354
354
  const code = `// compiled hydrator for entity ${meta.className} (${type + normalizeAccessors ? ' normalized' : ''})\n`
355
355
  + `return function(entity, data, factory, newEntity, convertCustomTypes, schema, parentSchema, normalizeAccessors) {\n`
356
356
  + `${lines.join('\n')}\n}`;
357
- const hydrator = Utils.createFunction(context, code);
357
+ const fnKey = `hydrator-${meta.uniqueName}-${type}-${normalizeAccessors}`;
358
+ const hydrator = Utils.createFunction(context, code, this.config.get('compiledFunctions'), fnKey);
358
359
  this.hydrators[key].set(meta.class, hydrator);
359
360
  return hydrator;
360
361
  }
package/index.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * @module core
4
4
  */
5
5
  export { EntityMetadata, PrimaryKeyProp, EntityRepositoryType, OptionalProps, EagerProps, HiddenProps, Config } from './typings.js';
6
- export type { Constructor, ConnectionType, Dictionary, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, EntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, MigrationDiff, GenerateOptions, FilterObject, IEntityGenerator, ISeedManager, RequiredEntityData, CheckCallback, IndexCallback, FormulaCallback, FormulaTable, SimpleColumnMeta, Rel, Ref, ScalarRef, EntityRef, ISchemaGenerator, UmzugMigration, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, EntityType, FromEntityType, Selected, IsSubset, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, FilterValue, MergeLoaded, MergeSelected, TypeConfig, AnyString, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, RequiredNullable, DefineConfig, Opt, Hidden, EntitySchemaWithMeta, InferEntity, CheckConstraint, GeneratedColumnCallback, FilterDef, EntityCtor, Subquery, } from './typings.js';
6
+ export type { CompiledFunctions, Constructor, ConnectionType, Dictionary, Primary, IPrimaryKey, ObjectQuery, FilterQuery, IWrappedEntity, EntityName, EntityData, Highlighter, MaybePromise, AnyEntity, EntityClass, EntityProperty, PopulateOptions, Populate, Loaded, New, LoadedReference, LoadedCollection, IMigrator, IMigrationGenerator, MigratorEvent, GetRepository, MigrationObject, DeepPartial, PrimaryProperty, Cast, IsUnknown, EntityDictionary, EntityDTO, MigrationDiff, GenerateOptions, FilterObject, IEntityGenerator, ISeedManager, RequiredEntityData, CheckCallback, IndexCallback, FormulaCallback, FormulaTable, SimpleColumnMeta, Rel, Ref, ScalarRef, EntityRef, ISchemaGenerator, UmzugMigration, MigrateOptions, MigrationResult, MigrationRow, EntityKey, EntityValue, EntityDataValue, FilterKey, EntityType, FromEntityType, Selected, IsSubset, EntityProps, ExpandProperty, ExpandScalar, FilterItemValue, ExpandQuery, Scalar, ExpandHint, FilterValue, MergeLoaded, MergeSelected, TypeConfig, AnyString, ClearDatabaseOptions, CreateSchemaOptions, EnsureDatabaseOptions, UpdateSchemaOptions, DropSchemaOptions, RefreshDatabaseOptions, AutoPath, UnboxArray, MetadataProcessor, ImportsResolver, RequiredNullable, DefineConfig, Opt, Hidden, EntitySchemaWithMeta, InferEntity, CheckConstraint, GeneratedColumnCallback, FilterDef, EntityCtor, Subquery, } from './typings.js';
7
7
  export * from './enums.js';
8
8
  export * from './errors.js';
9
9
  export * from './exceptions.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@mikro-orm/core",
3
3
  "type": "module",
4
- "version": "7.0.0-dev.220",
4
+ "version": "7.0.0-dev.222",
5
5
  "description": "TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.",
6
6
  "exports": {
7
7
  "./package.json": "./package.json",
package/typings.d.ts CHANGED
@@ -22,6 +22,7 @@ export type Constructor<T = unknown> = new (...args: any[]) => T;
22
22
  export type Dictionary<T = any> = {
23
23
  [k: string]: T;
24
24
  };
25
+ export type CompiledFunctions = Record<string, (...args: any[]) => any>;
25
26
  export type EntityKey<T = unknown, B extends boolean = false> = string & {
26
27
  [K in keyof T]-?: CleanKeys<T, K, B> extends never ? never : K;
27
28
  }[keyof T];
@@ -1,7 +1,7 @@
1
1
  import type { NamingStrategy } from '../naming-strategy/NamingStrategy.js';
2
2
  import { type CacheAdapter, type SyncCacheAdapter } from '../cache/CacheAdapter.js';
3
3
  import type { EntityRepository } from '../entity/EntityRepository.js';
4
- import type { AnyEntity, Constructor, Dictionary, EnsureDatabaseOptions, EntityClass, EntityMetadata, FilterDef, GenerateOptions, Highlighter, HydratorConstructor, IHydrator, IMigrationGenerator, IPrimaryKey, MaybePromise, Migration, MigrationObject } from '../typings.js';
4
+ import type { AnyEntity, CompiledFunctions, Constructor, Dictionary, EnsureDatabaseOptions, EntityClass, EntityMetadata, FilterDef, GenerateOptions, Highlighter, HydratorConstructor, IHydrator, IMigrationGenerator, IPrimaryKey, MaybePromise, Migration, MigrationObject } from '../typings.js';
5
5
  import { ObjectHydrator } from '../hydration/ObjectHydrator.js';
6
6
  import { NullHighlighter } from '../utils/NullHighlighter.js';
7
7
  import { type Logger, type LoggerNamespace, type LoggerOptions } from '../logging/Logger.js';
@@ -682,6 +682,12 @@ export interface Options<Driver extends IDatabaseDriver = IDatabaseDriver, EM ex
682
682
  * @default ObjectHydrator
683
683
  */
684
684
  hydrator?: HydratorConstructor;
685
+ /**
686
+ * Pre-generated compiled functions for hydration and comparison.
687
+ * Use the `compile` CLI command to create these functions.
688
+ * Enables deployment to runtimes that prohibit `new Function`/eval (e.g. Cloudflare Workers).
689
+ */
690
+ compiledFunctions?: CompiledFunctions;
685
691
  /**
686
692
  * Default loading strategy for relations.
687
693
  * - `'joined'`: Use SQL JOINs (single query, may cause cartesian product)
@@ -152,6 +152,10 @@ export class Configuration {
152
152
  highlighter: this.options.highlighter,
153
153
  writer: this.options.logger,
154
154
  });
155
+ const cf = this.options.compiledFunctions;
156
+ if (cf && cf.__version !== Utils.getORMVersion()) {
157
+ this.logger.warn('discovery', `Compiled functions were generated with MikroORM v${cf.__version ?? 'unknown'}, but the current version is v${Utils.getORMVersion()}. Please regenerate with \`npx mikro-orm compile\`.`);
158
+ }
155
159
  if (this.options.driver) {
156
160
  this.driver = new this.options.driver(this);
157
161
  this.platform = this.driver.getPlatform();
@@ -242,7 +246,7 @@ export class Configuration {
242
246
  * Gets instance of Comparator. (cached)
243
247
  */
244
248
  getComparator(metadata) {
245
- return this.getCachedService(EntityComparator, metadata, this.platform);
249
+ return this.getCachedService(EntityComparator, metadata, this.platform, this);
246
250
  }
247
251
  /**
248
252
  * Gets instance of MetadataProvider. (cached)
@@ -1,5 +1,6 @@
1
1
  import type { EntityData, EntityDictionary, EntityMetadata, EntityName, EntityProperty, IMetadataStorage } from '../typings.js';
2
2
  import type { Platform } from '../platforms/Platform.js';
3
+ import type { Configuration } from './Configuration.js';
3
4
  type Comparator<T> = (a: T, b: T, options?: {
4
5
  includeInverseSides?: boolean;
5
6
  }) => EntityData<T>;
@@ -9,6 +10,7 @@ type CompositeKeyPart = string | CompositeKeyPart[];
9
10
  export declare class EntityComparator {
10
11
  private readonly metadata;
11
12
  private readonly platform;
13
+ private readonly config?;
12
14
  private readonly comparators;
13
15
  private readonly mappers;
14
16
  private readonly snapshotGenerators;
@@ -16,7 +18,7 @@ export declare class EntityComparator {
16
18
  private readonly pkGettersConverted;
17
19
  private readonly pkSerializers;
18
20
  private tmpIndex;
19
- constructor(metadata: IMetadataStorage, platform: Platform);
21
+ constructor(metadata: IMetadataStorage, platform: Platform, config?: Configuration | undefined);
20
22
  /**
21
23
  * Computes difference between two entities.
22
24
  */
@@ -7,6 +7,7 @@ import { EntityIdentifier } from '../entity/EntityIdentifier.js';
7
7
  export class EntityComparator {
8
8
  metadata;
9
9
  platform;
10
+ config;
10
11
  comparators = new Map();
11
12
  mappers = new Map();
12
13
  snapshotGenerators = new Map();
@@ -14,9 +15,10 @@ export class EntityComparator {
14
15
  pkGettersConverted = new Map();
15
16
  pkSerializers = new Map();
16
17
  tmpIndex = 0;
17
- constructor(metadata, platform) {
18
+ constructor(metadata, platform, config) {
18
19
  this.metadata = metadata;
19
20
  this.platform = platform;
21
+ this.config = config;
20
22
  }
21
23
  /**
22
24
  * Computes difference between two entities.
@@ -88,9 +90,10 @@ export class EntityComparator {
88
90
  }
89
91
  lines.push(` return entity${this.wrap(pk)};`);
90
92
  }
91
- const code = `// compiled pk serializer for entity ${meta.className}\n`
93
+ const code = `// compiled pk getter for entity ${meta.className}\n`
92
94
  + `return function(entity) {\n${lines.join('\n')}\n}`;
93
- const pkSerializer = Utils.createFunction(context, code);
95
+ const fnKey = `pkGetter-${meta.uniqueName}`;
96
+ const pkSerializer = Utils.createFunction(context, code, this.config?.get('compiledFunctions'), fnKey);
94
97
  this.pkGetters.set(meta, pkSerializer);
95
98
  return pkSerializer;
96
99
  }
@@ -140,7 +143,8 @@ export class EntityComparator {
140
143
  }
141
144
  const code = `// compiled pk getter (with converted custom types) for entity ${meta.className}\n`
142
145
  + `return function(entity) {\n${lines.join('\n')}\n}`;
143
- const pkSerializer = Utils.createFunction(context, code);
146
+ const fnKey = `pkGetterConverted-${meta.uniqueName}`;
147
+ const pkSerializer = Utils.createFunction(context, code, this.config?.get('compiledFunctions'), fnKey);
144
148
  this.pkGettersConverted.set(meta, pkSerializer);
145
149
  return pkSerializer;
146
150
  }
@@ -192,7 +196,8 @@ export class EntityComparator {
192
196
  }
193
197
  const code = `// compiled pk serializer for entity ${meta.className}\n`
194
198
  + `return function(entity) {\n${lines.join('\n')}\n}`;
195
- const pkSerializer = Utils.createFunction(context, code);
199
+ const fnKey = `pkSerializer-${meta.uniqueName}`;
200
+ const pkSerializer = Utils.createFunction(context, code, this.config?.get('compiledFunctions'), fnKey);
196
201
  this.pkSerializers.set(meta, pkSerializer);
197
202
  return pkSerializer;
198
203
  }
@@ -221,7 +226,8 @@ export class EntityComparator {
221
226
  })
222
227
  .forEach(prop => lines.push(this.getPropertySnapshot(meta, prop, context, this.wrap(prop.name), this.wrap(prop.name), [prop.name])));
223
228
  const code = `return function(entity) {\n const ret = {};\n${lines.join('\n')}\n return ret;\n}`;
224
- const snapshotGenerator = Utils.createFunction(context, code);
229
+ const fnKey = `snapshotGenerator-${meta.uniqueName}`;
230
+ const snapshotGenerator = Utils.createFunction(context, code, this.config?.get('compiledFunctions'), fnKey);
225
231
  this.snapshotGenerators.set(meta, snapshotGenerator);
226
232
  return snapshotGenerator;
227
233
  }
@@ -369,7 +375,8 @@ export class EntityComparator {
369
375
  lines.push(` for (let k in result) { if (Object.hasOwn(result, k) && !mapped[k] && ret[k] === undefined) ret[k] = result[k]; }`);
370
376
  const code = `// compiled mapper for entity ${meta.className}\n`
371
377
  + `return function(result) {\n const ret = {};\n${lines.join('\n')}\n return ret;\n}`;
372
- const resultMapper = Utils.createFunction(context, code);
378
+ const fnKey = `resultMapper-${meta.uniqueName}`;
379
+ const resultMapper = Utils.createFunction(context, code, this.config?.get('compiledFunctions'), fnKey);
373
380
  this.mappers.set(meta, resultMapper);
374
381
  return resultMapper;
375
382
  }
@@ -588,7 +595,8 @@ export class EntityComparator {
588
595
  lines.push(`}`);
589
596
  const code = `// compiled comparator for entity ${meta.className}\n`
590
597
  + `return function(last, current, options) {\n const diff = {};\n${lines.join('\n')}\n return diff;\n}`;
591
- const comparator = Utils.createFunction(context, code);
598
+ const fnKey = `comparator-${meta.uniqueName}`;
599
+ const comparator = Utils.createFunction(context, code, this.config?.get('compiledFunctions'), fnKey);
592
600
  this.comparators.set(meta, comparator);
593
601
  return comparator;
594
602
  }
package/utils/Utils.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Dictionary, EntityData, EntityDictionary, EntityKey, EntityMetadata, EntityName, EntityProperty, Primary } from '../typings.js';
1
+ import type { CompiledFunctions, Dictionary, EntityData, EntityDictionary, EntityKey, EntityMetadata, EntityName, EntityProperty, Primary } from '../typings.js';
2
2
  import type { Collection } from '../entity/Collection.js';
3
3
  import type { Platform } from '../platforms/Platform.js';
4
4
  import type { ScalarReference } from '../entity/Reference.js';
@@ -143,7 +143,7 @@ export declare class Utils {
143
143
  static isOperator(key: PropertyKey, includeGroupOperators?: boolean): boolean;
144
144
  static hasNestedKey(object: unknown, key: string): boolean;
145
145
  static getORMVersion(): string;
146
- static createFunction(context: Map<string, any>, code: string): any;
146
+ static createFunction(context: Map<string, any>, code: string, compiledFunctions?: CompiledFunctions, key?: string): any;
147
147
  static callCompiledFunction<T extends unknown[], R>(fn: (...args: T) => R, ...args: T): R;
148
148
  static unwrapProperty<T>(entity: T, meta: EntityMetadata<T>, prop: EntityProperty<T>, payload?: boolean): [unknown, number[]][];
149
149
  static setPayloadProperty<T>(entity: EntityDictionary<T>, meta: EntityMetadata<T>, prop: EntityProperty<T>, value: unknown, idx: number[]): void;
package/utils/Utils.js CHANGED
@@ -123,7 +123,7 @@ export function parseJsonSafe(value) {
123
123
  }
124
124
  export class Utils {
125
125
  static PK_SEPARATOR = '~~~';
126
- static #ORM_VERSION = '7.0.0-dev.220';
126
+ static #ORM_VERSION = '7.0.0-dev.222';
127
127
  /**
128
128
  * Checks if the argument is instance of `Object`. Returns false for arrays.
129
129
  */
@@ -666,7 +666,10 @@ export class Utils {
666
666
  static getORMVersion() {
667
667
  return this.#ORM_VERSION;
668
668
  }
669
- static createFunction(context, code) {
669
+ static createFunction(context, code, compiledFunctions, key) {
670
+ if (key && compiledFunctions?.[key]) {
671
+ return compiledFunctions[key](...context.values());
672
+ }
670
673
  try {
671
674
  return new Function(...context.keys(), `'use strict';\n` + code)(...context.values());
672
675
  /* v8 ignore next */