@vsaas/loopback-datasource-juggler 12.1.2 → 13.0.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.
package/dist/lib/dao.js CHANGED
@@ -1059,6 +1059,7 @@ var require_dao = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modul
1059
1059
  fields: query.fields,
1060
1060
  applySetters: false,
1061
1061
  persisted: true,
1062
+ hydrateNestedModels: true,
1062
1063
  applyDefaultValues: false
1063
1064
  };
1064
1065
  obj = new Model(data, ctorOpts);
@@ -1445,6 +1446,7 @@ var require_dao = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modul
1445
1446
  fields: query.fields,
1446
1447
  applySetters: false,
1447
1448
  persisted: true,
1449
+ hydrateNestedModels: true,
1448
1450
  applyDefaultValues: false
1449
1451
  };
1450
1452
  let obj;
package/dist/lib/list.js CHANGED
@@ -10,8 +10,8 @@ var require_list = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modu
10
10
  const Any = require_lib_types.Types.Any;
11
11
  const { applyParentProperty } = require_lib_utils;
12
12
  module.exports = List;
13
- function List(items, itemType, parent) {
14
- if (!(this instanceof List)) return new List(items, itemType, parent);
13
+ function List(items, itemType, parent, itemOptions) {
14
+ if (!(this instanceof List)) return new List(items, itemType, parent, itemOptions);
15
15
  if (typeof items === "string") try {
16
16
  items = JSON.parse(items);
17
17
  } catch {
@@ -42,7 +42,7 @@ var require_list = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modu
42
42
  value: parent
43
43
  });
44
44
  items.forEach(function(item, i) {
45
- if (itemType && !(item instanceof itemType)) arr[i] = arr.toItem(item);
45
+ if (itemType && !(item instanceof itemType)) arr[i] = arr.toItem(item, itemOptions);
46
46
  else arr[i] = item;
47
47
  if (parent && arr[i] && typeof arr[i] === "object") applyParentProperty(arr[i], parent);
48
48
  });
@@ -50,8 +50,9 @@ var require_list = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modu
50
50
  }
51
51
  util.inherits(List, Array);
52
52
  const _push = List.prototype.push;
53
- List.prototype.toItem = function(item) {
54
- if (isClass(this.itemType)) return new this.itemType(item);
53
+ List.prototype.toItem = function(item, options) {
54
+ if (options && isModelConstructor(this.itemType)) return new this.itemType(item, options);
55
+ else if (isClass(this.itemType)) return new this.itemType(item);
55
56
  else if (Array.isArray(item)) return item;
56
57
  else if (this.itemType === Date) {
57
58
  if (item === null) return null;
@@ -96,6 +97,9 @@ var require_list = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, modu
96
97
  function isClass(fn) {
97
98
  return fn && fn.toString().indexOf("class ") === 0;
98
99
  }
100
+ function isModelConstructor(fn) {
101
+ return fn && fn.prototype && typeof fn.prototype._initProperties === "function";
102
+ }
99
103
  }));
100
104
  //#endregion
101
105
  module.exports = require_list();
@@ -4,6 +4,7 @@ const require_lib_globalize = require("./globalize.js");
4
4
  const require_lib_types = require("./types.js");
5
5
  const require_lib_utils = require("./utils.js");
6
6
  const require_lib_list = require("./list.js");
7
+ const require_lib_model_internals = require("./model-internals.js");
7
8
  const require_lib_model = require("./model.js");
8
9
  const require_lib_model_definition = require("./model-definition.js");
9
10
  const require_lib_mixins = require("./mixins.js");
@@ -23,6 +24,7 @@ var require_model_builder = /* @__PURE__ */ require_runtime.__commonJSMin(((expo
23
24
  const List = require_lib_list;
24
25
  const ModelDefinition = require_lib_model_definition;
25
26
  const MixinProvider = require_lib_mixins;
27
+ const { getNestedModelOptions, skipsCustomSetters } = require_lib_model_internals;
26
28
  const { deepMerge, deepMergeProperty, rankArrayElements, isClass, applyParentProperty } = require_lib_utils;
27
29
  require_lib_types(ModelBuilder);
28
30
  const introspect = require_lib_introspection(ModelBuilder);
@@ -320,6 +322,25 @@ var require_model_builder = /* @__PURE__ */ require_runtime.__commonJSMin(((expo
320
322
  ModelClass.validatesPresenceOf(propertyName, requiredOptions);
321
323
  }
322
324
  if (DataType === Date) ModelClass.validatesDateOf(propertyName);
325
+ let classCheckType;
326
+ let classCheckResult;
327
+ const isClassType = function(type) {
328
+ if (type !== classCheckType) {
329
+ classCheckResult = isClass(type);
330
+ classCheckType = type;
331
+ }
332
+ return classCheckResult;
333
+ };
334
+ let modelCheckType;
335
+ let modelCheckResult;
336
+ const holdsModelType = function(type) {
337
+ const itemType = Array.isArray(type) ? type[0] : type;
338
+ if (itemType !== modelCheckType) {
339
+ modelCheckResult = isModelClass(itemType);
340
+ modelCheckType = itemType;
341
+ }
342
+ return modelCheckResult;
343
+ };
323
344
  Object.defineProperty(ModelClass.prototype, propertyName, {
324
345
  get: function() {
325
346
  if (ModelClass.getter[propertyName]) return ModelClass.getter[propertyName].call(this);
@@ -333,14 +354,19 @@ var require_model_builder = /* @__PURE__ */ require_runtime.__commonJSMin(((expo
333
354
  else if (typeof DataType === "string") DataType = modelBuilder.resolveType(DataType);
334
355
  const persistUndefinedAsNull = ModelClass.definition.settings.persistUndefinedAsNull;
335
356
  if (value === void 0 && persistUndefinedAsNull) value = null;
336
- if (ModelClass.setter[propertyName]) ModelClass.setter[propertyName].call(this, value);
357
+ if (ModelClass.setter[propertyName] && !skipsCustomSetters(this)) ModelClass.setter[propertyName].call(this, value);
337
358
  else {
338
359
  this.__data = this.__data || {};
339
360
  if (value === null || value === void 0) this.__data[propertyName] = value;
340
- else if (DataType === List) this.__data[propertyName] = isClass(DataType) ? new DataType(value, properties[propertyName].type, this) : DataType(value, properties[propertyName].type, this);
341
361
  else {
342
- this.__data[propertyName] = value instanceof DataType ? value : isClass(DataType) ? new DataType(value) : DataType(value);
343
- if (value && this.__data[propertyName] instanceof DefaultModelBaseClass) applyParentProperty(this.__data[propertyName], this);
362
+ const propertyType = properties[propertyName].type;
363
+ const nestedModelOptions = getNestedModelOptions(this);
364
+ const modelOptions = nestedModelOptions && holdsModelType(propertyType) ? nestedModelOptions : void 0;
365
+ if (DataType === List) this.__data[propertyName] = isClassType(DataType) ? new DataType(value, propertyType, this, modelOptions) : DataType(value, propertyType, this, modelOptions);
366
+ else {
367
+ this.__data[propertyName] = value instanceof DataType ? value : modelOptions ? isClassType(DataType) ? new DataType(value, modelOptions) : DataType(value, modelOptions) : isClassType(DataType) ? new DataType(value) : DataType(value);
368
+ if (value && this.__data[propertyName] instanceof DefaultModelBaseClass) applyParentProperty(this.__data[propertyName], this);
369
+ }
344
370
  }
345
371
  }
346
372
  },
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ //#region src/lib/model-internals.ts
3
+ var require_model_internals = /* @__PURE__ */ require("../_virtual/_rolldown/runtime.js").__commonJSMin(((exports, module) => {
4
+ const outerFrames = [];
5
+ let activeInstance;
6
+ let activeSkipCustomSetters = false;
7
+ let activeNestedModelOptions;
8
+ function enterModelState(instance, skipCustomSetters, nestedModelOptions) {
9
+ outerFrames.push(activeInstance, activeSkipCustomSetters, activeNestedModelOptions);
10
+ activeInstance = instance;
11
+ activeSkipCustomSetters = skipCustomSetters;
12
+ activeNestedModelOptions = nestedModelOptions;
13
+ }
14
+ function exitModelState() {
15
+ activeNestedModelOptions = outerFrames.pop();
16
+ activeSkipCustomSetters = outerFrames.pop();
17
+ activeInstance = outerFrames.pop();
18
+ }
19
+ function findOuterFrame(instance) {
20
+ for (let i = outerFrames.length - 3; i >= 0; i -= 3) if (outerFrames[i] === instance) return i;
21
+ return -1;
22
+ }
23
+ function skipsCustomSetters(instance) {
24
+ if (instance === activeInstance) return activeSkipCustomSetters;
25
+ const frame = findOuterFrame(instance);
26
+ return frame !== -1 && outerFrames[frame + 1];
27
+ }
28
+ function getNestedModelOptions(instance) {
29
+ if (instance === activeInstance) return activeNestedModelOptions;
30
+ const frame = findOuterFrame(instance);
31
+ return frame === -1 ? void 0 : outerFrames[frame + 2];
32
+ }
33
+ module.exports = {
34
+ enterModelState,
35
+ exitModelState,
36
+ skipsCustomSetters,
37
+ getNestedModelOptions
38
+ };
39
+ }));
40
+ //#endregion
41
+ module.exports = require_model_internals();
package/dist/lib/model.js CHANGED
@@ -8,6 +8,7 @@ const require_lib_observer = require("./observer.js");
8
8
  const require_lib_hooks = require("./hooks.js");
9
9
  const require_lib_validations = require("./validations.js");
10
10
  const require_lib_id_utils = require("./id-utils.js");
11
+ const require_lib_model_internals = require("./model-internals.js");
11
12
  //#region src/lib/model.ts
12
13
  var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, module) => {
13
14
  /*!
@@ -28,6 +29,8 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
28
29
  const utils = require_lib_utils;
29
30
  const fieldsToArray = utils.fieldsToArray;
30
31
  const { uuidV1, uuidV4, nanoid } = require_lib_id_utils;
32
+ const { enterModelState, exitModelState } = require_lib_model_internals;
33
+ const nestedModelOptionsMarker = Symbol("nestedModelOptions");
31
34
  const BASE_TYPES = {
32
35
  String: true,
33
36
  Boolean: true,
@@ -69,10 +72,10 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
69
72
  * @property {Boolean} applyDefaultValues Default attributes and values will be applied
70
73
  * @property {Boolean} strict Set the instance level strict mode
71
74
  * @property {Boolean} persisted Whether the instance has been persisted
75
+ * @property {Boolean} hydrateNestedModels Internal read-hydration context
72
76
  * @private
73
77
  */
74
78
  ModelBaseClass.prototype._initProperties = function(data, options) {
75
- const self = this;
76
79
  const ctor = this.constructor;
77
80
  if (typeof data !== "undefined" && data !== null && data.constructor && typeof data.constructor !== "function") throw new Error(g.f("Property name \"{{constructor}}\" is not allowed in %s data", ctor.modelName));
78
81
  if (data instanceof ctor) data = data.toObject(false);
@@ -80,12 +83,10 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
80
83
  data = data || {};
81
84
  if (typeof ctor.applyProperties === "function") ctor.applyProperties(data);
82
85
  options = options || {};
83
- const applySetters = options.applySetters;
84
- const applyDefaultValues = options.applyDefaultValues;
86
+ const nestedModelOptions = options.hydrateNestedModels ? getNestedModelOptions(options) : void 0;
85
87
  let strict = options.strict;
86
88
  if (strict === void 0) strict = ctor.definition.settings.strict;
87
89
  else if (strict === "throw") g.warn("Warning: Model %s, {{strict mode: `throw`}} has been removed, please use {{`strict: true`}} instead, which returns{{`Validation Error`}} for unknown properties,", ctor.modelName);
88
- const persistUndefinedAsNull = ctor.definition.settings.persistUndefinedAsNull;
89
90
  if (ctor.hideInternalProperties) {
90
91
  Object.defineProperties(this, {
91
92
  __cachedRelations: {
@@ -133,8 +134,33 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
133
134
  this.__persisted = false;
134
135
  if (strict) this.__unknownProperties = [];
135
136
  }
136
- if (options.persisted !== void 0) this.__persisted = options.persisted === true;
137
- if (data.__cachedRelations) this.__cachedRelations = data.__cachedRelations;
137
+ enterModelState(this, options.applySetters === "coerce", nestedModelOptions);
138
+ try {
139
+ initPropertyValues(this, data, options, properties, strict, nestedModelOptions);
140
+ } finally {
141
+ exitModelState();
142
+ }
143
+ this.trigger("initialize");
144
+ };
145
+ function getNestedModelOptions(options) {
146
+ if (options[nestedModelOptionsMarker] === true) return options;
147
+ const nestedModelOptions = {
148
+ applySetters: "coerce",
149
+ applyDefaultValues: false,
150
+ persisted: options.persisted,
151
+ hydrateNestedModels: true
152
+ };
153
+ Object.defineProperty(nestedModelOptions, nestedModelOptionsMarker, { value: true });
154
+ return nestedModelOptions;
155
+ }
156
+ function initPropertyValues(self, data, options, properties, strict, nestedModelOptions) {
157
+ const ctor = self.constructor;
158
+ const applySetters = options.applySetters;
159
+ const applyDefaultValues = options.applyDefaultValues;
160
+ const applySettersOrCoercion = applySetters === true || applySetters === "coerce";
161
+ const persistUndefinedAsNull = ctor.definition.settings.persistUndefinedAsNull;
162
+ if (options.persisted !== void 0) self.__persisted = options.persisted === true;
163
+ if (data.__cachedRelations) self.__cachedRelations = data.__cachedRelations;
138
164
  let keys = Object.keys(data);
139
165
  if (Array.isArray(options.fields)) keys = keys.filter(function(k) {
140
166
  return isSelectedField(options.fields, k);
@@ -147,7 +173,7 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
147
173
  if (typeof propVal === "function") continue;
148
174
  if (propVal === void 0 && persistUndefinedAsNull) propVal = null;
149
175
  if (properties[p]) {
150
- if (applySetters || properties[p].id) self[p] = propVal;
176
+ if (applySettersOrCoercion || properties[p].id) self[p] = propVal;
151
177
  else self.__data[p] = propVal;
152
178
  } else if (ctor.relations[p]) {
153
179
  const relationType = ctor.relations[p].type;
@@ -166,18 +192,19 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
166
192
  if (ctor.relations[p].options.embedsProperties) {
167
193
  const fields = fieldsToArray(ctor.relations[p].properties, modelTo.definition.properties, modelTo.settings.strict);
168
194
  if (!~fields.indexOf(ctor.relations[p].keyTo)) fields.push(ctor.relations[p].keyTo);
169
- self.__data[p] = new modelTo(propVal, {
195
+ const embeddedOptions = nestedModelOptions ? Object.assign({}, nestedModelOptions, { fields }) : {
170
196
  fields,
171
197
  applySetters: false,
172
198
  persisted: options.persisted
173
- });
199
+ };
200
+ self.__data[p] = new modelTo(propVal, embeddedOptions);
174
201
  }
175
202
  }
176
203
  self.__cachedRelations[p] = propVal;
177
204
  } else if (strict === false || self.__cachedRelations[p]) {
178
205
  self[p] = self.__data[p] = propVal !== void 0 ? propVal : self.__cachedRelations[p];
179
- if (/\./.test(p)) throw new Error(g.f("Property names containing dot(s) are not supported. Model: %s, dynamic property: %s", this.constructor.modelName, p));
180
- } else if (strict !== "filter") this.__unknownProperties.push(p);
206
+ if (/\./.test(p)) throw new Error(g.f("Property names containing dot(s) are not supported. Model: %s, dynamic property: %s", self.constructor.modelName, p));
207
+ } else if (strict !== "filter") self.__unknownProperties.push(p);
181
208
  }
182
209
  keys = Object.keys(properties);
183
210
  if (Array.isArray(options.fields)) keys = keys.filter(function(k) {
@@ -186,60 +213,27 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
186
213
  size = keys.length;
187
214
  for (let k = 0; k < size; k++) {
188
215
  p = keys[k];
189
- propVal = self.__data[p];
190
216
  const type = properties[p].type;
191
- if (applyDefaultValues && propVal === void 0 && appliesDefaultsOnWrites(properties[p])) {
192
- let def = properties[p]["default"];
193
- if (def !== void 0) {
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();
198
- self.__data[p] = propVal = def;
199
- }
200
- }
201
- if (ignoresMatchedDefault(properties[p]) && properties[p].default === propVal) delete self.__data[p];
202
- if (applyDefaultValues && propVal === void 0) {
203
- const defn = properties[p].defaultFn;
204
- switch (defn) {
205
- case void 0: break;
206
- case "guid":
207
- case "uuid":
208
- propVal = uuidV1();
209
- break;
210
- case "uuidv4":
211
- propVal = uuidV4();
212
- break;
213
- case "now":
214
- propVal = /* @__PURE__ */ new Date();
215
- break;
216
- case "shortid":
217
- case "nanoid":
218
- propVal = nanoid(9);
219
- break;
220
- default: g.warn("Unknown default value provider %s", defn);
221
- }
222
- if (propVal !== void 0) self.__data[p] = propVal;
223
- }
217
+ propVal = applyDefaultValue(self, p, properties[p], applyDefaultValues);
224
218
  if (propVal === void 0 && persistUndefinedAsNull) self.__data[p] = propVal = null;
225
- if (!BASE_TYPES[type.name]) {
226
- if (typeof self.__data[p] !== "object" && self.__data[p]) try {
227
- self.__data[p] = JSON.parse(self.__data[p] + "");
228
- } catch {
229
- self.__data[p] = String(self.__data[p]);
230
- }
231
- if (type.prototype instanceof ModelBaseClass) {
232
- if (!(self.__data[p] instanceof type) && typeof self.__data[p] === "object" && self.__data[p] !== null) {
233
- self.__data[p] = new type(self.__data[p]);
234
- utils.applyParentProperty(self.__data[p], this);
235
- }
236
- } else if (type.name === "Array" || Array.isArray(type)) {
237
- if (!(self.__data[p] instanceof List) && self.__data[p] !== void 0 && self.__data[p] !== null) self.__data[p] = List(self.__data[p], type, self);
238
- }
239
- }
219
+ coercePropertyValue(self, p, type, nestedModelOptions);
240
220
  }
241
- this.trigger("initialize");
242
- };
221
+ }
222
+ /**
223
+ * Apply current write defaults to an existing instance without rebuilding it.
224
+ * This is used when a read-hydrated historical child is written after its
225
+ * model definition gained a defaulted property.
226
+ */
227
+ function applyDefaultValuesToInstance(instance) {
228
+ const properties = instance.constructor.definition.properties;
229
+ for (const propertyName of Object.keys(properties)) {
230
+ const property = properties[propertyName];
231
+ const wasMissing = instance.__data[propertyName] === void 0;
232
+ const propVal = applyDefaultValue(instance, propertyName, property, true);
233
+ if (wasMissing && propVal !== void 0) coercePropertyValue(instance, propertyName, property.type);
234
+ }
235
+ }
236
+ Object.defineProperty(ModelBaseClass, "_applyDefaultValuesToInstance", { value: applyDefaultValuesToInstance });
243
237
  function ignoresMatchedDefault(property) {
244
238
  if (property && property.persistDefaultValues === false) return true;
245
239
  }
@@ -247,6 +241,59 @@ var require_model = /* @__PURE__ */ require_runtime.__commonJSMin(((exports, mod
247
241
  if (property && "applyDefaultOnWrites" in property) return property.applyDefaultOnWrites;
248
242
  return true;
249
243
  }
244
+ function applyDefaultValue(instance, propertyName, property, applyDefaultValues) {
245
+ let propVal = instance.__data[propertyName];
246
+ if (applyDefaultValues && propVal === void 0 && appliesDefaultsOnWrites(property)) {
247
+ let def = property.default;
248
+ if (def !== void 0) {
249
+ if (typeof def === "function") {
250
+ if (def === Date) def = /* @__PURE__ */ new Date();
251
+ else def = def();
252
+ } else if (property.type.name === "Date" && def === "$now") def = /* @__PURE__ */ new Date();
253
+ instance.__data[propertyName] = propVal = def;
254
+ }
255
+ }
256
+ if (ignoresMatchedDefault(property) && property.default === propVal) delete instance.__data[propertyName];
257
+ if (applyDefaultValues && propVal === void 0) {
258
+ switch (property.defaultFn) {
259
+ case void 0: break;
260
+ case "guid":
261
+ case "uuid":
262
+ propVal = uuidV1();
263
+ break;
264
+ case "uuidv4":
265
+ propVal = uuidV4();
266
+ break;
267
+ case "now":
268
+ propVal = /* @__PURE__ */ new Date();
269
+ break;
270
+ case "shortid":
271
+ case "nanoid":
272
+ propVal = nanoid(9);
273
+ break;
274
+ default: g.warn("Unknown default value provider %s", property.defaultFn);
275
+ }
276
+ if (propVal !== void 0) instance.__data[propertyName] = propVal;
277
+ }
278
+ return propVal;
279
+ }
280
+ function coercePropertyValue(instance, propertyName, type, nestedModelOptions) {
281
+ if (!BASE_TYPES[type.name]) {
282
+ if (typeof instance.__data[propertyName] !== "object" && instance.__data[propertyName]) try {
283
+ instance.__data[propertyName] = JSON.parse(instance.__data[propertyName] + "");
284
+ } catch {
285
+ instance.__data[propertyName] = String(instance.__data[propertyName]);
286
+ }
287
+ if (type.prototype instanceof ModelBaseClass) {
288
+ if (!(instance.__data[propertyName] instanceof type) && typeof instance.__data[propertyName] === "object" && instance.__data[propertyName] !== null) {
289
+ instance.__data[propertyName] = nestedModelOptions ? new type(instance.__data[propertyName], nestedModelOptions) : new type(instance.__data[propertyName]);
290
+ utils.applyParentProperty(instance.__data[propertyName], instance);
291
+ }
292
+ } else if (type.name === "Array" || Array.isArray(type)) {
293
+ if (!(instance.__data[propertyName] instanceof List) && instance.__data[propertyName] !== void 0 && instance.__data[propertyName] !== null) instance.__data[propertyName] = List(instance.__data[propertyName], type, instance, nestedModelOptions);
294
+ }
295
+ }
296
+ }
250
297
  /**
251
298
  * Define a property on the model.
252
299
  * @param {String} prop Property name
@@ -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;
@@ -402,6 +403,57 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
402
403
  Relation.apply(this, arguments);
403
404
  }
404
405
  util.inherits(ReferencesMany, Relation);
406
+ function applyWriteDefaults(modelInstance) {
407
+ if (modelInstance && typeof ModelBaseClass._applyDefaultValuesToInstance === "function") ModelBaseClass._applyDefaultValuesToInstance(modelInstance);
408
+ }
409
+ function applyWriteDefaultsToEmbeddedGraph(modelInstance, primaryRelation) {
410
+ if (primaryRelation) {
411
+ if (!(hasOtherEmbeddedRelation(modelInstance.constructor, primaryRelation) || hasOtherEmbeddedRelation(primaryRelation.modelTo))) {
412
+ applyWriteDefaultsToEmbeddedValue(modelInstance[primaryRelation.keyFrom], primaryRelation.multiple);
413
+ return;
414
+ }
415
+ }
416
+ const visited = /* @__PURE__ */ new Set();
417
+ const relationCache = /* @__PURE__ */ new Map();
418
+ visited.add(modelInstance);
419
+ applyWriteDefaultsToEmbeddedRelations(modelInstance, visited, relationCache);
420
+ }
421
+ function hasOtherEmbeddedRelation(modelClass, excludedRelation) {
422
+ const relations = modelClass && modelClass.relations;
423
+ if (!relations) return false;
424
+ return Object.keys(relations).some(function(relationName) {
425
+ const relation = relations[relationName];
426
+ return relation && relation.embed === true && relation !== excludedRelation;
427
+ });
428
+ }
429
+ function applyWriteDefaultsToEmbeddedModel(modelInstance, visited, relationCache) {
430
+ if (!modelInstance || visited.has(modelInstance)) return;
431
+ visited.add(modelInstance);
432
+ applyWriteDefaults(modelInstance);
433
+ applyWriteDefaultsToEmbeddedRelations(modelInstance, visited, relationCache);
434
+ }
435
+ function applyWriteDefaultsToEmbeddedRelations(modelInstance, visited, relationCache) {
436
+ getEmbeddedRelations(modelInstance.constructor, relationCache).forEach(function(relation) {
437
+ applyWriteDefaultsToEmbeddedValue(modelInstance[relation.keyFrom], relation.multiple, visited, relationCache);
438
+ });
439
+ }
440
+ function applyWriteDefaultsToEmbeddedValue(embeddedValue, multiple, visited, relationCache) {
441
+ if (!embeddedValue) return;
442
+ if (multiple) embeddedValue.forEach(function(embeddedInstance) {
443
+ if (visited) applyWriteDefaultsToEmbeddedModel(embeddedInstance, visited, relationCache);
444
+ else applyWriteDefaults(embeddedInstance);
445
+ });
446
+ else if (visited) applyWriteDefaultsToEmbeddedModel(embeddedValue, visited, relationCache);
447
+ else applyWriteDefaults(embeddedValue);
448
+ }
449
+ function getEmbeddedRelations(modelClass, relationCache) {
450
+ let embeddedRelations = relationCache.get(modelClass);
451
+ if (embeddedRelations !== void 0) return embeddedRelations;
452
+ const relations = modelClass && modelClass.relations;
453
+ embeddedRelations = relations ? Object.keys(relations).map((relationName) => relations[relationName]).filter((relation) => relation && relation.embed === true) : [];
454
+ relationCache.set(modelClass, embeddedRelations);
455
+ return embeddedRelations;
456
+ }
405
457
  /*!
406
458
  * Find the relation by foreign key
407
459
  * @param {*} foreignKey The foreign key
@@ -487,6 +539,10 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
487
539
  * @property {String} as Name of the property in the referring model that corresponds to the foreign key field in the related model.
488
540
  * @property {String} foreignKey Property name of foreign key field.
489
541
  * @property {Object} model Model object
542
+ * @property {Object} options Extra relation options such as `disableInclude`
543
+ * and `countRelated`. When `countRelated` is true on a hasManyThrough
544
+ * relation, `count()` counts existing related target instances instead of
545
+ * through-model rows (orphan through records are excluded).
490
546
  */
491
547
  RelationDefinition.hasMany = function hasMany(modelFrom, modelToRef, params) {
492
548
  const thisClassName = modelFrom.modelName;
@@ -546,6 +602,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
546
602
  scopeMethods.create = scopeMethod(definition, "create");
547
603
  scopeMethods.add = scopeMethod(definition, "add");
548
604
  scopeMethods.remove = scopeMethod(definition, "remove");
605
+ scopeMethods.count = scopeMethod(definition, "count");
549
606
  const addFunc = scopeMethods.add;
550
607
  modelFrom.prototype["__link__" + relationName] = addFunc;
551
608
  const removeFunc = scopeMethods.remove;
@@ -916,6 +973,65 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
916
973
  return cb.promise;
917
974
  };
918
975
  /**
976
+ * Count related instances for a hasManyThrough relation.
977
+ *
978
+ * By default this counts through-model rows, including orphans and duplicate
979
+ * links. Set `options.countRelated` on the relation to count unique existing
980
+ * related target instances instead. The optional `where` is applied to the
981
+ * through model by default, or to the target model when `countRelated` is true.
982
+ *
983
+ * @param {Object} [where]
984
+ * @param {Object} [options]
985
+ * @param {Function} [cb]
986
+ */
987
+ HasManyThrough.prototype.count = function(where, options, cb) {
988
+ if (typeof where === "function") {
989
+ cb = where;
990
+ where = {};
991
+ options = {};
992
+ } else if (typeof options === "function" && cb === void 0) {
993
+ cb = options;
994
+ options = {};
995
+ }
996
+ options = options || {};
997
+ where = where || {};
998
+ const definition = this.definition;
999
+ const modelThrough = definition.modelThrough;
1000
+ const pk1 = definition.keyFrom;
1001
+ cb = cb || utils.createPromiseCallback();
1002
+ if (!definition.options || !definition.options.countRelated) {
1003
+ const filter = { where: {} };
1004
+ filter.where[definition.keyTo] = this.modelInstance[pk1];
1005
+ definition.applyScope(this.modelInstance, filter);
1006
+ mergeQuery(filter, { where });
1007
+ modelThrough.count(filter.where, options, cb);
1008
+ return cb.promise;
1009
+ }
1010
+ const keys = throughKeys(definition);
1011
+ const fk1 = keys[0];
1012
+ const fk2 = keys[1];
1013
+ const query = {};
1014
+ query[fk1] = this.modelInstance[pk1];
1015
+ const filter = { where: query };
1016
+ definition.applyScope(this.modelInstance, filter);
1017
+ const modelTo = definition.modelTo;
1018
+ const idName = modelTo.definition.idName();
1019
+ modelThrough.find({ where: filter.where }, options, function(err, throughs) {
1020
+ if (err) return cb(err);
1021
+ const ids = uniq((throughs || []).map(function(row) {
1022
+ return row[fk2];
1023
+ }).filter(function(id) {
1024
+ return id != null;
1025
+ }));
1026
+ if (ids.length === 0) return cb(null, 0);
1027
+ const targetFilter = { where: {} };
1028
+ targetFilter.where[idName] = { inq: ids };
1029
+ mergeQuery(targetFilter, { where });
1030
+ modelTo.count(targetFilter.where, options, cb);
1031
+ });
1032
+ return cb.promise;
1033
+ };
1034
+ /**
919
1035
  * Remove the target model instance from the 'hasMany' relation
920
1036
  * @param {Object|ID) acInst The actual instance or id value
921
1037
  */
@@ -1688,6 +1804,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
1688
1804
  const modelTo = this.definition.modelTo;
1689
1805
  const propertyName = this.definition.keyFrom;
1690
1806
  const modelInstance = this.modelInstance;
1807
+ const relationDefinition = this.definition;
1691
1808
  if (typeof targetModelData === "function" && !cb) {
1692
1809
  cb = targetModelData;
1693
1810
  targetModelData = {};
@@ -1696,6 +1813,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
1696
1813
  cb = cb || utils.createPromiseCallback();
1697
1814
  const inst = this.callScopeMethod("build", targetModelData);
1698
1815
  const updateEmbedded = function(callback) {
1816
+ applyWriteDefaultsToEmbeddedGraph(modelInstance, relationDefinition);
1699
1817
  if (modelInstance.isNewRecord()) {
1700
1818
  modelInstance.setAttribute(propertyName, inst);
1701
1819
  modelInstance.save(options, function(err) {
@@ -1768,6 +1886,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
1768
1886
  const data = targetModelData instanceof ModelBaseClass ? targetModelData.toObject() : targetModelData;
1769
1887
  const embeddedInstance = this.embeddedValue();
1770
1888
  if (embeddedInstance instanceof modelTo) {
1889
+ applyWriteDefaultsToEmbeddedGraph(modelInstance, this.definition);
1771
1890
  cb = cb || utils.createPromiseCallback();
1772
1891
  const hookState = {};
1773
1892
  let context = {
@@ -1813,6 +1932,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
1813
1932
  return cb.promise;
1814
1933
  }
1815
1934
  modelInstance.unsetAttribute(propertyName, true);
1935
+ applyWriteDefaultsToEmbeddedGraph(modelInstance, this.definition);
1816
1936
  const context = {
1817
1937
  Model: modelTo,
1818
1938
  instance: embeddedInstance,
@@ -2057,6 +2177,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
2057
2177
  const embeddedList = this.embeddedList();
2058
2178
  const inst = this.findById(fkId);
2059
2179
  if (inst instanceof modelTo) {
2180
+ applyWriteDefaultsToEmbeddedGraph(modelInstance, this.definition);
2060
2181
  const hookState = {};
2061
2182
  let context = {
2062
2183
  Model: modelTo,
@@ -2102,6 +2223,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
2102
2223
  const modelTo = this.definition.modelTo;
2103
2224
  const propertyName = this.definition.keyFrom;
2104
2225
  const modelInstance = this.modelInstance;
2226
+ const relationDefinition = this.definition;
2105
2227
  const embeddedList = this.embeddedList();
2106
2228
  const inst = fkId instanceof modelTo ? fkId : this.findById(fkId);
2107
2229
  if (inst instanceof modelTo) {
@@ -2115,6 +2237,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
2115
2237
  if (err) return cb(err);
2116
2238
  const index = embeddedList.indexOf(inst);
2117
2239
  if (index > -1) embeddedList.splice(index, 1);
2240
+ applyWriteDefaultsToEmbeddedGraph(modelInstance, relationDefinition);
2118
2241
  if (typeof cb !== "function") return;
2119
2242
  modelInstance.updateAttribute(propertyName, embeddedList, context.options, function(err) {
2120
2243
  if (err) return cb(err);
@@ -2137,6 +2260,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
2137
2260
  const propertyName = this.definition.keyFrom;
2138
2261
  const modelInstance = this.modelInstance;
2139
2262
  let embeddedList = this.embeddedList();
2263
+ applyWriteDefaultsToEmbeddedGraph(modelInstance, this.definition);
2140
2264
  if (where && Object.keys(where).length > 0) {
2141
2265
  const filter = applyFilter({ where });
2142
2266
  const reject = function(v) {
@@ -2167,6 +2291,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
2167
2291
  const modelTo = this.definition.modelTo;
2168
2292
  const propertyName = this.definition.keyFrom;
2169
2293
  const modelInstance = this.modelInstance;
2294
+ const relationDefinition = this.definition;
2170
2295
  if (typeof options === "function" && cb === void 0) {
2171
2296
  cb = options;
2172
2297
  options = {};
@@ -2180,6 +2305,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
2180
2305
  const inst = this.callScopeMethod("build", targetModelData);
2181
2306
  const embeddedList = this.embeddedList();
2182
2307
  const updateEmbedded = function(callback) {
2308
+ applyWriteDefaultsToEmbeddedGraph(modelInstance, relationDefinition);
2183
2309
  if (modelInstance.isNewRecord()) {
2184
2310
  modelInstance.setAttribute(propertyName, embeddedList);
2185
2311
  modelInstance.save(options, function(err) {
@@ -2284,6 +2410,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
2284
2410
  if (ref instanceof belongsTo.modelTo) {
2285
2411
  const inst = self.build(data || {});
2286
2412
  inst[defOpts.belongsTo](ref);
2413
+ applyWriteDefaultsToEmbeddedGraph(modelInstance, self.definition);
2287
2414
  modelInstance.save(function(err) {
2288
2415
  cb(err, err ? null : inst);
2289
2416
  });
@@ -2319,6 +2446,7 @@ var require_relation_definition = /* @__PURE__ */ require_runtime.__commonJSMin(
2319
2446
  items.forEach(function(item) {
2320
2447
  self.unset(item);
2321
2448
  });
2449
+ applyWriteDefaultsToEmbeddedGraph(modelInstance, self.definition);
2322
2450
  modelInstance.save(options, function(err) {
2323
2451
  cb(err);
2324
2452
  });
@@ -71,6 +71,10 @@ var require_relations = /* @__PURE__ */ require_runtime.__commonJSMin(((exports,
71
71
  * @property {Object|Function} scope Explicitly define additional scopes.
72
72
  * @property {Boolean} invert Specify if the relation is inverted.
73
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).
74
78
  */
75
79
  RelationMixin.hasMany = function hasMany(modelTo, params) {
76
80
  return RelationDefinition.hasMany(this, modelTo, params);
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.2",
5
+ "version": "13.0.0",
6
6
  "description": "Fork of loopback-datasource-juggler for LoopBack 3 style applications",
7
7
  "keywords": [
8
8
  "Connector",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vsaas/loopback-datasource-juggler",
3
- "version": "12.1.2",
3
+ "version": "13.0.0",
4
4
  "description": "Fork of loopback-datasource-juggler for LoopBack 3 style applications",
5
5
  "keywords": [
6
6
  "Connector",
@@ -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<