@web-ts-toolkit/moo 0.42.2 → 0.47.1

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.
@@ -28,6 +28,121 @@ var resolveFilter = (value, document) => {
28
28
  }
29
29
  return result;
30
30
  };
31
+ var isNonEmptyString = (value) => typeof value === "string" && value.trim().length > 0;
32
+ var isEmptyFilterObject = (value) => Object.keys(value).length === 0;
33
+ var EMPTY_FULL_FILTER_MESSAGE = "cascadeDeletePlugin rejects empty foreignFilter by default because {} would match every document in the dependent collection; provide a non-empty filter object. Broad deletes are not implicitly enabled.";
34
+ var DEFAULT_MAX_CONCURRENCY = 8;
35
+ var DEFAULT_BATCH_SIZE = 100;
36
+ var assertPositiveIntOption = (value, name, modelName) => {
37
+ if (value === void 0) return;
38
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
39
+ throw new Error(
40
+ `cascadeDeletePlugin for model "${modelName}" requires \`${name}\` to be an integer >= 1 when provided`
41
+ );
42
+ }
43
+ };
44
+ var assertPluginOptions = (options) => {
45
+ if (!isPlainObject2(options)) {
46
+ throw new Error("cascadeDeletePlugin requires options with a non-empty `model` name");
47
+ }
48
+ const { model, localField, foreignField, foreignFilter, extraForeignFilter } = options;
49
+ if (!isNonEmptyString(model)) {
50
+ throw new Error("cascadeDeletePlugin requires a non-empty `model` name");
51
+ }
52
+ if (localField !== void 0 && !isNonEmptyString(localField)) {
53
+ throw new Error("cascadeDeletePlugin requires `localField` to be a non-empty string when provided");
54
+ }
55
+ assertPositiveIntOption(options.maxConcurrency, "maxConcurrency", model);
56
+ assertPositiveIntOption(options.batchSize, "batchSize", model);
57
+ if (foreignField !== void 0 && !isNonEmptyString(foreignField)) {
58
+ throw new Error("cascadeDeletePlugin requires `foreignField` to be a non-empty string when provided");
59
+ }
60
+ if (foreignFilter !== void 0) {
61
+ if (!isFunction2(foreignFilter) && !isPlainObject2(foreignFilter)) {
62
+ throw new Error(
63
+ `cascadeDeletePlugin invalid \`foreignFilter\` for model "${model}": expected a plain filter object or a resolver function`
64
+ );
65
+ }
66
+ if (isPlainObject2(foreignFilter) && isEmptyFilterObject(foreignFilter)) {
67
+ throw new Error(`cascadeDeletePlugin ${EMPTY_FULL_FILTER_MESSAGE}`);
68
+ }
69
+ } else if (!isNonEmptyString(localField) || !isNonEmptyString(foreignField)) {
70
+ throw new Error(
71
+ `cascadeDeletePlugin for model "${model}" requires either \`foreignFilter\` or both \`localField\` and \`foreignField\``
72
+ );
73
+ }
74
+ if (extraForeignFilter !== void 0) {
75
+ if (!isFunction2(extraForeignFilter) && !isPlainObject2(extraForeignFilter)) {
76
+ throw new Error(
77
+ `cascadeDeletePlugin invalid \`extraForeignFilter\` for model "${model}": expected a plain filter object or a resolver function`
78
+ );
79
+ }
80
+ }
81
+ };
82
+ var assertFullFilterNotEmpty = (filter, modelName) => {
83
+ if (isEmptyFilterObject(filter)) {
84
+ throw new Error(`cascadeDeletePlugin for model "${modelName}" ${EMPTY_FULL_FILTER_MESSAGE}`);
85
+ }
86
+ };
87
+ var isMissingScalarKey = (value) => {
88
+ if (value === void 0 || value === null) return true;
89
+ if (typeof value === "string" && value.trim().length === 0) return true;
90
+ return false;
91
+ };
92
+ var unwrapKeyValue = (value) => {
93
+ if (isPlainObject2(value)) {
94
+ const candidate = value._id;
95
+ if (candidate !== void 0 && candidate !== null) return candidate;
96
+ }
97
+ if (isObject(value)) {
98
+ try {
99
+ const candidate = value._id;
100
+ if (candidate !== void 0 && candidate !== null) return candidate;
101
+ } catch {
102
+ }
103
+ }
104
+ return value;
105
+ };
106
+ var normalizeKeyList = (localValue) => {
107
+ if (Array.isArray(localValue)) {
108
+ const keys = [];
109
+ for (const entry of localValue) {
110
+ const unwrapped2 = unwrapKeyValue(entry);
111
+ if (!isMissingScalarKey(unwrapped2)) keys.push(unwrapped2);
112
+ }
113
+ return keys.length > 0 ? keys : null;
114
+ }
115
+ const unwrapped = unwrapKeyValue(localValue);
116
+ if (isMissingScalarKey(unwrapped)) return null;
117
+ return [unwrapped];
118
+ };
119
+ var isPathDeselected = (owner, path) => {
120
+ try {
121
+ const candidate = owner;
122
+ if (typeof candidate.$isSelected === "function") {
123
+ const result = candidate.$isSelected(path);
124
+ if (typeof result === "boolean") return result === false;
125
+ }
126
+ if (typeof candidate.isSelected === "function") {
127
+ const result = candidate.isSelected(path);
128
+ if (typeof result === "boolean") return result === false;
129
+ }
130
+ } catch {
131
+ }
132
+ return false;
133
+ };
134
+ var buildRelationshipPredicate = (foreignField, localValue) => {
135
+ const keys = normalizeKeyList(localValue);
136
+ if (!keys) return null;
137
+ if (Array.isArray(localValue)) {
138
+ return { [foreignField]: { $in: keys } };
139
+ }
140
+ return { [foreignField]: keys[0] };
141
+ };
142
+ var combineWithRelationship = (relationship, extra) => {
143
+ if (!extra || isEmptyFilterObject(extra)) return relationship;
144
+ return { $and: [relationship, extra] };
145
+ };
31
146
  var applyQueryOptions = (query, options) => {
32
147
  let builder = query;
33
148
  if (options.select) {
@@ -42,8 +157,81 @@ var applyQueryOptions = (query, options) => {
42
157
  if (options.lean) {
43
158
  builder = builder.lean();
44
159
  }
160
+ if (options.session) {
161
+ builder = builder.session(options.session);
162
+ }
45
163
  return builder;
46
164
  };
165
+ var getOwningConnection = (owner) => {
166
+ const candidate = owner?.collection?.conn ?? owner?.constructor?.collection?.conn ?? null;
167
+ if (candidate && typeof candidate.model === "function") {
168
+ return candidate;
169
+ }
170
+ return mongoose;
171
+ };
172
+ var getBoundSession = (owner) => {
173
+ try {
174
+ const session = owner?.$session?.() ?? null;
175
+ return session ?? null;
176
+ } catch {
177
+ return null;
178
+ }
179
+ };
180
+ var resolveExecutionContext = (owner, targetModelName, explicitSession) => {
181
+ const session = explicitSession ?? getBoundSession(owner) ?? null;
182
+ const connection = getOwningConnection(owner);
183
+ const Target = connection.model(targetModelName);
184
+ return { connection, Target, session };
185
+ };
186
+ var isInTransaction = (session) => {
187
+ try {
188
+ return typeof session?.inTransaction === "function" ? session.inTransaction() : false;
189
+ } catch {
190
+ return false;
191
+ }
192
+ };
193
+ var getSessionClient = (session) => {
194
+ if (!session) return null;
195
+ return session.client ?? null;
196
+ };
197
+ var getConnectionClient = (connection) => {
198
+ try {
199
+ if (connection === mongoose) {
200
+ return mongoose.connection.getClient?.() ?? null;
201
+ }
202
+ return connection.getClient?.() ?? null;
203
+ } catch {
204
+ return null;
205
+ }
206
+ };
207
+ var getTopologyType = (client) => {
208
+ try {
209
+ const topology = client?.topology;
210
+ const type = topology?.description?.type;
211
+ return typeof type === "string" ? type : null;
212
+ } catch {
213
+ return null;
214
+ }
215
+ };
216
+ var assertTransactionSupported = (context) => {
217
+ const { connection, session } = context;
218
+ if (!session) return;
219
+ const sessionClient = getSessionClient(session);
220
+ const connectionClient = getConnectionClient(connection);
221
+ if (sessionClient && connectionClient && sessionClient !== connectionClient) {
222
+ throw new Error(
223
+ "cascadeDeletePlugin does not support sessions bound to a different connection/client; pass a session from the owning model connection"
224
+ );
225
+ }
226
+ if (isInTransaction(session)) {
227
+ const topologyType = getTopologyType(sessionClient);
228
+ if (topologyType === "Single") {
229
+ throw new Error(
230
+ "cascadeDeletePlugin does not support transactions on a standalone MongoDB deployment; use a replica set or sharded cluster, or delete without a transaction"
231
+ );
232
+ }
233
+ }
234
+ };
47
235
  var supportsDeleteOne = (value) => isObject(value) && typeof value.deleteOne === "function";
48
236
  var supportsRemove = (value) => isObject(value) && typeof value.remove === "function";
49
237
  var mergeResults = (previousResults, modelName, currentResults) => {
@@ -56,56 +244,189 @@ var mergeResults = (previousResults, modelName, currentResults) => {
56
244
  [modelName]: currentResults
57
245
  };
58
246
  };
247
+ var resolveDependentFilter = (owner, config) => {
248
+ const { model, localField, foreignField, foreignFilter, extraForeignFilter } = config;
249
+ const document = owner.toObject({ virtuals: false });
250
+ if (foreignFilter !== void 0) {
251
+ const resolved = resolveFilter(foreignFilter, document);
252
+ if (resolved === null) return null;
253
+ assertFullFilterNotEmpty(resolved, model);
254
+ return resolved;
255
+ }
256
+ if (localField && foreignField) {
257
+ const localValue = owner.get(localField);
258
+ if (normalizeKeyList(localValue) === null) {
259
+ if (isPathDeselected(owner, localField)) {
260
+ throw new Error(
261
+ `cascadeDeletePlugin for model "${model}" cannot resolve dependents: localField "${localField}" was not selected on the document; load the document with that path projected instead of assuming an empty relation`
262
+ );
263
+ }
264
+ return null;
265
+ }
266
+ const relationship = buildRelationshipPredicate(foreignField, localValue);
267
+ if (!relationship) return null;
268
+ const extraFilter = resolveFilter(extraForeignFilter, document);
269
+ return combineWithRelationship(relationship, extraFilter);
270
+ }
271
+ return null;
272
+ };
273
+ var resolveTraversalLimits = (options) => ({
274
+ maxConcurrency: typeof options.maxConcurrency === "number" ? options.maxConcurrency : DEFAULT_MAX_CONCURRENCY,
275
+ batchSize: typeof options.batchSize === "number" ? options.batchSize : DEFAULT_BATCH_SIZE
276
+ });
277
+ var extractIdList = (rows) => rows.map((row) => {
278
+ if (isPlainObject2(row)) return row._id;
279
+ if (isObject(row)) {
280
+ try {
281
+ const candidate = row._id;
282
+ if (candidate !== void 0) return candidate;
283
+ } catch {
284
+ }
285
+ }
286
+ return row;
287
+ });
288
+ var fetchDependentIdPage = async (Target, filter, session, lastId, batchSize) => {
289
+ const paged = lastId === void 0 ? filter : { $and: [filter, { _id: { $gt: lastId } }] };
290
+ let query = Target.find(paged).select("_id").sort({ _id: 1 }).limit(batchSize).lean();
291
+ if (session) query = query.session(session);
292
+ const rows = await query;
293
+ return extractIdList(Array.isArray(rows) ? rows : []);
294
+ };
295
+ var loadHydratedDependent = async (Target, id, session) => {
296
+ const query = Target.findById(id);
297
+ const result = session ? await query.session(session) : await query;
298
+ return result ?? null;
299
+ };
300
+ var runWithConcurrencyLimit = async (items, limit, task) => {
301
+ if (items.length === 0) return;
302
+ const workerCount = Math.max(1, Math.min(limit, items.length));
303
+ let next = 0;
304
+ let failed = false;
305
+ let firstError = null;
306
+ const workers = Array.from({ length: workerCount }, () => {
307
+ const run = async () => {
308
+ while (true) {
309
+ if (failed) return;
310
+ const index = next;
311
+ next += 1;
312
+ if (index >= items.length) return;
313
+ try {
314
+ await task(items[index]);
315
+ } catch (error) {
316
+ if (!failed) {
317
+ failed = true;
318
+ firstError = error;
319
+ }
320
+ throw error;
321
+ }
322
+ }
323
+ };
324
+ return run();
325
+ });
326
+ try {
327
+ await Promise.all(workers);
328
+ } catch {
329
+ throw firstError;
330
+ }
331
+ };
59
332
  function cascadeDeletePlugin(schema, options) {
333
+ assertPluginOptions(options);
60
334
  const { model, localField, foreignField, foreignFilter, extraForeignFilter } = options ?? {};
335
+ const filterConfig = {
336
+ model,
337
+ localField,
338
+ foreignField,
339
+ foreignFilter,
340
+ extraForeignFilter
341
+ };
342
+ const traversalLimits = resolveTraversalLimits(options ?? {});
61
343
  const findDependents = async function(queryOptions) {
62
- const Target = mongoose.model(model);
63
- let query = null;
64
- const document = this.toObject({ virtuals: false });
65
- if (foreignFilter) {
66
- query = resolveFilter(foreignFilter, document);
67
- } else if (localField && foreignField) {
68
- const localValue = this.get(localField);
69
- const extraFilter = resolveFilter(extraForeignFilter, document) ?? {};
70
- query = {
71
- [foreignField]: Array.isArray(localValue) ? { $in: localValue } : localValue,
72
- ...extraFilter
73
- };
74
- }
344
+ const context = resolveExecutionContext(this, model, queryOptions?.session ?? null);
345
+ const { Target, session } = context;
346
+ const query = resolveDependentFilter(this, filterConfig);
75
347
  if (!query || !isPlainObject2(query)) {
76
348
  return [];
77
349
  }
78
- return await applyQueryOptions(Target.find(query), queryOptions);
350
+ const mergedOptions = session ? { ...queryOptions, session } : queryOptions;
351
+ return await applyQueryOptions(Target.find(query), mergedOptions);
79
352
  };
80
353
  const findOrphans = async function(queryOptions) {
81
354
  if (!localField || !foreignField) return null;
82
- const Target = mongoose.model(model);
355
+ const context = resolveExecutionContext(this, model, queryOptions?.session ?? null);
356
+ const { Target, session } = context;
83
357
  const schemaValue = Target.schema.obj[foreignField];
84
358
  if (!schemaValue) return null;
85
359
  const isMyRef = isReference(schemaValue, this.modelName);
86
360
  if (!isMyRef) return null;
87
- const ids = await this.distinct("_id");
88
- const extraFilter = resolveFilter(extraForeignFilter) ?? {};
89
- const query = {
90
- [foreignField]: { $not: { $in: ids } },
91
- ...extraFilter
361
+ const ids = session != null ? await this.distinct("_id", {}, { session }) : await this.distinct("_id");
362
+ const extraFilter = resolveFilter(extraForeignFilter);
363
+ const relationship = {
364
+ [foreignField]: { $not: { $in: ids } }
92
365
  };
93
- return await applyQueryOptions(Target.find(query), queryOptions);
366
+ const query = combineWithRelationship(
367
+ relationship,
368
+ extraFilter
369
+ );
370
+ const mergedOptions = session ? { ...queryOptions, session } : queryOptions;
371
+ return await applyQueryOptions(Target.find(query), mergedOptions);
94
372
  };
95
- const deleteDependents = async function() {
96
- const documents = await findDependents.call(this, { select: "_id" });
97
- await Promise.all(
98
- documents.map((document) => {
99
- if (supportsDeleteOne(document)) {
100
- return document.deleteOne();
101
- }
102
- if (supportsRemove(document)) {
103
- return document.remove();
373
+ const deleteDependents = async function(operationOptions) {
374
+ const context = resolveExecutionContext(this, model, operationOptions?.session ?? null);
375
+ assertTransactionSupported(context);
376
+ const { Target, session } = context;
377
+ const filter = resolveDependentFilter(this, filterConfig);
378
+ if (!filter || !isPlainObject2(filter)) {
379
+ return;
380
+ }
381
+ const deleteSingle = async (document) => {
382
+ if (session != null && typeof document.$session === "function") {
383
+ try {
384
+ await document.$session?.(session);
385
+ } catch {
104
386
  }
105
- return Promise.resolve();
106
- })
107
- );
387
+ }
388
+ if (supportsDeleteOne(document)) {
389
+ return session != null ? document.deleteOne({ session }) : document.deleteOne();
390
+ }
391
+ if (supportsRemove(document)) {
392
+ return session != null ? document.remove({ session }) : document.remove();
393
+ }
394
+ return Promise.resolve();
395
+ };
396
+ const deleteById = async (id) => {
397
+ const hydrated = await loadHydratedDependent(Target, id, session);
398
+ if (!hydrated) return;
399
+ await deleteSingle(hydrated);
400
+ };
401
+ const effectiveConcurrency = session != null && isInTransaction(session) ? 1 : traversalLimits.maxConcurrency;
402
+ const seen = /* @__PURE__ */ new Set();
403
+ let lastId;
404
+ let firstPage = true;
405
+ for (; ; ) {
406
+ const ids = await fetchDependentIdPage(
407
+ Target,
408
+ filter,
409
+ session,
410
+ firstPage ? void 0 : lastId,
411
+ traversalLimits.batchSize
412
+ );
413
+ firstPage = false;
414
+ if (ids.length === 0) return;
415
+ const fresh = ids.filter((id) => {
416
+ const key = typeof id === "object" && id !== null ? String(id) : `${typeof id}:${String(id)}`;
417
+ if (seen.has(key)) return false;
418
+ seen.add(key);
419
+ return true;
420
+ });
421
+ await runWithConcurrencyLimit(fresh, effectiveConcurrency, deleteById);
422
+ lastId = ids[ids.length - 1];
423
+ if (ids.length < traversalLimits.batchSize) return;
424
+ }
108
425
  };
426
+ schema.pre("deleteOne", { document: true, query: false }, async function preDeleteOne(...args) {
427
+ const explicitSession = args[1]?.session ?? args[0]?.session ?? null;
428
+ assertTransactionSupported(resolveExecutionContext(this, model, explicitSession));
429
+ });
109
430
  schema.post("deleteOne", { document: true, query: false }, async function postDeleteOne() {
110
431
  await deleteDependents.call(this);
111
432
  });
@@ -1,4 +1,4 @@
1
1
  export { ModelDocument, ModelFunctionInstanceMethods, ModelFunctionPluginOptions, ModelFunctionStaticMethods, modelFunctionPlugin } from './model-function.mjs';
2
- export { CascadeDeleteDependencyMap, CascadeDeleteDocumentMethods, CascadeDeleteModelStatics, CascadeDeletePluginOptions, FilterResolver, QueryFilter, cascadeDeletePlugin } from './cascade-delete.mjs';
2
+ export { CascadeDeleteDependencyMap, CascadeDeleteDocumentMethods, CascadeDeleteModelStatics, CascadeDeletePluginOptions, FilterResolver, QueryFilter, QueryOperators, cascadeDeletePlugin } from './cascade-delete.mjs';
3
3
  export { NewDocumentPluginOptions, newDocumentPlugin } from './new-document.mjs';
4
4
  import 'mongoose';
@@ -1,4 +1,4 @@
1
1
  export { ModelDocument, ModelFunctionInstanceMethods, ModelFunctionPluginOptions, ModelFunctionStaticMethods, modelFunctionPlugin } from './model-function.js';
2
- export { CascadeDeleteDependencyMap, CascadeDeleteDocumentMethods, CascadeDeleteModelStatics, CascadeDeletePluginOptions, FilterResolver, QueryFilter, cascadeDeletePlugin } from './cascade-delete.js';
2
+ export { CascadeDeleteDependencyMap, CascadeDeleteDocumentMethods, CascadeDeleteModelStatics, CascadeDeletePluginOptions, FilterResolver, QueryFilter, QueryOperators, cascadeDeletePlugin } from './cascade-delete.js';
3
3
  export { NewDocumentPluginOptions, newDocumentPlugin } from './new-document.js';
4
4
  import 'mongoose';