@nocobase/database 2.0.0-alpha.5 → 2.0.0-alpha.50

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/lib/belongs-to-array/belongs-to-array-repository.d.ts +0 -2
  2. package/lib/belongs-to-array/belongs-to-array-repository.js +0 -13
  3. package/lib/collection.d.ts +1 -3
  4. package/lib/collection.js +30 -30
  5. package/lib/database.d.ts +1 -0
  6. package/lib/database.js +15 -9
  7. package/lib/dialects/mariadb-dialect.js +6 -1
  8. package/lib/dialects/postgres-dialect.js +0 -3
  9. package/lib/eager-loading/eager-loading-tree.js +2 -1
  10. package/lib/fields/index.d.ts +1 -3
  11. package/lib/fields/index.js +0 -2
  12. package/lib/index.d.ts +3 -1
  13. package/lib/index.js +8 -0
  14. package/lib/interfaces/time-interface.js +1 -1
  15. package/lib/{fields/encryption-field/index.d.ts → operators/in.d.ts} +2 -3
  16. package/lib/{fields/encryption-field/errors/EncryptionError.js → operators/in.js} +11 -15
  17. package/lib/operators/index.js +2 -0
  18. package/lib/relation-repository/belongs-to-many-repository.js +1 -2
  19. package/lib/relation-repository/relation-repository.js +1 -1
  20. package/lib/relation-repository/single-relation-repository.js +1 -2
  21. package/lib/repository.js +2 -2
  22. package/lib/sync-runner.js +3 -0
  23. package/lib/update-associations.d.ts +2 -4
  24. package/lib/update-associations.js +6 -14
  25. package/lib/utils/field-validation.d.ts +0 -45
  26. package/lib/utils/field-validation.js +2 -60
  27. package/lib/utils.d.ts +1 -0
  28. package/lib/utils.js +10 -0
  29. package/lib/view/field-type-map.js +2 -2
  30. package/package.json +4 -4
  31. package/lib/fields/encryption-field/encryption-field.d.ts +0 -20
  32. package/lib/fields/encryption-field/encryption-field.js +0 -110
  33. package/lib/fields/encryption-field/errors/EncryptionError.d.ts +0 -11
  34. package/lib/fields/encryption-field/index.js +0 -34
  35. package/lib/fields/encryption-field/utils.d.ts +0 -6
  36. package/lib/fields/encryption-field/utils.js +0 -152
@@ -12,7 +12,6 @@ import { FindOptions } from '../repository';
12
12
  import { MultipleRelationRepository } from '../relation-repository/multiple-relation-repository';
13
13
  import Database from '../database';
14
14
  import { Model } from '../model';
15
- import { UpdateAssociationOptions } from '../update-associations';
16
15
  export declare class BelongsToArrayAssociation {
17
16
  db: Database;
18
17
  associationType: string;
@@ -35,7 +34,6 @@ export declare class BelongsToArrayAssociation {
35
34
  generateInclude(parentAs?: string): {
36
35
  on: void;
37
36
  };
38
- update(instance: Model, value: any, options?: UpdateAssociationOptions): Promise<void>;
39
37
  }
40
38
  export declare class BelongsToArrayRepository extends MultipleRelationRepository {
41
39
  private belongsToArrayAssociation;
@@ -94,19 +94,6 @@ const _BelongsToArrayAssociation = class _BelongsToArrayAssociation {
94
94
  on: this.db.queryInterface.generateJoinOnForJSONArray(left, right)
95
95
  };
96
96
  }
97
- async update(instance, value, options = {}) {
98
- await instance.update(
99
- {
100
- [this.as]: value
101
- },
102
- {
103
- values: {
104
- [this.as]: value
105
- },
106
- transaction: options == null ? void 0 : options.transaction
107
- }
108
- );
109
- }
110
97
  };
111
98
  __name(_BelongsToArrayAssociation, "BelongsToArrayAssociation");
112
99
  let BelongsToArrayAssociation = _BelongsToArrayAssociation;
@@ -93,9 +93,6 @@ export declare class Collection<TModelAttributes extends {} = any, TCreationAttr
93
93
  validate(options: {
94
94
  values: Record<string, any> | Record<string, any>[];
95
95
  operation: 'create' | 'update';
96
- context: {
97
- t: Function;
98
- };
99
96
  }): void;
100
97
  isMultiFilterTargetKey(): boolean;
101
98
  tableName(): any;
@@ -129,6 +126,7 @@ export declare class Collection<TModelAttributes extends {} = any, TCreationAttr
129
126
  updateOptions(options: CollectionOptions, mergeOptions?: any): this;
130
127
  setSortable(sortable: any): void;
131
128
  updateField(name: string, options: FieldOptions): void;
129
+ private normalizeFieldName;
132
130
  addIndex(index: string | string[] | {
133
131
  fields: string[];
134
132
  unique?: boolean;
package/lib/collection.js CHANGED
@@ -58,6 +58,7 @@ var import_model = require("./model");
58
58
  var import_repository = require("./repository");
59
59
  var import_utils = require("./utils");
60
60
  var import_field_validation = require("./utils/field-validation");
61
+ var import_joi = __toESM(require("joi"));
61
62
  function EnsureAtomicity(target, propertyKey, descriptor) {
62
63
  const originalMethod = descriptor.value;
63
64
  descriptor.value = function(...args) {
@@ -161,50 +162,33 @@ const _Collection = class _Collection extends import_events.EventEmitter {
161
162
  }
162
163
  }
163
164
  validate(options) {
164
- const { values: updateValues, context, operation } = options;
165
+ const { values: updateValues, operation } = options;
165
166
  if (!updateValues) {
166
167
  return;
167
168
  }
168
169
  const values = Array.isArray(updateValues) ? updateValues : [updateValues];
169
- const { t } = context || { t: /* @__PURE__ */ __name((key, options2) => key, "t") };
170
- const unwrapTplLabel = /* @__PURE__ */ __name((label) => {
171
- if (typeof label !== "string") return label;
172
- const m = label.match(/^[\s\t]*\{\{\s*t\(\s*(['"])(.*?)\1(?:\s*,[\s\S]*)?\)\s*\}\}[\s\t]*$/);
173
- return m ? m[2] : label;
174
- }, "unwrapTplLabel");
175
170
  const helper = /* @__PURE__ */ __name((field, value) => {
176
- var _a, _b, _c;
171
+ var _a, _b;
177
172
  const val = value[field.name];
178
173
  if (!field.options.validation) {
179
174
  return;
180
175
  }
181
- const fieldLabel = unwrapTplLabel(((_a = field.options.uiSchema) == null ? void 0 : _a.title) || field.name);
182
176
  if (field instanceof import_fields.RelationField) {
183
- if ((_b = field.options) == null ? void 0 : _b.validation.rules) {
184
- const isRequired = (_c = field.options) == null ? void 0 : _c.validation.rules.some((rule) => rule.name === "required");
185
- if (isRequired && !val) {
186
- throw new Error(
187
- t("{{#label}} is required", {
188
- ns: "client",
189
- "#label": `${t("Collection", { ns: "client" })}: ${this.name}, ${t("Field", { ns: "client" })}: ${t(
190
- fieldLabel,
191
- { ns: "client" }
192
- )}`
193
- })
194
- );
177
+ const rules = ((_b = (_a = field.options) == null ? void 0 : _a.validation) == null ? void 0 : _b.rules) || [];
178
+ const required = rules.some((rule) => rule.name === "required");
179
+ if (required) {
180
+ const { error: error2 } = import_joi.default.any().empty(null).required().label(`${this.name}.${field.name}`).validate(val);
181
+ if (error2) {
182
+ throw error2;
195
183
  }
196
184
  }
197
185
  return;
198
186
  }
199
187
  const joiSchema = (0, import_field_validation.buildJoiSchema)(field.options.validation, {
200
- label: `${t("Collection", { ns: "client" })}: ${this.name}, ${t("Field", { ns: "client" })}: ${t(fieldLabel, {
201
- ns: "client"
202
- })}`,
188
+ label: `${this.name}.${field.name}`,
203
189
  value: val
204
190
  });
205
- const { error } = joiSchema.validate(val, {
206
- messages: (0, import_field_validation.getJoiErrorMessage)(t)
207
- });
191
+ const { error } = joiSchema.validate(val);
208
192
  if (error) {
209
193
  throw error;
210
194
  }
@@ -613,6 +597,12 @@ const _Collection = class _Collection extends import_events.EventEmitter {
613
597
  }
614
598
  this.setField(options.name || name, options);
615
599
  }
600
+ normalizeFieldName(val) {
601
+ if (!this.options.underscored) {
602
+ return val;
603
+ }
604
+ return Array.isArray(val) ? val.map((v) => (0, import_utils.snakeCase)(v)) : (0, import_utils.snakeCase)(val);
605
+ }
616
606
  addIndex(index) {
617
607
  if (!index) {
618
608
  return;
@@ -642,7 +632,7 @@ const _Collection = class _Collection extends import_events.EventEmitter {
642
632
  return;
643
633
  }
644
634
  for (const item of indexes) {
645
- if (import_lodash.default.isEqual(item.fields, indexName)) {
635
+ if (import_lodash.default.isEqual(this.normalizeFieldName(item.fields), this.normalizeFieldName(indexName))) {
646
636
  return;
647
637
  }
648
638
  const name2 = item.fields.join(",");
@@ -678,11 +668,21 @@ const _Collection = class _Collection extends import_events.EventEmitter {
678
668
  */
679
669
  refreshIndexes() {
680
670
  const indexes = this.model._indexes;
671
+ const attributes = {};
672
+ for (const [name, field] of Object.entries(this.model.getAttributes())) {
673
+ attributes[this.normalizeFieldName(name)] = field;
674
+ }
681
675
  this.model._indexes = import_lodash.default.uniqBy(
682
676
  indexes.filter((item) => {
683
- return item.fields.every((field) => this.model.rawAttributes[field]);
677
+ return item.fields.every((field) => {
678
+ const name = this.normalizeFieldName(field);
679
+ return attributes[name];
680
+ });
684
681
  }).map((item) => {
685
- item.fields = item.fields.map((field) => this.model.rawAttributes[field].field);
682
+ item.fields = item.fields.map((field) => {
683
+ const name = this.normalizeFieldName(field);
684
+ return attributes[name].field;
685
+ });
686
686
  return item;
687
687
  }),
688
688
  "name"
package/lib/database.d.ts CHANGED
@@ -215,6 +215,7 @@ export declare class Database extends EventEmitter implements AsyncEmitter {
215
215
  private registerCollectionType;
216
216
  quoteIdentifier(identifier: string): string;
217
217
  quoteTable(tableName: string): string;
218
+ private runSQLWithSchema;
218
219
  runSQL(sql: string, options?: RunSQLOptions): Promise<any>;
219
220
  }
220
221
  export declare function extendCollection(collectionOptions: CollectionOptions, mergeOptions?: MergeOptions): {
package/lib/database.js CHANGED
@@ -287,8 +287,8 @@ const _Database = class _Database extends import_events.EventEmitter {
287
287
  */
288
288
  initListener() {
289
289
  this.on("afterConnect", async (client) => {
290
- if (this.inDialect("postgres")) {
291
- await client.query("SET search_path = public");
290
+ if (this.isPostgresCompatibleDialect()) {
291
+ await client.query("SET search_path TO public");
292
292
  }
293
293
  });
294
294
  this.on("beforeDefine", (model, options) => {
@@ -431,11 +431,7 @@ const _Database = class _Database extends import_events.EventEmitter {
431
431
  */
432
432
  collection(options) {
433
433
  options = import_lodash.default.cloneDeep(options);
434
- if (typeof options.underscored !== "boolean") {
435
- if (this.options.underscored) {
436
- options.underscored = true;
437
- }
438
- }
434
+ options.underscored = options.underscored ?? this.options.underscored;
439
435
  this.logger.trace(`beforeDefineCollection: ${(0, import_safe_json_stringify.default)(options)}`, {
440
436
  databaseInstanceId: this.instanceId
441
437
  });
@@ -791,18 +787,28 @@ const _Database = class _Database extends import_events.EventEmitter {
791
787
  quoteTable(tableName) {
792
788
  return this.sequelize.getQueryInterface().quoteIdentifiers(tableName);
793
789
  }
790
+ async runSQLWithSchema(finalSQL, bind, transaction) {
791
+ if (!this.options.schema || !this.isPostgresCompatibleDialect()) {
792
+ return this.sequelize.query(finalSQL, { bind, transaction });
793
+ }
794
+ const execute = /* @__PURE__ */ __name(async (t) => {
795
+ await this.sequelize.query(`SET LOCAL search_path TO ${this.options.schema}`, { transaction: t });
796
+ return this.sequelize.query(finalSQL, { bind, transaction: t });
797
+ }, "execute");
798
+ return transaction ? execute(transaction) : this.sequelize.transaction(execute);
799
+ }
794
800
  async runSQL(sql, options = {}) {
795
801
  const { filter, bind, type, transaction } = options;
796
802
  let finalSQL = sql;
797
803
  if (!finalSQL.replace(/\s+/g, " ").trim()) {
798
804
  throw new Error("SQL cannot be empty");
799
805
  }
806
+ const queryGenerator = this.sequelize.getQueryInterface().queryGenerator;
800
807
  if (filter) {
801
808
  let where = {};
802
809
  const tmpCollection = new import_collection.Collection({ name: "tmp", underscored: false }, { database: this });
803
810
  const r = tmpCollection.repository;
804
811
  where = r.buildQueryOptions({ filter }).where;
805
- const queryGenerator = this.sequelize.getQueryInterface().queryGenerator;
806
812
  const wSQL = queryGenerator.getWhereConditions(where, null, null, { bindParam: true });
807
813
  if (wSQL) {
808
814
  let normalizedSQL = sql.replace(/\s+/g, " ").trim();
@@ -813,7 +819,7 @@ const _Database = class _Database extends import_events.EventEmitter {
813
819
  }
814
820
  }
815
821
  this.logger.debug("runSQL", { finalSQL });
816
- const result = await this.sequelize.query(finalSQL, { bind, transaction });
822
+ const result = await this.runSQLWithSchema(finalSQL, bind, transaction);
817
823
  let data = result[0];
818
824
  if (type === "selectVar") {
819
825
  if (Array.isArray(data)) {
@@ -35,7 +35,12 @@ module.exports = __toCommonJS(mariadb_dialect_exports);
35
35
  var import_base_dialect = require("./base-dialect");
36
36
  const _MariadbDialect = class _MariadbDialect extends import_base_dialect.BaseDialect {
37
37
  getSequelizeOptions(options) {
38
- options.dialectOptions = { ...options.dialectOptions || {}, supportBigNumbers: true, bigNumberStrings: true };
38
+ options.dialectOptions = {
39
+ ...options.dialectOptions || {},
40
+ multipleStatements: true,
41
+ supportBigNumbers: true,
42
+ bigNumberStrings: true
43
+ };
39
44
  return options;
40
45
  }
41
46
  getVersionGuard() {
@@ -52,9 +52,6 @@ const _PostgresDialect = class _PostgresDialect extends import_base_dialect.Base
52
52
  if (!options.hooks["afterConnect"]) {
53
53
  options.hooks["afterConnect"] = [];
54
54
  }
55
- options.hooks["afterConnect"].push(async (connection) => {
56
- await connection.query("SET search_path TO public;");
57
- });
58
55
  return options;
59
56
  }
60
57
  getVersionGuard() {
@@ -215,7 +215,8 @@ const _EagerLoadingTree = class _EagerLoadingTree {
215
215
  attributes: [primaryKeyField],
216
216
  group: `${node.model.name}.${primaryKeyField}`,
217
217
  transaction,
218
- include: (0, import_utils.processIncludes)(includeForFilter, node.model)
218
+ include: (0, import_utils.processIncludes)(includeForFilter, node.model),
219
+ raw: true
219
220
  })).map((row) => {
220
221
  return { row, pk: row[primaryKeyField] };
221
222
  });
@@ -27,7 +27,6 @@ import { UidFieldOptions } from './uid-field';
27
27
  import { UUIDFieldOptions } from './uuid-field';
28
28
  import { VirtualFieldOptions } from './virtual-field';
29
29
  import { NanoidFieldOptions } from './nanoid-field';
30
- import { EncryptionField } from './encryption-field';
31
30
  import { UnixTimestampFieldOptions } from './unix-timestamp-field';
32
31
  import { DateOnlyFieldOptions } from './date-only-field';
33
32
  import { DatetimeNoTzFieldOptions } from './datetime-no-tz-field';
@@ -59,7 +58,6 @@ export * from './uid-field';
59
58
  export * from './uuid-field';
60
59
  export * from './virtual-field';
61
60
  export * from './nanoid-field';
62
- export * from './encryption-field';
63
61
  export * from './unix-timestamp-field';
64
62
  export * from './snowflake-id-field';
65
- export type FieldOptions = BaseFieldOptions | StringFieldOptions | IntegerFieldOptions | FloatFieldOptions | DecimalFieldOptions | DoubleFieldOptions | RealFieldOptions | JsonFieldOptions | JsonbFieldOptions | BooleanFieldOptions | RadioFieldOptions | TextFieldOptions | VirtualFieldOptions | ArrayFieldOptions | SetFieldOptions | TimeFieldOptions | DateFieldOptions | DatetimeTzFieldOptions | DatetimeNoTzFieldOptions | DateOnlyFieldOptions | UnixTimestampFieldOptions | UidFieldOptions | UUIDFieldOptions | NanoidFieldOptions | PasswordFieldOptions | ContextFieldOptions | BelongsToFieldOptions | HasOneFieldOptions | HasManyFieldOptions | BelongsToManyFieldOptions | EncryptionField | SnowflakeIdFieldOptions;
63
+ export type FieldOptions = BaseFieldOptions | StringFieldOptions | IntegerFieldOptions | FloatFieldOptions | DecimalFieldOptions | DoubleFieldOptions | RealFieldOptions | JsonFieldOptions | JsonbFieldOptions | BooleanFieldOptions | RadioFieldOptions | TextFieldOptions | VirtualFieldOptions | ArrayFieldOptions | SetFieldOptions | TimeFieldOptions | DateFieldOptions | DatetimeTzFieldOptions | DatetimeNoTzFieldOptions | DateOnlyFieldOptions | UnixTimestampFieldOptions | UidFieldOptions | UUIDFieldOptions | NanoidFieldOptions | PasswordFieldOptions | ContextFieldOptions | BelongsToFieldOptions | HasOneFieldOptions | HasManyFieldOptions | BelongsToManyFieldOptions | SnowflakeIdFieldOptions;
@@ -49,7 +49,6 @@ __reExport(fields_exports, require("./uid-field"), module.exports);
49
49
  __reExport(fields_exports, require("./uuid-field"), module.exports);
50
50
  __reExport(fields_exports, require("./virtual-field"), module.exports);
51
51
  __reExport(fields_exports, require("./nanoid-field"), module.exports);
52
- __reExport(fields_exports, require("./encryption-field"), module.exports);
53
52
  __reExport(fields_exports, require("./unix-timestamp-field"), module.exports);
54
53
  __reExport(fields_exports, require("./snowflake-id-field"), module.exports);
55
54
  // Annotate the CommonJS export names for ESM import in node:
@@ -80,7 +79,6 @@ __reExport(fields_exports, require("./snowflake-id-field"), module.exports);
80
79
  ...require("./uuid-field"),
81
80
  ...require("./virtual-field"),
82
81
  ...require("./nanoid-field"),
83
- ...require("./encryption-field"),
84
82
  ...require("./unix-timestamp-field"),
85
83
  ...require("./snowflake-id-field")
86
84
  });
package/lib/index.d.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
9
  export { BaseError, BelongsToGetAssociationMixin, DataTypes, fn, HasManyCountAssociationsMixin, HasManyCreateAssociationMixin, HasManyGetAssociationsMixin, literal, ModelStatic, Op, SyncOptions, Transaction, UniqueConstraintError, ValidationError, ValidationErrorItem, where, } from 'sequelize';
10
+ export { ValidationError as JoiValidationError } from 'joi';
10
11
  export * from './belongs-to-array/belongs-to-array-repository';
11
12
  export * from './collection';
12
13
  export * from './collection-group-manager';
@@ -35,11 +36,12 @@ export * from './repository';
35
36
  export * from './relation-repository/relation-repository';
36
37
  export { default as sqlParser, SQLParserTypes } from './sql-parser';
37
38
  export * from './update-associations';
38
- export { snakeCase } from './utils';
39
+ export { snakeCase, extractTypeFromDefinition } from './utils';
39
40
  export * from './value-parsers';
40
41
  export * from './view-collection';
41
42
  export { default as fieldTypeMap } from './view/field-type-map';
42
43
  export * from './view/view-inference';
43
44
  export * from './update-guard';
45
+ export { TableInfo } from './query-interface/query-interface';
44
46
  export { default as operators } from './operators';
45
47
  export { filterIncludes, mergeIncludes } from './utils/filter-include';
package/lib/index.js CHANGED
@@ -44,15 +44,18 @@ __export(src_exports, {
44
44
  HasManyCountAssociationsMixin: () => import_sequelize.HasManyCountAssociationsMixin,
45
45
  HasManyCreateAssociationMixin: () => import_sequelize.HasManyCreateAssociationMixin,
46
46
  HasManyGetAssociationsMixin: () => import_sequelize.HasManyGetAssociationsMixin,
47
+ JoiValidationError: () => import_joi.ValidationError,
47
48
  ModelStatic: () => import_sequelize.ModelStatic,
48
49
  Op: () => import_sequelize.Op,
49
50
  SQLParserTypes: () => import_sql_parser.SQLParserTypes,
50
51
  SyncOptions: () => import_sequelize.SyncOptions,
52
+ TableInfo: () => import_query_interface.TableInfo,
51
53
  Transaction: () => import_sequelize.Transaction,
52
54
  UniqueConstraintError: () => import_sequelize.UniqueConstraintError,
53
55
  ValidationError: () => import_sequelize.ValidationError,
54
56
  ValidationErrorItem: () => import_sequelize.ValidationErrorItem,
55
57
  default: () => import_database.Database,
58
+ extractTypeFromDefinition: () => import_utils.extractTypeFromDefinition,
56
59
  fieldTypeMap: () => import_field_type_map.default,
57
60
  filterIncludes: () => import_filter_include.filterIncludes,
58
61
  fn: () => import_sequelize.fn,
@@ -65,6 +68,7 @@ __export(src_exports, {
65
68
  });
66
69
  module.exports = __toCommonJS(src_exports);
67
70
  var import_sequelize = require("sequelize");
71
+ var import_joi = require("joi");
68
72
  __reExport(src_exports, require("./belongs-to-array/belongs-to-array-repository"), module.exports);
69
73
  __reExport(src_exports, require("./collection"), module.exports);
70
74
  __reExport(src_exports, require("./collection-group-manager"), module.exports);
@@ -99,6 +103,7 @@ __reExport(src_exports, require("./view-collection"), module.exports);
99
103
  var import_field_type_map = __toESM(require("./view/field-type-map"));
100
104
  __reExport(src_exports, require("./view/view-inference"), module.exports);
101
105
  __reExport(src_exports, require("./update-guard"), module.exports);
106
+ var import_query_interface = require("./query-interface/query-interface");
102
107
  var import_operators = __toESM(require("./operators"));
103
108
  var import_filter_include = require("./utils/filter-include");
104
109
  // Annotate the CommonJS export names for ESM import in node:
@@ -110,14 +115,17 @@ var import_filter_include = require("./utils/filter-include");
110
115
  HasManyCountAssociationsMixin,
111
116
  HasManyCreateAssociationMixin,
112
117
  HasManyGetAssociationsMixin,
118
+ JoiValidationError,
113
119
  ModelStatic,
114
120
  Op,
115
121
  SQLParserTypes,
116
122
  SyncOptions,
123
+ TableInfo,
117
124
  Transaction,
118
125
  UniqueConstraintError,
119
126
  ValidationError,
120
127
  ValidationErrorItem,
128
+ extractTypeFromDefinition,
121
129
  fieldTypeMap,
122
130
  filterIncludes,
123
131
  fn,
@@ -47,7 +47,7 @@ import_dayjs.default.extend(import_utc.default);
47
47
  const _TimeInterface = class _TimeInterface extends import_base_interface.BaseInterface {
48
48
  toValue(value, ctx) {
49
49
  if (this.validate(value)) {
50
- const result = import_dayjs.default.utc(value).format("HH:mm:ss");
50
+ const result = (0, import_dayjs.default)(value).format("HH:mm:ss");
51
51
  return result;
52
52
  }
53
53
  return value;
@@ -6,6 +6,5 @@
6
6
  * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
- export * from './encryption-field';
10
- export * from './utils';
11
- export * from './errors/EncryptionError';
9
+ declare const _default: Record<string, any>;
10
+ export default _default;
@@ -11,7 +11,6 @@ var __defProp = Object.defineProperty;
11
11
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
12
  var __getOwnPropNames = Object.getOwnPropertyNames;
13
13
  var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
15
14
  var __export = (target, all) => {
16
15
  for (var name in all)
17
16
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -25,20 +24,17 @@ var __copyProps = (to, from, except, desc) => {
25
24
  return to;
26
25
  };
27
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
- var EncryptionError_exports = {};
29
- __export(EncryptionError_exports, {
30
- EncryptionError: () => EncryptionError
27
+ var in_exports = {};
28
+ __export(in_exports, {
29
+ default: () => in_default
31
30
  });
32
- module.exports = __toCommonJS(EncryptionError_exports);
33
- const _EncryptionError = class _EncryptionError extends Error {
34
- constructor(message, options) {
35
- super(message, options);
36
- this.name = "EncryptionError";
31
+ module.exports = __toCommonJS(in_exports);
32
+ var import_lodash = require("lodash");
33
+ var import_sequelize = require("sequelize");
34
+ var in_default = {
35
+ $in(val, ctx) {
36
+ return {
37
+ [import_sequelize.Op.in]: val == null ? [] : (0, import_lodash.castArray)(val)
38
+ };
37
39
  }
38
40
  };
39
- __name(_EncryptionError, "EncryptionError");
40
- let EncryptionError = _EncryptionError;
41
- // Annotate the CommonJS export names for ESM import in node:
42
- 0 && (module.exports = {
43
- EncryptionError
44
- });
@@ -46,6 +46,7 @@ var import_empty = __toESM(require("./empty"));
46
46
  var import_string = __toESM(require("./string"));
47
47
  var import_eq = __toESM(require("./eq"));
48
48
  var import_ne = __toESM(require("./ne"));
49
+ var import_in = __toESM(require("./in"));
49
50
  var import_notIn = __toESM(require("./notIn"));
50
51
  var import_boolean = __toESM(require("./boolean"));
51
52
  var import_child_collection = __toESM(require("./child-collection"));
@@ -57,6 +58,7 @@ var operators_default = {
57
58
  ...import_string.default,
58
59
  ...import_eq.default,
59
60
  ...import_ne.default,
61
+ ...import_in.default,
60
62
  ...import_notIn.default,
61
63
  ...import_boolean.default,
62
64
  ...import_child_collection.default
@@ -88,8 +88,7 @@ const _BelongsToManyRepository = class _BelongsToManyRepository extends import_m
88
88
  };
89
89
  this.collection.validate({
90
90
  values,
91
- operation: "create",
92
- context: options.context
91
+ operation: "create"
93
92
  });
94
93
  const instance = await sourceModel[createAccessor](values, createOptions);
95
94
  await (0, import_update_associations.updateAssociations)(instance, values, { ...options, transaction: transaction2 });
@@ -178,7 +178,7 @@ const _RelationRepository = class _RelationRepository {
178
178
  const values = options.values;
179
179
  const transaction2 = await this.getTransaction(options);
180
180
  const sourceModel = await this.getSourceModel(transaction2);
181
- this.collection.validate({ values, context: options.context, operation: "create" });
181
+ this.collection.validate({ values, operation: "create" });
182
182
  const instance = await sourceModel[createAccessor](guard.sanitize(options.values), { ...options, transaction: transaction2 });
183
183
  await (0, import_update_associations.updateAssociations)(instance, values, { ...options, transaction: transaction2 });
184
184
  if (options.hooks !== false) {
@@ -51,7 +51,6 @@ module.exports = __toCommonJS(single_relation_repository_exports);
51
51
  var import_target_collection_decorator = __toESM(require("../decorators/target-collection-decorator"));
52
52
  var import_update_associations = require("../update-associations");
53
53
  var import_relation_repository = require("./relation-repository");
54
- var import_lodash = __toESM(require("lodash"));
55
54
  const _SingleRelationRepository = class _SingleRelationRepository extends import_relation_repository.RelationRepository {
56
55
  async remove(options) {
57
56
  const transaction2 = await this.getTransaction(options);
@@ -104,7 +103,7 @@ const _SingleRelationRepository = class _SingleRelationRepository extends import
104
103
  throw new Error("The record does not exist");
105
104
  }
106
105
  await (0, import_update_associations.updateModelByValues)(target, options == null ? void 0 : options.values, {
107
- ...import_lodash.default.omit(options, "values"),
106
+ ...options,
108
107
  transaction: transaction2
109
108
  });
110
109
  if (options.hooks !== false) {
package/lib/repository.js CHANGED
@@ -453,7 +453,7 @@ const _Repository = class _Repository {
453
453
  underscored: this.collection.options.underscored
454
454
  });
455
455
  const values = this.model.callSetters(guard.sanitize(options.values || {}), options);
456
- this.validate({ values, context: options.context, operation: "create" });
456
+ this.validate({ values, operation: "create" });
457
457
  const instance = await this.model.create(values, {
458
458
  ...options,
459
459
  transaction: transaction2
@@ -498,7 +498,7 @@ const _Repository = class _Repository {
498
498
  const transaction2 = await this.getTransaction(options);
499
499
  const guard = import_update_guard.UpdateGuard.fromOptions(this.model, { ...options, underscored: this.collection.options.underscored });
500
500
  const values = this.model.callSetters(guard.sanitize(options.values || {}), options);
501
- this.validate({ values, context: options.context, operation: "update" });
501
+ this.validate({ values, operation: "update" });
502
502
  if (options.individualHooks === false) {
503
503
  const { model: Model2 } = this.collection;
504
504
  const primaryKeyField = Model2.primaryKeyField || Model2.primaryKeyAttribute;
@@ -162,6 +162,9 @@ const _SyncRunner = class _SyncRunner {
162
162
  }, "isJSONColumn");
163
163
  for (const columnName in columns) {
164
164
  const column = columns[columnName];
165
+ if (isJSONColumn(column) && this.database.inDialect("mysql")) {
166
+ continue;
167
+ }
165
168
  const isPrimaryKey = /* @__PURE__ */ __name(() => {
166
169
  const attribute = this.findAttributeByColumnName(columnName);
167
170
  return attribute && attribute.primaryKey || column.primaryKey;
@@ -13,9 +13,7 @@ export declare function modelAssociations(instance: Model): {
13
13
  [key: string]: Association<import("sequelize").Model<any, any>, import("sequelize").Model<any, any>>;
14
14
  };
15
15
  export declare function belongsToManyAssociations(instance: Model): Array<BelongsToMany>;
16
- export declare function modelAssociationByKey(instance: Model, key: string): Association & {
17
- update?: (instance: Model, value: any, options: UpdateAssociationOptions) => Promise<any>;
18
- };
16
+ export declare function modelAssociationByKey(instance: Model, key: string): Association;
19
17
  type UpdateValue = {
20
18
  [key: string]: any;
21
19
  };
@@ -51,7 +49,7 @@ export declare function updateAssociations(instance: Model, values: any, options
51
49
  * @param value
52
50
  * @param options
53
51
  */
54
- export declare function updateAssociation(instance: Model, key: string, value: any, options?: UpdateAssociationOptions): Promise<any>;
52
+ export declare function updateAssociation(instance: Model, key: string, value: any, options?: UpdateAssociationOptions): Promise<boolean>;
55
53
  /**
56
54
  * update belongsTo and HasOne
57
55
  * @param model
@@ -81,8 +81,7 @@ async function updateModelByValues(instance, values, options) {
81
81
  }
82
82
  instance.constructor.collection.validate({
83
83
  values,
84
- operation: "update",
85
- context: options == null ? void 0 : options.context
84
+ operation: "update"
86
85
  });
87
86
  await instance.update(values, options);
88
87
  await updateAssociations(instance, values, options);
@@ -177,9 +176,6 @@ async function updateAssociation(instance, key, value, options = {}) {
177
176
  if (options.associationContext && isReverseAssociationPair(association, options.associationContext)) {
178
177
  return false;
179
178
  }
180
- if (association.update) {
181
- return association.update(instance, value, options);
182
- }
183
179
  switch (association.associationType) {
184
180
  case "HasOne":
185
181
  case "BelongsTo":
@@ -259,7 +255,7 @@ async function updateSingleAssociation(model, key, value, options = {}) {
259
255
  if (association.associationType === "HasOne") {
260
256
  delete updateValues[association.foreignKey];
261
257
  }
262
- await instance2.update(updateValues, { ...options, transaction });
258
+ await instance2.update(updateValues, { ...options, transaction, inputValues: updateValues });
263
259
  }
264
260
  await updateAssociations(instance2, value, {
265
261
  ...options,
@@ -273,10 +269,9 @@ async function updateSingleAssociation(model, key, value, options = {}) {
273
269
  }
274
270
  association.target.collection.validate({
275
271
  values: value,
276
- context: options.context,
277
272
  operation: "create"
278
273
  });
279
- const instance = await model[createAccessor](value, { context, transaction });
274
+ const instance = await model[createAccessor](value, { context, transaction, inputValues: value });
280
275
  await updateAssociations(instance, value, {
281
276
  ...options,
282
277
  transaction,
@@ -368,10 +363,9 @@ async function updateMultipleAssociation(model, key, value, options = {}) {
368
363
  if ((0, import_utils.isUndefinedOrNull)(item[targetKey])) {
369
364
  association.target.collection.validate({
370
365
  values: item,
371
- context: options.context,
372
366
  operation: "create"
373
367
  });
374
- const instance = await model[createAccessor](item, accessorOptions);
368
+ const instance = await model[createAccessor](item, { ...accessorOptions, inputValues: item });
375
369
  await updateAssociations(instance, item, {
376
370
  ...options,
377
371
  transaction,
@@ -390,10 +384,9 @@ async function updateMultipleAssociation(model, key, value, options = {}) {
390
384
  if (!instance) {
391
385
  association.target.collection.validate({
392
386
  values: item,
393
- context: options.context,
394
387
  operation: "create"
395
388
  });
396
- instance = await model[createAccessor](item, accessorOptions);
389
+ instance = await model[createAccessor](item, { ...accessorOptions, inputValues: item });
397
390
  await updateAssociations(instance, item, {
398
391
  ...options,
399
392
  transaction,
@@ -414,10 +407,9 @@ async function updateMultipleAssociation(model, key, value, options = {}) {
414
407
  }
415
408
  association.target.collection.validate({
416
409
  values: item,
417
- context: options.context,
418
410
  operation: "update"
419
411
  });
420
- await instance.update(item, { ...options, transaction });
412
+ await instance.update(item, { ...options, transaction, inputValues: item });
421
413
  }
422
414
  await updateAssociations(instance, item, {
423
415
  ...options,
@@ -12,48 +12,3 @@ export declare function buildJoiSchema(validation: ValidationOptions, options: {
12
12
  label?: string;
13
13
  value: string;
14
14
  }): AnySchema;
15
- export declare function getJoiErrorMessage(t: Function): {
16
- 'string.base': any;
17
- 'string.empty': any;
18
- 'string.min': any;
19
- 'string.max': any;
20
- 'string.length': any;
21
- 'string.alphanum': any;
22
- 'string.token': any;
23
- 'string.regex': any;
24
- 'string.email': any;
25
- 'string.uri': any;
26
- 'string.uriCustomScheme': any;
27
- 'string.isoDate': any;
28
- 'string.guid': any;
29
- 'string.hex': any;
30
- 'string.hostname': any;
31
- 'string.lowercase': any;
32
- 'string.uppercase': any;
33
- 'string.trim': any;
34
- 'string.creditCard': any;
35
- 'string.pattern.base': any;
36
- 'string.pattern.name': any;
37
- 'string.pattern.invert.base': any;
38
- 'string.pattern.invert.name': any;
39
- 'any.required': any;
40
- 'number.base': any;
41
- 'number.min': any;
42
- 'number.max': any;
43
- 'number.less': any;
44
- 'number.greater': any;
45
- 'number.float': any;
46
- 'number.integer': any;
47
- 'number.negative': any;
48
- 'number.positive': any;
49
- 'number.precision': any;
50
- 'number.multiple': any;
51
- 'number.port': any;
52
- 'number.unsafe': any;
53
- 'date.base': any;
54
- 'date.format': any;
55
- 'date.greater': any;
56
- 'date.less': any;
57
- 'date.max': any;
58
- 'date.min': any;
59
- };
@@ -37,8 +37,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
37
37
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
38
  var field_validation_exports = {};
39
39
  __export(field_validation_exports, {
40
- buildJoiSchema: () => buildJoiSchema,
41
- getJoiErrorMessage: () => getJoiErrorMessage
40
+ buildJoiSchema: () => buildJoiSchema
42
41
  });
43
42
  module.exports = __toCommonJS(field_validation_exports);
44
43
  var import_joi = __toESM(require("joi"));
@@ -80,64 +79,7 @@ function buildJoiSchema(validation, options) {
80
79
  return schema;
81
80
  }
82
81
  __name(buildJoiSchema, "buildJoiSchema");
83
- function getJoiErrorMessage(t) {
84
- const tOptions = { ns: "client" };
85
- const JoiErrorMessages = {
86
- "string.base": t("{{#label}} must be a string", tOptions),
87
- "string.empty": t("{{#label}} is not allowed to be empty", tOptions),
88
- "string.min": t("{{#label}} length must be at least {{#limit}} characters long", tOptions),
89
- "string.max": t("{{#label}} length must be less than or equal to {{#limit}} characters long", tOptions),
90
- "string.length": t("{{#label}} length must be {{#limit}} characters long", tOptions),
91
- "string.alphanum": t("{{#label}} must only contain alpha-numeric characters", tOptions),
92
- "string.token": t("{{#label}} must only contain alpha-numeric and underscore characters", tOptions),
93
- "string.regex": t("{{#label}} with value {{#value}} fails to match the required pattern", tOptions),
94
- "string.email": t("{{#label}} email address doesn\u2019t meet the required format", tOptions),
95
- "string.uri": t("{{#label}} must be a valid uri", tOptions),
96
- "string.uriCustomScheme": t(
97
- "{{#label}} must be a valid uri with a scheme matching the {{#scheme}} pattern",
98
- tOptions
99
- ),
100
- "string.isoDate": t("{{#label}} must be a valid ISO 8601 date", tOptions),
101
- "string.guid": t("{{#label}} must be a valid UUID", tOptions),
102
- "string.hex": t("{{#label}} must only contain hexadecimal characters", tOptions),
103
- "string.hostname": t("{{#label}} must be a valid hostname", tOptions),
104
- "string.lowercase": t("{{#label}} must only contain lowercase characters", tOptions),
105
- "string.uppercase": t("{{#label}} must only contain uppercase characters", tOptions),
106
- "string.trim": t("{{#label}} must not have leading or trailing whitespace", tOptions),
107
- "string.creditCard": t("{{#label}} must be a credit card", tOptions),
108
- "string.pattern.base": t('{{#label}} with value "{{#value}}" fails to match the required pattern', tOptions),
109
- "string.pattern.name": t('{{#label}} with value "{{#value}}" fails to match the {{#name}} pattern', tOptions),
110
- "string.pattern.invert.base": t('{{#label}} with value "{{#value}}" matches the inverted pattern', tOptions),
111
- "string.pattern.invert.name": t(
112
- '{{#label}} with value "{{#value}}" matches the inverted {{#name}} pattern',
113
- tOptions
114
- ),
115
- "any.required": t("{{#label}} is required", tOptions),
116
- "number.base": t("{{#label}} must be a number", tOptions),
117
- "number.min": t("{{#label}} must be greater than or equal to {{#limit}}", tOptions),
118
- "number.max": t("{{#label}} must be less than or equal to {{#limit}}", tOptions),
119
- "number.less": t("{{#label}} must be less than {{#limit}}", tOptions),
120
- "number.greater": t("{{#label}} must be greater than {{#limit}}", tOptions),
121
- "number.float": t("{{#label}} must be a float or double", tOptions),
122
- "number.integer": t("{{#label}} must be an integer", tOptions),
123
- "number.negative": t("{{#label}} must be a negative number", tOptions),
124
- "number.positive": t("{{#label}} must be a positive number", tOptions),
125
- "number.precision": t("{{#label}} must not have more than {{#limit}} decimal places", tOptions),
126
- "number.multiple": t("{{#label}} must be a multiple of {{#multiple}}", tOptions),
127
- "number.port": t("{{#label}} must be a valid port", tOptions),
128
- "number.unsafe": t("{{#label}} must be a safe number", tOptions),
129
- "date.base": t("{{#label}} must be a valid date", tOptions),
130
- "date.format": t("{{#label}} must be in {{#format}} format", tOptions),
131
- "date.greater": t("{{#label}} must be greater than {{#limit}}", tOptions),
132
- "date.less": t("{{#label}} must be less than {{#limit}}", tOptions),
133
- "date.max": t("{{#label}} must be less than or equal to {{#limit}}", tOptions),
134
- "date.min": t("{{#label}} must be greater than or equal to {{#limit}}", tOptions)
135
- };
136
- return JoiErrorMessages;
137
- }
138
- __name(getJoiErrorMessage, "getJoiErrorMessage");
139
82
  // Annotate the CommonJS export names for ESM import in node:
140
83
  0 && (module.exports = {
141
- buildJoiSchema,
142
- getJoiErrorMessage
84
+ buildJoiSchema
143
85
  });
package/lib/utils.d.ts CHANGED
@@ -16,4 +16,5 @@ export declare function percent2float(value: string): number;
16
16
  export declare function isUndefinedOrNull(value: any): boolean;
17
17
  export declare function isStringOrNumber(value: any): boolean;
18
18
  export declare function getKeysByPrefix(keys: string[], prefix: string): string[];
19
+ export declare function extractTypeFromDefinition(rawType: string): string;
19
20
  export declare function processIncludes(includes: any[], model: any, parentAs?: string): any[];
package/lib/utils.js CHANGED
@@ -38,6 +38,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
38
38
  var utils_exports = {};
39
39
  __export(utils_exports, {
40
40
  checkIdentifier: () => checkIdentifier,
41
+ extractTypeFromDefinition: () => extractTypeFromDefinition,
41
42
  getKeysByPrefix: () => getKeysByPrefix,
42
43
  getTableName: () => getTableName,
43
44
  isStringOrNumber: () => isStringOrNumber,
@@ -141,6 +142,14 @@ function getKeysByPrefix(keys, prefix) {
141
142
  return keys.filter((key) => key.startsWith(`${prefix}.`)).map((key) => key.substring(prefix.length + 1));
142
143
  }
143
144
  __name(getKeysByPrefix, "getKeysByPrefix");
145
+ function extractTypeFromDefinition(rawType) {
146
+ const leftParenIndex = rawType.indexOf("(");
147
+ if (leftParenIndex === -1) {
148
+ return rawType.toLowerCase();
149
+ }
150
+ return rawType.substring(0, leftParenIndex).toLowerCase().trim();
151
+ }
152
+ __name(extractTypeFromDefinition, "extractTypeFromDefinition");
144
153
  function processIncludes(includes, model, parentAs = "") {
145
154
  includes.forEach((include, index) => {
146
155
  const association = model.associations[include.association];
@@ -164,6 +173,7 @@ __name(processIncludes, "processIncludes");
164
173
  // Annotate the CommonJS export names for ESM import in node:
165
174
  0 && (module.exports = {
166
175
  checkIdentifier,
176
+ extractTypeFromDefinition,
167
177
  getKeysByPrefix,
168
178
  getTableName,
169
179
  isStringOrNumber,
@@ -39,7 +39,7 @@ const postgres = {
39
39
  name: "string",
40
40
  smallint: ["integer", "sort"],
41
41
  integer: ["integer", "unixTimestamp", "sort"],
42
- bigint: ["bigInt", "unixTimestamp", "sort"],
42
+ bigint: ["bigInt", "snowflakeId", "unixTimestamp", "sort"],
43
43
  decimal: "decimal",
44
44
  numeric: "float",
45
45
  real: "float",
@@ -77,7 +77,7 @@ const mysql = {
77
77
  int: ["integer", "unixTimestamp", "sort"],
78
78
  "int unsigned": ["integer", "unixTimestamp", "sort"],
79
79
  integer: ["integer", "unixTimestamp", "sort"],
80
- bigint: ["bigInt", "unixTimestamp", "sort"],
80
+ bigint: ["bigInt", "snowflakeId", "unixTimestamp", "sort"],
81
81
  "bigint unsigned": ["bigInt", "unixTimestamp", "sort"],
82
82
  float: "float",
83
83
  double: "float",
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@nocobase/database",
3
- "version": "2.0.0-alpha.5",
3
+ "version": "2.0.0-alpha.50",
4
4
  "description": "",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",
7
7
  "license": "AGPL-3.0",
8
8
  "dependencies": {
9
- "@nocobase/logger": "2.0.0-alpha.5",
10
- "@nocobase/utils": "2.0.0-alpha.5",
9
+ "@nocobase/logger": "2.0.0-alpha.50",
10
+ "@nocobase/utils": "2.0.0-alpha.50",
11
11
  "async-mutex": "^0.3.2",
12
12
  "chalk": "^4.1.1",
13
13
  "cron-parser": "4.4.0",
@@ -39,5 +39,5 @@
39
39
  "url": "git+https://github.com/nocobase/nocobase.git",
40
40
  "directory": "packages/database"
41
41
  },
42
- "gitHead": "943e035bbec27f9ecfe8ce8857955945f20976f3"
42
+ "gitHead": "a6eb64abf3632e116ad0b295a7f410270a1059d1"
43
43
  }
@@ -1,20 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- import { DataTypes } from 'sequelize';
10
- import { BaseColumnFieldOptions, Field } from '../field';
11
- export interface EncryptionFieldOptions extends BaseColumnFieldOptions {
12
- type: 'encryption';
13
- hidden?: boolean;
14
- }
15
- export declare class EncryptionField extends Field {
16
- get dataType(): DataTypes.StringDataTypeConstructor;
17
- init(): void;
18
- bind(): void;
19
- unbind(): void;
20
- }
@@ -1,110 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- var __defProp = Object.defineProperty;
11
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
- var __getOwnPropNames = Object.getOwnPropertyNames;
13
- var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
15
- var __export = (target, all) => {
16
- for (var name in all)
17
- __defProp(target, name, { get: all[name], enumerable: true });
18
- };
19
- var __copyProps = (to, from, except, desc) => {
20
- if (from && typeof from === "object" || typeof from === "function") {
21
- for (let key of __getOwnPropNames(from))
22
- if (!__hasOwnProp.call(to, key) && key !== except)
23
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
24
- }
25
- return to;
26
- };
27
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
- var encryption_field_exports = {};
29
- __export(encryption_field_exports, {
30
- EncryptionField: () => EncryptionField
31
- });
32
- module.exports = __toCommonJS(encryption_field_exports);
33
- var import_sequelize = require("sequelize");
34
- var import_EncryptionError = require("./errors/EncryptionError");
35
- var import_utils = require("./utils");
36
- var import_field = require("../field");
37
- const _EncryptionField = class _EncryptionField extends import_field.Field {
38
- get dataType() {
39
- return import_sequelize.DataTypes.STRING;
40
- }
41
- init() {
42
- (0, import_utils.aesCheckKey)();
43
- const { name, iv } = this.options;
44
- this.writeListener = async (model) => {
45
- (0, import_utils.aesCheckKey)();
46
- if (!model.changed(name)) {
47
- return;
48
- }
49
- const value = model.get(name);
50
- if (value !== void 0 && value !== null) {
51
- try {
52
- const encrypted = await (0, import_utils.aesEncrypt)(value, iv);
53
- model.set(name, encrypted);
54
- } catch (error) {
55
- console.error(error);
56
- if (error instanceof import_EncryptionError.EncryptionError) {
57
- throw error;
58
- } else {
59
- throw new import_EncryptionError.EncryptionError("Encryption failed");
60
- }
61
- }
62
- } else {
63
- model.set(name, null);
64
- }
65
- };
66
- this.findListener = async (instances, options) => {
67
- (0, import_utils.aesCheckKey)();
68
- instances = Array.isArray(instances) ? instances : [instances];
69
- await Promise.all(
70
- instances.map(async (instance) => {
71
- var _a;
72
- const value = (_a = instance.get) == null ? void 0 : _a.call(instance, name);
73
- if (value !== void 0 && value !== null) {
74
- try {
75
- instance.set(name, await (0, import_utils.aesDecrypt)(value, iv));
76
- } catch (error) {
77
- console.error(error);
78
- if (error instanceof import_EncryptionError.EncryptionError) {
79
- throw error;
80
- } else {
81
- throw new import_EncryptionError.EncryptionError(
82
- "Decryption failed, the environment variable `ENCRYPTION_FIELD_KEY` may be incorrect"
83
- );
84
- }
85
- }
86
- }
87
- return instance;
88
- })
89
- );
90
- };
91
- }
92
- bind() {
93
- super.bind();
94
- this.on("afterFind", this.findListener);
95
- this.on("beforeSave", this.writeListener);
96
- this.on("beforeBulkCreate", this.writeListener);
97
- }
98
- unbind() {
99
- super.unbind();
100
- this.off("afterFind", this.findListener);
101
- this.off("beforeSave", this.writeListener);
102
- this.off("beforeBulkCreate", this.writeListener);
103
- }
104
- };
105
- __name(_EncryptionField, "EncryptionField");
106
- let EncryptionField = _EncryptionField;
107
- // Annotate the CommonJS export names for ESM import in node:
108
- 0 && (module.exports = {
109
- EncryptionField
110
- });
@@ -1,11 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
- export declare class EncryptionError extends Error {
10
- constructor(message?: string, options?: ErrorOptions);
11
- }
@@ -1,34 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- var __defProp = Object.defineProperty;
11
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
- var __getOwnPropNames = Object.getOwnPropertyNames;
13
- var __hasOwnProp = Object.prototype.hasOwnProperty;
14
- var __copyProps = (to, from, except, desc) => {
15
- if (from && typeof from === "object" || typeof from === "function") {
16
- for (let key of __getOwnPropNames(from))
17
- if (!__hasOwnProp.call(to, key) && key !== except)
18
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
- }
20
- return to;
21
- };
22
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
23
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
- var encryption_field_exports = {};
25
- module.exports = __toCommonJS(encryption_field_exports);
26
- __reExport(encryption_field_exports, require("./encryption-field"), module.exports);
27
- __reExport(encryption_field_exports, require("./utils"), module.exports);
28
- __reExport(encryption_field_exports, require("./errors/EncryptionError"), module.exports);
29
- // Annotate the CommonJS export names for ESM import in node:
30
- 0 && (module.exports = {
31
- ...require("./encryption-field"),
32
- ...require("./utils"),
33
- ...require("./errors/EncryptionError")
34
- });
@@ -1,6 +0,0 @@
1
- export declare function aesEncrypt(text: string, ivString?: string): Promise<unknown>;
2
- export declare function aesDecrypt(encrypted: string, ivString?: string): Promise<unknown>;
3
- export declare function aesEncryptSync(text: string, ivString?: string): string;
4
- export declare function aseDecryptSync(encrypted: string, ivString?: string): string;
5
- export declare function aesCheckKey(): void;
6
- export declare function checkValueAndIv(type: 'Decrypt' | 'Encrypt', value: string, iv: string): void;
@@ -1,152 +0,0 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- var __create = Object.create;
11
- var __defProp = Object.defineProperty;
12
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
- var __getOwnPropNames = Object.getOwnPropertyNames;
14
- var __getProtoOf = Object.getPrototypeOf;
15
- var __hasOwnProp = Object.prototype.hasOwnProperty;
16
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
17
- var __export = (target, all) => {
18
- for (var name in all)
19
- __defProp(target, name, { get: all[name], enumerable: true });
20
- };
21
- var __copyProps = (to, from, except, desc) => {
22
- if (from && typeof from === "object" || typeof from === "function") {
23
- for (let key2 of __getOwnPropNames(from))
24
- if (!__hasOwnProp.call(to, key2) && key2 !== except)
25
- __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
26
- }
27
- return to;
28
- };
29
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
30
- // If the importer is in node compatibility mode or this is not an ESM
31
- // file that has been converted to a CommonJS file using a Babel-
32
- // compatible transform (i.e. "__esModule" has not been set), then set
33
- // "default" to the CommonJS "module.exports" for node compatibility.
34
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
35
- mod
36
- ));
37
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
38
- var utils_exports = {};
39
- __export(utils_exports, {
40
- aesCheckKey: () => aesCheckKey,
41
- aesDecrypt: () => aesDecrypt,
42
- aesEncrypt: () => aesEncrypt,
43
- aesEncryptSync: () => aesEncryptSync,
44
- aseDecryptSync: () => aseDecryptSync,
45
- checkValueAndIv: () => checkValueAndIv
46
- });
47
- module.exports = __toCommonJS(utils_exports);
48
- var import_crypto = __toESM(require("crypto"));
49
- var import_EncryptionError = require("./errors/EncryptionError");
50
- const algorithm = "aes-256-cbc";
51
- const keyString = process.env.ENCRYPTION_FIELD_KEY || "";
52
- const defaultIvString = process.env.ENCRYPTION_FIELD_IV || "Vc53-4G(rTi0vg@a";
53
- const key = Buffer.from(keyString, "utf8");
54
- function aesEncrypt(text, ivString = defaultIvString) {
55
- checkValueAndIv("Encrypt", text, ivString);
56
- return new Promise((resolve, reject) => {
57
- const iv = Buffer.from(ivString, "utf8");
58
- const cipher = import_crypto.default.createCipheriv(algorithm, key, iv);
59
- let encrypted = "";
60
- cipher.setEncoding("hex");
61
- cipher.on("data", (chunk) => {
62
- encrypted += chunk;
63
- });
64
- cipher.on("end", () => {
65
- resolve(encrypted);
66
- });
67
- cipher.on("error", (err) => {
68
- reject(err);
69
- });
70
- cipher.write(text);
71
- cipher.end();
72
- });
73
- }
74
- __name(aesEncrypt, "aesEncrypt");
75
- function aesDecrypt(encrypted, ivString = defaultIvString) {
76
- checkValueAndIv("Decrypt", encrypted, ivString);
77
- return new Promise((resolve, reject) => {
78
- const iv = Buffer.from(ivString, "utf8");
79
- const decipher = import_crypto.default.createDecipheriv(algorithm, key, iv);
80
- let decrypted = "";
81
- decipher.setEncoding("utf8");
82
- decipher.on("data", (chunk) => {
83
- decrypted += chunk;
84
- });
85
- decipher.on("end", () => {
86
- resolve(decrypted);
87
- });
88
- decipher.on("error", (err) => {
89
- reject(err);
90
- });
91
- decipher.write(encrypted, "hex");
92
- decipher.end();
93
- });
94
- }
95
- __name(aesDecrypt, "aesDecrypt");
96
- function aesEncryptSync(text, ivString = defaultIvString) {
97
- checkValueAndIv("Encrypt", text, ivString);
98
- const iv = Buffer.from(ivString, "utf8");
99
- const cipher = import_crypto.default.createCipheriv(algorithm, key, iv);
100
- let encrypted = cipher.update(text, "utf8", "hex");
101
- encrypted += cipher.final("hex");
102
- return encrypted;
103
- }
104
- __name(aesEncryptSync, "aesEncryptSync");
105
- function aseDecryptSync(encrypted, ivString = defaultIvString) {
106
- checkValueAndIv("Decrypt", encrypted, ivString);
107
- const iv = Buffer.from(ivString, "utf8");
108
- const decipher = import_crypto.default.createDecipheriv(algorithm, key, iv);
109
- let decrypted = decipher.update(encrypted, "hex", "utf8");
110
- decrypted += decipher.final("utf8");
111
- return decrypted;
112
- }
113
- __name(aseDecryptSync, "aseDecryptSync");
114
- function aesCheckKey() {
115
- if (!keyString) {
116
- throw new import_EncryptionError.EncryptionError("The environment variable `ENCRYPTION_FIELD_KEY` is required, please set it");
117
- }
118
- if (typeof keyString !== "string") {
119
- throw new import_EncryptionError.EncryptionError("The environment variable `ENCRYPTION_FIELD_KEY` must be a string");
120
- }
121
- if (keyString.length !== 32) {
122
- throw new import_EncryptionError.EncryptionError("The environment variable `ENCRYPTION_FIELD_KEY` must be a 32-character string");
123
- }
124
- }
125
- __name(aesCheckKey, "aesCheckKey");
126
- function checkValueAndIv(type, value, iv) {
127
- const msg = `${type} Failed: `;
128
- if (typeof value !== "string") {
129
- throw new import_EncryptionError.EncryptionError(msg + "The value must be a string, but got " + typeof value);
130
- }
131
- if (type === "Decrypt") {
132
- if (value.length % 2 !== 0) {
133
- throw new import_EncryptionError.EncryptionError(msg + `The encrypted value is invalid, not a hex string. The value is "${value}"`);
134
- }
135
- }
136
- if (typeof iv !== "string") {
137
- throw new import_EncryptionError.EncryptionError(msg + "The `iv` must be a string, but got " + typeof iv);
138
- }
139
- if (iv.length !== 16) {
140
- throw new import_EncryptionError.EncryptionError(msg + "The `iv` must be a 16-character string");
141
- }
142
- }
143
- __name(checkValueAndIv, "checkValueAndIv");
144
- // Annotate the CommonJS export names for ESM import in node:
145
- 0 && (module.exports = {
146
- aesCheckKey,
147
- aesDecrypt,
148
- aesEncrypt,
149
- aesEncryptSync,
150
- aseDecryptSync,
151
- checkValueAndIv
152
- });