@vsaas/loopback-datasource-juggler 12.1.1 → 12.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  //#region \0rolldown/runtime.js
2
- var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
2
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
3
3
  //#endregion
4
4
  exports.__commonJSMin = __commonJSMin;
@@ -381,9 +381,7 @@ var require_memory = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
381
381
  case "Boolean":
382
382
  val = Boolean(val);
383
383
  break;
384
- case "Number":
385
- val = Number(val);
386
- break;
384
+ case "Number": val = Number(val);
387
385
  }
388
386
  data[key] = val;
389
387
  }
@@ -49,7 +49,7 @@ Transient.prototype.generateId = function(model, data, idName) {
49
49
  if (idName) idType = props[idName] && props[idName].type;
50
50
  idType = idType || this.getDefaultIdType();
51
51
  if (idType === Number) return Math.floor(Math.random() * 1e4);
52
- else return crypto.randomBytes(Math.ceil(24 / 2)).toString("hex").slice(0, 24);
52
+ else return crypto.randomBytes(Math.ceil(12)).toString("hex").slice(0, 24);
53
53
  };
54
54
  Transient.prototype.exists = function exists(model, id, callback) {
55
55
  process.nextTick(function() {
package/dist/lib/dao.js CHANGED
@@ -595,10 +595,11 @@ var require_dao = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modul
595
595
  const id = getIdValue(this, data);
596
596
  if (id === void 0 || id === null) return this.create(data, options, cb);
597
597
  let doValidate = void 0;
598
- if (options.validate === void 0) if (Model.settings.validateUpsert === void 0) {
599
- if (Model.settings.automaticValidation !== void 0) doValidate = Model.settings.automaticValidation;
600
- } else doValidate = Model.settings.validateUpsert;
601
- else doValidate = options.validate;
598
+ if (options.validate === void 0) {
599
+ if (Model.settings.validateUpsert === void 0) {
600
+ if (Model.settings.automaticValidation !== void 0) doValidate = Model.settings.automaticValidation;
601
+ } else doValidate = Model.settings.validateUpsert;
602
+ } else doValidate = options.validate;
602
603
  if (this.settings.forceId) {
603
604
  options = Object.create(options);
604
605
  options.validate = !!doValidate;
@@ -638,10 +639,12 @@ var require_dao = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modul
638
639
  Model = Model.lookupModel(update);
639
640
  if (doValidate === false) callConnector();
640
641
  else inst.isValid(function(valid) {
641
- if (!valid) if (doValidate) return cb(new ValidationError(inst), inst);
642
- else {
643
- g.warn("Ignoring validation errors in {{updateOrCreate()}}:");
644
- g.warn(" %s", new ValidationError(inst).message);
642
+ if (!valid) {
643
+ if (doValidate) return cb(new ValidationError(inst), inst);
644
+ else {
645
+ g.warn("Ignoring validation errors in {{updateOrCreate()}}:");
646
+ g.warn(" %s", new ValidationError(inst).message);
647
+ }
645
648
  }
646
649
  callConnector();
647
650
  }, update, options);
@@ -1137,8 +1140,10 @@ var require_dao = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modul
1137
1140
  });
1138
1141
  } else Model.findOne(query, withoutLeanOption(options), function(err, record) {
1139
1142
  if (err) return cb(err);
1140
- if (record) if (cb.promise) return cb(null, [record, false]);
1141
- else return cb(null, record, false);
1143
+ if (record) {
1144
+ if (cb.promise) return cb(null, [record, false]);
1145
+ else return cb(null, record, false);
1146
+ }
1142
1147
  Model.create(data, options, function(err, record) {
1143
1148
  if (cb.promise) cb(err, [record, record != null]);
1144
1149
  else cb(err, record, record != null);
@@ -1448,17 +1453,19 @@ var require_dao = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modul
1448
1453
  } catch (err) {
1449
1454
  return callback(err);
1450
1455
  }
1451
- if (query && query.include) if (query.collect) {
1452
- obj = obj.__cachedRelations[query.collect];
1453
- if (obj === null) obj = void 0;
1454
- } else {
1455
- for (let i = 0; i < includedRelationNames.length; i++) {
1456
- const relationName = includedRelationNames[i];
1457
- let included = obj.__cachedRelations[relationName];
1458
- if (Array.isArray(included)) included = new List(included, null, obj);
1459
- if (included) obj.__data[relationName] = included;
1456
+ if (query && query.include) {
1457
+ if (query.collect) {
1458
+ obj = obj.__cachedRelations[query.collect];
1459
+ if (obj === null) obj = void 0;
1460
+ } else {
1461
+ for (let i = 0; i < includedRelationNames.length; i++) {
1462
+ const relationName = includedRelationNames[i];
1463
+ let included = obj.__cachedRelations[relationName];
1464
+ if (Array.isArray(included)) included = new List(included, null, obj);
1465
+ if (included) obj.__data[relationName] = included;
1466
+ }
1467
+ delete obj.__data.__cachedRelations;
1460
1468
  }
1461
- delete obj.__data.__cachedRelations;
1462
1469
  }
1463
1470
  callback(null, obj);
1464
1471
  }
@@ -1788,8 +1795,10 @@ var require_dao = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modul
1788
1795
  if (isPKMissing(Model, cb)) return cb.promise;
1789
1796
  else if (this.isNewRecord()) return Model.create(this, options, cb);
1790
1797
  const hookState = {};
1791
- if (options.validate === void 0) if (Model.settings.automaticValidation === void 0) options.validate = true;
1792
- else options.validate = Model.settings.automaticValidation;
1798
+ if (options.validate === void 0) {
1799
+ if (Model.settings.automaticValidation === void 0) options.validate = true;
1800
+ else options.validate = Model.settings.automaticValidation;
1801
+ }
1793
1802
  if (options.throws === void 0) options.throws = false;
1794
1803
  const inst = this;
1795
1804
  const connector = inst.getConnector();
@@ -1916,10 +1925,11 @@ var require_dao = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modul
1916
1925
  this.applyScope(query);
1917
1926
  this.applyProperties(data);
1918
1927
  let doValidate = false;
1919
- if (options.validate === void 0) if (Model.settings.validateUpdate === void 0) {
1920
- if (Model.settings.automaticValidation !== void 0) doValidate = Model.settings.automaticValidation;
1921
- } else doValidate = Model.settings.validateUpdate;
1922
- else doValidate = options.validate;
1928
+ if (options.validate === void 0) {
1929
+ if (Model.settings.validateUpdate === void 0) {
1930
+ if (Model.settings.automaticValidation !== void 0) doValidate = Model.settings.automaticValidation;
1931
+ } else doValidate = Model.settings.validateUpdate;
1932
+ } else doValidate = options.validate;
1923
1933
  where = query.where;
1924
1934
  const context = {
1925
1935
  Model,
@@ -402,12 +402,14 @@ var require_datasource = /* @__PURE__ */ require_runtime.__commonJSMin(((exports
402
402
  */
403
403
  DataSource.prototype.setup = function(dsName, settings) {
404
404
  let connector;
405
- if (dsName && typeof dsName === "object") if (settings === void 0) {
406
- settings = dsName;
407
- dsName = void 0;
408
- } else {
409
- connector = dsName;
410
- dsName = void 0;
405
+ if (dsName && typeof dsName === "object") {
406
+ if (settings === void 0) {
407
+ settings = dsName;
408
+ dsName = void 0;
409
+ } else {
410
+ connector = dsName;
411
+ dsName = void 0;
412
+ }
411
413
  }
412
414
  if (typeof dsName !== "string") dsName = void 0;
413
415
  if (typeof settings === "object") {
@@ -1319,9 +1321,10 @@ var require_datasource = /* @__PURE__ */ require_runtime.__commonJSMin(((exports
1319
1321
  else if (typeof options.nameMapper === "function") nameMapper = options.nameMapper;
1320
1322
  else nameMapper = function mapName(type, name) {
1321
1323
  if (type === "table" || type === "model") return fromDBName(name, pascalCase);
1322
- else if (type == "fk") if (disableCamelCase) return fromDBName(name + "Rel");
1323
- else return fromDBName(name + "Rel", camelCase);
1324
- else if (disableCamelCase) return fromDBName(name);
1324
+ else if (type == "fk") {
1325
+ if (disableCamelCase) return fromDBName(name + "Rel");
1326
+ else return fromDBName(name + "Rel", camelCase);
1327
+ } else if (disableCamelCase) return fromDBName(name);
1325
1328
  else return fromDBName(name, camelCase);
1326
1329
  };
1327
1330
  if (this.connector.discoverSchemas) {
@@ -1784,9 +1787,7 @@ var require_datasource = /* @__PURE__ */ require_runtime.__commonJSMin(((exports
1784
1787
  this.connector.defineForeignKey(className, key, foreignClassName, cb);
1785
1788
  break;
1786
1789
  default:
1787
- case 3:
1788
- this.connector.defineForeignKey(className, key, cb);
1789
- break;
1790
+ case 3: this.connector.defineForeignKey(className, key, cb);
1790
1791
  }
1791
1792
  } else this.defineProperty(className, key, fkDef);
1792
1793
  };
package/dist/lib/hooks.js CHANGED
@@ -48,12 +48,13 @@ var require_hooks = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
48
48
  if (beforeHook) deprecateHook(inst.constructor, ["before", "pre"], capitalizedName);
49
49
  if (afterHook) deprecateHook(inst.constructor, ["after", "post"], capitalizedName);
50
50
  }
51
- if (work) if (beforeHook) beforeHook.call(inst, function() {
52
- if (arguments.length) return callback && callback.apply(null, arguments);
53
- work.call(inst, next);
54
- }, data);
55
- else work.call(inst, next);
56
- else next();
51
+ if (work) {
52
+ if (beforeHook) beforeHook.call(inst, function() {
53
+ if (arguments.length) return callback && callback.apply(null, arguments);
54
+ work.call(inst, next);
55
+ }, data);
56
+ else work.call(inst, next);
57
+ } else next();
57
58
  function next(done) {
58
59
  if (afterHook) afterHook.call(inst, done);
59
60
  else if (done) done.call(this);
@@ -709,7 +709,8 @@ var require_include = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, m
709
709
  function targetLinkingTask(next) {
710
710
  eachParallel(targets, linkOneToMany, next);
711
711
  function linkOneToMany(target, next) {
712
- const objList = objTargetIdMap[target[relation.keyTo].toString()];
712
+ const targetId = target[relation.keyTo];
713
+ const objList = objTargetIdMap[targetId.toString()];
713
714
  eachParallel(objList, function(obj, next) {
714
715
  if (!obj) return next();
715
716
  obj.__cachedRelations[relationName] = target;
package/dist/lib/jutil.js CHANGED
@@ -14,7 +14,10 @@ var require_jutil = /* @__PURE__ */ require("../_virtual/_rolldown/runtime.js").
14
14
  override: false
15
15
  };
16
16
  if (options.staticProperties) Object.keys(baseClass).forEach(function(classProp) {
17
- if (classProp !== "super_" && (!newClass.hasOwnProperty(classProp) || options.override)) Object.defineProperty(newClass, classProp, Object.getOwnPropertyDescriptor(baseClass, classProp));
17
+ if (classProp !== "super_" && (!newClass.hasOwnProperty(classProp) || options.override)) {
18
+ const pd = Object.getOwnPropertyDescriptor(baseClass, classProp);
19
+ Object.defineProperty(newClass, classProp, pd);
20
+ }
18
21
  });
19
22
  };
20
23
  /**
@@ -32,7 +32,7 @@ var require_delete_all = /* @__PURE__ */ require_runtime.__commonJSMin(((exports
32
32
  const errMsg = "Connector does not support key-value pair deletion";
33
33
  debug(errMsg);
34
34
  process.nextTick(function() {
35
- const err = new Error(errMsg);
35
+ const err = /* @__PURE__ */ new Error(errMsg);
36
36
  err.statusCode = 501;
37
37
  callback(err);
38
38
  });
@@ -31,7 +31,7 @@ var require_delete = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mo
31
31
  const errMsg = "Connector does not support key-value pair deletion";
32
32
  debug(errMsg);
33
33
  process.nextTick(function() {
34
- const err = new Error(errMsg);
34
+ const err = /* @__PURE__ */ new Error(errMsg);
35
35
  err.statusCode = 501;
36
36
  callback(err);
37
37
  });
@@ -23,11 +23,12 @@ var require_mixins = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mo
23
23
  */
24
24
  MixinProvider.prototype.applyMixin = function applyMixin(modelClass, name, options) {
25
25
  const fn = this.mixins[name];
26
- if (typeof fn === "function") if (modelClass.dataSource) fn(modelClass, options || {});
27
- else modelClass.once("dataSourceAttached", function() {
28
- fn(modelClass, options || {});
29
- });
30
- else {
26
+ if (typeof fn === "function") {
27
+ if (modelClass.dataSource) fn(modelClass, options || {});
28
+ else modelClass.once("dataSourceAttached", function() {
29
+ fn(modelClass, options || {});
30
+ });
31
+ } else {
31
32
  const model = this.modelBuilder.getModel(name);
32
33
  if (model) {
33
34
  debug("Mixin is resolved to a model: %s", name);
@@ -544,13 +544,14 @@ var require_model_builder = /* @__PURE__ */ require_runtime.__commonJSMin(((expo
544
544
  prop = this.define(prop, {}, { unresolved: true });
545
545
  return prop;
546
546
  }
547
- } else if (prop.constructor.name === "Object") if (!isSubProperty && prop.type) return this.resolveType(prop.type, true);
548
- else return this.define(this.getSchemaName(null), prop, {
549
- anonymous: true,
550
- idInjection: false,
551
- strict: this.settings.strictEmbeddedModels || false
552
- });
553
- else if ("function" === typeof prop) return prop;
547
+ } else if (prop.constructor.name === "Object") {
548
+ if (!isSubProperty && prop.type) return this.resolveType(prop.type, true);
549
+ else return this.define(this.getSchemaName(null), prop, {
550
+ anonymous: true,
551
+ idInjection: false,
552
+ strict: this.settings.strictEmbeddedModels || false
553
+ });
554
+ } else if ("function" === typeof prop) return prop;
554
555
  return prop;
555
556
  };
556
557
  /**
@@ -568,12 +569,14 @@ var require_model_builder = /* @__PURE__ */ require_runtime.__commonJSMin(((expo
568
569
  */
569
570
  ModelBuilder.prototype.buildModels = function(schemas, createModel) {
570
571
  const models = {};
571
- if (!Array.isArray(schemas)) if (schemas.properties && schemas.name) schemas = [schemas];
572
- else schemas = [{
573
- name: this.getSchemaName(),
574
- properties: schemas,
575
- options: { anonymous: true }
576
- }];
572
+ if (!Array.isArray(schemas)) {
573
+ if (schemas.properties && schemas.name) schemas = [schemas];
574
+ else schemas = [{
575
+ name: this.getSchemaName(),
576
+ properties: schemas,
577
+ options: { anonymous: true }
578
+ }];
579
+ }
577
580
  let relations = [];
578
581
  for (let s = 0, n = schemas.length; s < n; s++) {
579
582
  const name = this.getSchemaName(schemas[s].name);
@@ -214,8 +214,10 @@ var require_model_definition = /* @__PURE__ */ require_runtime.__commonJSMin(((e
214
214
  if (val === void 0 || val === null) return val;
215
215
  if ("function" === typeof val.toJSON) return val.toJSON();
216
216
  if ("function" === typeof val) {
217
- if (isModelClass(val)) if (val.settings && val.settings.anonymous) return val.definition && val.definition.toJSON().properties;
218
- else return val.modelName;
217
+ if (isModelClass(val)) {
218
+ if (val.settings && val.settings.anonymous) return val.definition && val.definition.toJSON().properties;
219
+ else return val.modelName;
220
+ }
219
221
  return val.name;
220
222
  } else return val;
221
223
  };
@@ -303,7 +303,6 @@ var require_model_utils = /* @__PURE__ */ require_runtime.__commonJSMin(((export
303
303
  val.statusCode = 400;
304
304
  throw val;
305
305
  }
306
- break;
307
306
  }
308
307
  break;
309
308
  }
@@ -316,31 +315,33 @@ var require_model_utils = /* @__PURE__ */ require_runtime.__commonJSMin(((export
316
315
  for (let i = 0; i < val.length; i++) if (val[i] !== null && val[i] !== void 0) {
317
316
  if (!(val[i] instanceof RegExp)) val[i] = isClass(DataType) ? new DataType(val[i]) : DataType(val[i]);
318
317
  }
319
- } else if (val != null) if (operator === null && val instanceof RegExp) operator = "regexp";
320
- else if (operator === "regexp" && val instanceof RegExp) {} else if ((operator === "like" || operator === "nlike" || operator === "ilike" || operator === "nilike") && val instanceof RegExp) {} else if (allowExtendedOperators && typeof val === "object") {} else {
321
- if (!allowExtendedOperators) {
322
- const extendedOperators = Object.keys(val).filter(function(k) {
323
- return k[0] === "$";
324
- });
325
- if (extendedOperators.length) {
326
- const msg = g.f("Operators \"" + extendedOperators.join(", ") + "\" are not allowed in query");
327
- const err = new Error(msg);
328
- err.code = "OPERATOR_NOT_ALLOWED_IN_QUERY";
329
- err.statusCode = 400;
330
- err.details = {
331
- operators: extendedOperators,
332
- where
333
- };
334
- throw err;
318
+ } else if (val != null) {
319
+ if (operator === null && val instanceof RegExp) operator = "regexp";
320
+ else if (operator === "regexp" && val instanceof RegExp) {} else if ((operator === "like" || operator === "nlike" || operator === "ilike" || operator === "nilike") && val instanceof RegExp) {} else if (allowExtendedOperators && typeof val === "object") {} else {
321
+ if (!allowExtendedOperators) {
322
+ const extendedOperators = Object.keys(val).filter(function(k) {
323
+ return k[0] === "$";
324
+ });
325
+ if (extendedOperators.length) {
326
+ const msg = g.f("Operators \"" + extendedOperators.join(", ") + "\" are not allowed in query");
327
+ const err = new Error(msg);
328
+ err.code = "OPERATOR_NOT_ALLOWED_IN_QUERY";
329
+ err.statusCode = 400;
330
+ err.details = {
331
+ operators: extendedOperators,
332
+ where
333
+ };
334
+ throw err;
335
+ }
335
336
  }
337
+ if (isNestedModel(DataType)) {
338
+ if (Array.isArray(DataType) && Array.isArray(val)) {
339
+ if (val === null || val === void 0) continue;
340
+ for (const it of val) self._coerce(it, options, DataType[0].definition);
341
+ } else self._coerce(val, options, DataType.definition);
342
+ continue;
343
+ } else val = isClass(DataType) ? new DataType(val) : DataType(val);
336
344
  }
337
- if (isNestedModel(DataType)) {
338
- if (Array.isArray(DataType) && Array.isArray(val)) {
339
- if (val === null || val === void 0) continue;
340
- for (const it of val) self._coerce(it, options, DataType[0].definition);
341
- } else self._coerce(val, options, DataType.definition);
342
- continue;
343
- } else val = isClass(DataType) ? new DataType(val) : DataType(val);
344
345
  }
345
346
  if (operator && operator !== "eq") {
346
347
  const value = {};
package/dist/lib/model.js CHANGED
@@ -146,16 +146,18 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
146
146
  propVal = data[p];
147
147
  if (typeof propVal === "function") continue;
148
148
  if (propVal === void 0 && persistUndefinedAsNull) propVal = null;
149
- if (properties[p]) if (applySetters || properties[p].id) self[p] = propVal;
150
- else self.__data[p] = propVal;
151
- else if (ctor.relations[p]) {
149
+ if (properties[p]) {
150
+ if (applySetters || properties[p].id) self[p] = propVal;
151
+ else self.__data[p] = propVal;
152
+ } else if (ctor.relations[p]) {
152
153
  const relationType = ctor.relations[p].type;
153
154
  let modelTo;
154
155
  if (!properties[p]) {
155
156
  modelTo = ctor.relations[p].modelTo || ModelBaseClass;
156
157
  const multiple = ctor.relations[p].multiple;
158
+ const typeName = multiple ? "Array" : modelTo.modelName;
157
159
  properties[p] = {
158
- name: multiple ? "Array" : modelTo.modelName,
160
+ name: typeName,
159
161
  type: multiple ? [modelTo] : modelTo
160
162
  };
161
163
  }
@@ -189,9 +191,10 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
189
191
  if (applyDefaultValues && propVal === void 0 && appliesDefaultsOnWrites(properties[p])) {
190
192
  let def = properties[p]["default"];
191
193
  if (def !== void 0) {
192
- if (typeof def === "function") if (def === Date) def = /* @__PURE__ */ new Date();
193
- else def = def();
194
- else if (type.name === "Date" && def === "$now") def = /* @__PURE__ */ new Date();
194
+ if (typeof def === "function") {
195
+ if (def === Date) def = /* @__PURE__ */ new Date();
196
+ else def = def();
197
+ } else if (type.name === "Date" && def === "$now") def = /* @__PURE__ */ new Date();
195
198
  self.__data[p] = propVal = def;
196
199
  }
197
200
  }
@@ -20,6 +20,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
20
20
  const mergeQuery = utils.mergeQuery;
21
21
  const idEquals = utils.idEquals;
22
22
  const idsHaveDuplicates = utils.idsHaveDuplicates;
23
+ const uniq = utils.uniq;
23
24
  const ModelBaseClass = require_lib_model;
24
25
  const applyFilter = require_lib_connectors_memory.applyFilter;
25
26
  const ValidationError = require_lib_validations.ValidationError;
@@ -487,6 +488,10 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
487
488
  * @property {String} as Name of the property in the referring model that corresponds to the foreign key field in the related model.
488
489
  * @property {String} foreignKey Property name of foreign key field.
489
490
  * @property {Object} model Model object
491
+ * @property {Object} options Extra relation options such as `disableInclude`
492
+ * and `countRelated`. When `countRelated` is true on a hasManyThrough
493
+ * relation, `count()` counts existing related target instances instead of
494
+ * through-model rows (orphan through records are excluded).
490
495
  */
491
496
  RelationDefinition.hasMany = function hasMany(modelFrom, modelToRef, params) {
492
497
  const thisClassName = modelFrom.modelName;
@@ -546,6 +551,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
546
551
  scopeMethods.create = scopeMethod(definition, "create");
547
552
  scopeMethods.add = scopeMethod(definition, "add");
548
553
  scopeMethods.remove = scopeMethod(definition, "remove");
554
+ scopeMethods.count = scopeMethod(definition, "count");
549
555
  const addFunc = scopeMethods.add;
550
556
  modelFrom.prototype["__link__" + relationName] = addFunc;
551
557
  const removeFunc = scopeMethods.remove;
@@ -916,6 +922,65 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
916
922
  return cb.promise;
917
923
  };
918
924
  /**
925
+ * Count related instances for a hasManyThrough relation.
926
+ *
927
+ * By default this counts through-model rows, including orphans and duplicate
928
+ * links. Set `options.countRelated` on the relation to count unique existing
929
+ * related target instances instead. The optional `where` is applied to the
930
+ * through model by default, or to the target model when `countRelated` is true.
931
+ *
932
+ * @param {Object} [where]
933
+ * @param {Object} [options]
934
+ * @param {Function} [cb]
935
+ */
936
+ HasManyThrough.prototype.count = function(where, options, cb) {
937
+ if (typeof where === "function") {
938
+ cb = where;
939
+ where = {};
940
+ options = {};
941
+ } else if (typeof options === "function" && cb === void 0) {
942
+ cb = options;
943
+ options = {};
944
+ }
945
+ options = options || {};
946
+ where = where || {};
947
+ const definition = this.definition;
948
+ const modelThrough = definition.modelThrough;
949
+ const pk1 = definition.keyFrom;
950
+ cb = cb || utils.createPromiseCallback();
951
+ if (!definition.options || !definition.options.countRelated) {
952
+ const filter = { where: {} };
953
+ filter.where[definition.keyTo] = this.modelInstance[pk1];
954
+ definition.applyScope(this.modelInstance, filter);
955
+ mergeQuery(filter, { where });
956
+ modelThrough.count(filter.where, options, cb);
957
+ return cb.promise;
958
+ }
959
+ const keys = throughKeys(definition);
960
+ const fk1 = keys[0];
961
+ const fk2 = keys[1];
962
+ const query = {};
963
+ query[fk1] = this.modelInstance[pk1];
964
+ const filter = { where: query };
965
+ definition.applyScope(this.modelInstance, filter);
966
+ const modelTo = definition.modelTo;
967
+ const idName = modelTo.definition.idName();
968
+ modelThrough.find({ where: filter.where }, options, function(err, throughs) {
969
+ if (err) return cb(err);
970
+ const ids = uniq((throughs || []).map(function(row) {
971
+ return row[fk2];
972
+ }).filter(function(id) {
973
+ return id != null;
974
+ }));
975
+ if (ids.length === 0) return cb(null, 0);
976
+ const targetFilter = { where: {} };
977
+ targetFilter.where[idName] = { inq: ids };
978
+ mergeQuery(targetFilter, { where });
979
+ modelTo.count(targetFilter.where, options, cb);
980
+ });
981
+ return cb.promise;
982
+ };
983
+ /**
919
984
  * Remove the target model instance from the 'hasMany' relation
920
985
  * @param {Object|ID) acInst The actual instance or id value
921
986
  */
@@ -1488,28 +1553,29 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
1488
1553
  if (newValue) {
1489
1554
  newValue[fk] = modelInstance[pk];
1490
1555
  self.resetCache(newValue);
1491
- } else if (typeof cb === "function") if (cachedValue === void 0) {
1492
- const query = { where: {} };
1493
- query.where[fk] = modelInstance[pk];
1494
- definition.applyScope(modelInstance, query);
1495
- modelTo.findOne(query, options, function(err, inst) {
1496
- if (err) return cb(err);
1497
- if (!inst) return cb(null, null);
1498
- if (inst[fk] != null && modelInstance[pk] != null && inst[fk].toString() === modelInstance[pk].toString()) {
1499
- self.resetCache(inst);
1500
- cb(null, inst);
1501
- } else {
1502
- err = new Error(g.f("Key mismatch: %s.%s: %s, %s.%s: %s", self.definition.modelFrom.modelName, pk, modelInstance[pk], modelTo.modelName, fk, inst[fk]));
1503
- err.statusCode = 400;
1504
- cb(err);
1505
- }
1506
- });
1507
- return modelInstance[pk];
1508
- } else {
1509
- cb(null, cachedValue);
1510
- return cachedValue;
1511
- }
1512
- else if (condOrRefresh === void 0) return cachedValue;
1556
+ } else if (typeof cb === "function") {
1557
+ if (cachedValue === void 0) {
1558
+ const query = { where: {} };
1559
+ query.where[fk] = modelInstance[pk];
1560
+ definition.applyScope(modelInstance, query);
1561
+ modelTo.findOne(query, options, function(err, inst) {
1562
+ if (err) return cb(err);
1563
+ if (!inst) return cb(null, null);
1564
+ if (inst[fk] != null && modelInstance[pk] != null && inst[fk].toString() === modelInstance[pk].toString()) {
1565
+ self.resetCache(inst);
1566
+ cb(null, inst);
1567
+ } else {
1568
+ err = new Error(g.f("Key mismatch: %s.%s: %s, %s.%s: %s", self.definition.modelFrom.modelName, pk, modelInstance[pk], modelTo.modelName, fk, inst[fk]));
1569
+ err.statusCode = 400;
1570
+ cb(err);
1571
+ }
1572
+ });
1573
+ return modelInstance[pk];
1574
+ } else {
1575
+ cb(null, cachedValue);
1576
+ return cachedValue;
1577
+ }
1578
+ } else if (condOrRefresh === void 0) return cachedValue;
1513
1579
  else {
1514
1580
  newValue[fk] = modelInstance[pk];
1515
1581
  self.resetCache();
@@ -1874,9 +1940,10 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
1874
1940
  if (hasErrors) err(false);
1875
1941
  });
1876
1942
  if (!params.polymorphic) modelFrom.validate(propertyName, function(err) {
1877
- if (idsHaveDuplicates((this[propertyName] || []).map(function(m) {
1943
+ const ids = (this[propertyName] || []).map(function(m) {
1878
1944
  return m[idName] && m[idName].toString();
1879
- }))) {
1945
+ });
1946
+ if (idsHaveDuplicates(ids)) {
1880
1947
  this.errors.add(propertyName, "contains duplicate `" + idName + "`", "uniqueness");
1881
1948
  err(false);
1882
1949
  }
@@ -2351,7 +2418,8 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
2351
2418
  }
2352
2419
  });
2353
2420
  modelFrom.validate(relationName, function(err) {
2354
- if (idsHaveDuplicates(this[fk] || [])) {
2421
+ const ids = this[fk] || [];
2422
+ if (idsHaveDuplicates(ids)) {
2355
2423
  const msg = "contains duplicate `" + modelTo.modelName + "` instance";
2356
2424
  this.errors.add(relationName, msg, "uniqueness");
2357
2425
  err(false);
@@ -3,6 +3,9 @@ const require_runtime = require("../_virtual/_rolldown/runtime.js");
3
3
  const require_lib_relation_definition = require("./relation-definition.js");
4
4
  //#region src/lib/relations.ts
5
5
  var require_relations = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, module) => {
6
+ /*!
7
+ * Dependencies
8
+ */
6
9
  const RelationDefinition = require_lib_relation_definition.RelationDefinition;
7
10
  module.exports = RelationMixin;
8
11
  /**
@@ -68,6 +71,10 @@ var require_relations = /* @__PURE__ */ require_runtime.__commonJSMin(((exports,
68
71
  * @property {Object|Function} scope Explicitly define additional scopes.
69
72
  * @property {Boolean} invert Specify if the relation is inverted.
70
73
  * @property {Object} model The model object.
74
+ * @property {Object} options Extra relation options such as `disableInclude`
75
+ * and `countRelated`. When `countRelated` is true on a hasManyThrough
76
+ * relation, `count()` counts existing related target instances instead of
77
+ * through-model rows (orphan through records are excluded).
71
78
  */
72
79
  RelationMixin.hasMany = function hasMany(modelTo, params) {
73
80
  return RelationDefinition.hasMany(this, modelTo, params);
package/dist/lib/scope.js CHANGED
@@ -95,11 +95,13 @@ var require_scope = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
95
95
  options = {};
96
96
  }
97
97
  options = options || {};
98
- if (condOrRefresh !== void 0) if (typeof condOrRefresh === "boolean") actualRefresh = condOrRefresh;
99
- else {
100
- actualCond = condOrRefresh;
101
- actualRefresh = true;
102
- saveOnCache = false;
98
+ if (condOrRefresh !== void 0) {
99
+ if (typeof condOrRefresh === "boolean") actualRefresh = condOrRefresh;
100
+ else {
101
+ actualCond = condOrRefresh;
102
+ actualRefresh = true;
103
+ saveOnCache = false;
104
+ }
103
105
  }
104
106
  cb = cb || utils.createPromiseCallback();
105
107
  if (!self.__cachedRelations || self.__cachedRelations[name] === void 0 || actualRefresh) {
@@ -189,6 +191,17 @@ var require_scope = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
189
191
  Object.defineProperty(cls, name, {
190
192
  enumerable: false,
191
193
  configurable: true,
194
+ /**
195
+ * This defines a property for the scope. For example, user.accounts or
196
+ * User.vips. Please note the cls can be the model class or prototype of
197
+ * the model class.
198
+ *
199
+ * The property value is function. It can be used to query the scope,
200
+ * such as user.accounts(condOrRefresh, cb) or User.vips(cb). The value
201
+ * can also have child properties for create/build/delete. For example,
202
+ * user.accounts.create(act, cb).
203
+ *
204
+ */
192
205
  get: function() {
193
206
  const targetModel = definition.targetModel(this);
194
207
  const self = this;
@@ -316,7 +329,8 @@ var require_scope = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
316
329
  }
317
330
  options = options || {};
318
331
  const targetModel = definition.targetModel(this._receiver);
319
- const filter = mergeQuery({ where: this._scope && this._scope.where || {} }, { where: where || {} });
332
+ const scoped = this._scope && this._scope.where || {};
333
+ const filter = mergeQuery({ where: scoped }, { where: where || {} });
320
334
  return targetModel.destroyAll(filter.where, options, cb);
321
335
  }
322
336
  function updateAll(where, data, options, cb) {
@@ -331,7 +345,8 @@ var require_scope = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
331
345
  }
332
346
  options = options || {};
333
347
  const targetModel = definition.targetModel(this._receiver);
334
- const filter = mergeQuery({ where: this._scope && this._scope.where || {} }, { where: where || {} });
348
+ const scoped = this._scope && this._scope.where || {};
349
+ const filter = mergeQuery({ where: scoped }, { where: where || {} });
335
350
  return targetModel.updateAll(filter.where, data, options, cb);
336
351
  }
337
352
  function findById(id, filter, options, cb) {
@@ -372,7 +387,8 @@ var require_scope = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
372
387
  }
373
388
  options = options || {};
374
389
  const targetModel = definition.targetModel(this._receiver);
375
- filter = mergeQuery({ where: this._scope && this._scope.where || {} }, filter || {});
390
+ const scoped = this._scope && this._scope.where || {};
391
+ filter = mergeQuery({ where: scoped }, filter || {});
376
392
  return targetModel.findOne(filter, options, cb);
377
393
  }
378
394
  function count(where, options, cb) {
@@ -385,7 +401,8 @@ var require_scope = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
385
401
  }
386
402
  options = options || {};
387
403
  const targetModel = definition.targetModel(this._receiver);
388
- const filter = mergeQuery({ where: this._scope && this._scope.where || {} }, { where: where || {} });
404
+ const scoped = this._scope && this._scope.where || {};
405
+ const filter = mergeQuery({ where: scoped }, { where: where || {} });
389
406
  return targetModel.count(filter.where, options, cb);
390
407
  }
391
408
  return definition;
package/dist/lib/utils.js CHANGED
@@ -43,7 +43,7 @@ var require_utils = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
43
43
  * @type {string}
44
44
  */
45
45
  const PARENT_PROPERTY_NAME = "__parent";
46
- const REGEXP_OPERATORS = new Set([
46
+ const REGEXP_OPERATORS = /* @__PURE__ */ new Set([
47
47
  "like",
48
48
  "nlike",
49
49
  "ilike",
@@ -147,14 +147,18 @@ var require_utils = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
147
147
  if (!update) return;
148
148
  spec = spec || {};
149
149
  base = base || {};
150
- if (update.where && Object.keys(update.where).length > 0) if (base.where && Object.keys(base.where).length > 0) base.where = { and: [base.where, update.where] };
151
- else base.where = update.where;
152
- if (spec.include !== false && update.include) if (!base.include) base.include = update.include;
153
- else if (spec.nestedInclude === true) {
154
- const saved = base.include;
155
- base.include = {};
156
- base.include[update.include] = saved;
157
- } else base.include = mergeIncludes(base.include, update.include);
150
+ if (update.where && Object.keys(update.where).length > 0) {
151
+ if (base.where && Object.keys(base.where).length > 0) base.where = { and: [base.where, update.where] };
152
+ else base.where = update.where;
153
+ }
154
+ if (spec.include !== false && update.include) {
155
+ if (!base.include) base.include = update.include;
156
+ else if (spec.nestedInclude === true) {
157
+ const saved = base.include;
158
+ base.include = {};
159
+ base.include[update.include] = saved;
160
+ } else base.include = mergeIncludes(base.include, update.include);
161
+ }
158
162
  if (spec.collect !== false && update.collect) base.collect = update.collect;
159
163
  if (spec.fields !== false && update.fields !== void 0) base.fields = update.fields;
160
164
  else if (update.fields !== void 0) base.fields = [].concat(base.fields).concat(update.fields);
@@ -607,11 +611,12 @@ var require_utils = /* @__PURE__ */ require_runtime.__commonJSMin(((exports) =>
607
611
  const uniqueIds = /* @__PURE__ */ new Set();
608
612
  for (i = 0; i < ids.length; ++i) {
609
613
  const idType = typeof ids[i];
610
- if (idType === "string" || idType === "number") if (uniqueIds.has(ids[i])) {
611
- hasDuplicates = true;
612
- break;
613
- } else uniqueIds.add(ids[i]);
614
- else break;
614
+ if (idType === "string" || idType === "number") {
615
+ if (uniqueIds.has(ids[i])) {
616
+ hasDuplicates = true;
617
+ break;
618
+ } else uniqueIds.add(ids[i]);
619
+ } else break;
615
620
  }
616
621
  if (hasDuplicates === void 0 && uniqueIds.size === ids.length) hasDuplicates = false;
617
622
  }
@@ -600,13 +600,15 @@ var require_validations = /* @__PURE__ */ require_runtime.__commonJSMin(((export
600
600
  if (typeof conf[kind] === "function") {
601
601
  doValidate = conf[kind].call(inst);
602
602
  if (kind === "unless") doValidate = !doValidate;
603
- } else if (typeof conf[kind] === "string") if (typeof inst[conf[kind]] === "function") {
604
- doValidate = inst[conf[kind]].call(inst);
605
- if (kind === "unless") doValidate = !doValidate;
606
- } else if (inst.__data.hasOwnProperty(conf[kind])) {
607
- doValidate = inst[conf[kind]];
608
- if (kind === "unless") doValidate = !doValidate;
609
- } else doValidate = kind === "if";
603
+ } else if (typeof conf[kind] === "string") {
604
+ if (typeof inst[conf[kind]] === "function") {
605
+ doValidate = inst[conf[kind]].call(inst);
606
+ if (kind === "unless") doValidate = !doValidate;
607
+ } else if (inst.__data.hasOwnProperty(conf[kind])) {
608
+ doValidate = inst[conf[kind]];
609
+ if (kind === "unless") doValidate = !doValidate;
610
+ } else doValidate = kind === "if";
611
+ }
610
612
  return !doValidate;
611
613
  }
612
614
  const defaultMessages = {
package/dist/package.js CHANGED
@@ -2,7 +2,7 @@
2
2
  var require_package = /* @__PURE__ */ require("./_virtual/_rolldown/runtime.js").__commonJSMin(((exports, module) => {
3
3
  module.exports = {
4
4
  "name": "@vsaas/loopback-datasource-juggler",
5
- "version": "12.1.1",
5
+ "version": "12.2.0",
6
6
  "description": "Fork of loopback-datasource-juggler for LoopBack 3 style applications",
7
7
  "keywords": [
8
8
  "Connector",
@@ -41,6 +41,7 @@ var require_package = /* @__PURE__ */ require("./_virtual/_rolldown/runtime.js")
41
41
  "default": "./dist/lib/browser.depd.js"
42
42
  },
43
43
  "./*": {
44
+ "types": "./types/*.d.ts",
44
45
  "require": "./dist/lib/*.js",
45
46
  "default": "./dist/lib/*.js"
46
47
  },
@@ -66,7 +67,7 @@ var require_package = /* @__PURE__ */ require("./_virtual/_rolldown/runtime.js")
66
67
  "debug": "catalog:",
67
68
  "depd": "^2.0.0",
68
69
  "inflection": "^3.0.2",
69
- "minimatch": "10.2.4",
70
+ "minimatch": "^10.2.6",
70
71
  "neotraverse": "^0.6.18",
71
72
  "qs": "catalog:"
72
73
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vsaas/loopback-datasource-juggler",
3
- "version": "12.1.1",
3
+ "version": "12.2.0",
4
4
  "description": "Fork of loopback-datasource-juggler for LoopBack 3 style applications",
5
5
  "keywords": [
6
6
  "Connector",
@@ -41,6 +41,7 @@
41
41
  "default": "./dist/lib/browser.depd.js"
42
42
  },
43
43
  "./*": {
44
+ "types": "./types/*.d.ts",
44
45
  "require": "./dist/lib/*.js",
45
46
  "default": "./dist/lib/*.js"
46
47
  },
@@ -54,20 +55,20 @@
54
55
  "debug": "4.4.3",
55
56
  "depd": "^2.0.0",
56
57
  "inflection": "^3.0.2",
57
- "minimatch": "10.2.4",
58
+ "minimatch": "^10.2.6",
58
59
  "neotraverse": "^0.6.18",
59
- "qs": "^6.15.2",
60
- "@vsaas/loopback-connector": "^12.0.0"
60
+ "qs": "^6.15.3",
61
+ "@vsaas/loopback-connector": "^12.0.1"
61
62
  },
62
63
  "devDependencies": {
63
64
  "@types/node": "25.5.0",
64
65
  "bson": "^4.7.2",
65
- "oxfmt": "0.42.0",
66
- "oxlint": "1.57.0",
66
+ "oxfmt": "0.64.0",
67
+ "oxlint": "1.79.0",
67
68
  "should": "13.2.3",
68
- "tsdown": "0.21.7",
69
+ "tsdown": "0.22.14",
69
70
  "typescript": "6.0.2",
70
- "vitest": "4.1.4",
71
+ "vitest": "4.1.11",
71
72
  "loopback-connector-throwing": "1.0.0"
72
73
  },
73
74
  "engines": {
@@ -137,6 +137,8 @@ export declare class HasManyThrough<
137
137
  exists(acInst: any, options?: Options, callback?: Callback<boolean>): PromiseOrVoid<boolean>;
138
138
 
139
139
  remove(acInst: any, options?: Options, callback?: Callback<boolean>): PromiseOrVoid<boolean>;
140
+
141
+ count(where?: Where, options?: Options, callback?: Callback<number>): PromiseOrVoid<number>;
140
142
  }
141
143
 
142
144
  export declare class HasOne<