@web-ts-toolkit/moo 0.43.0 → 0.48.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/plugins/index.js CHANGED
@@ -89,6 +89,121 @@ var resolveFilter = (value, document) => {
89
89
  }
90
90
  return result;
91
91
  };
92
+ var isNonEmptyString = (value) => typeof value === "string" && value.trim().length > 0;
93
+ var isEmptyFilterObject = (value) => Object.keys(value).length === 0;
94
+ 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.";
95
+ var DEFAULT_MAX_CONCURRENCY = 8;
96
+ var DEFAULT_BATCH_SIZE = 100;
97
+ var assertPositiveIntOption = (value, name, modelName) => {
98
+ if (value === void 0) return;
99
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
100
+ throw new Error(
101
+ `cascadeDeletePlugin for model "${modelName}" requires \`${name}\` to be an integer >= 1 when provided`
102
+ );
103
+ }
104
+ };
105
+ var assertPluginOptions = (options) => {
106
+ if (!(0, import_utils2.isPlainObject)(options)) {
107
+ throw new Error("cascadeDeletePlugin requires options with a non-empty `model` name");
108
+ }
109
+ const { model, localField, foreignField, foreignFilter, extraForeignFilter } = options;
110
+ if (!isNonEmptyString(model)) {
111
+ throw new Error("cascadeDeletePlugin requires a non-empty `model` name");
112
+ }
113
+ if (localField !== void 0 && !isNonEmptyString(localField)) {
114
+ throw new Error("cascadeDeletePlugin requires `localField` to be a non-empty string when provided");
115
+ }
116
+ assertPositiveIntOption(options.maxConcurrency, "maxConcurrency", model);
117
+ assertPositiveIntOption(options.batchSize, "batchSize", model);
118
+ if (foreignField !== void 0 && !isNonEmptyString(foreignField)) {
119
+ throw new Error("cascadeDeletePlugin requires `foreignField` to be a non-empty string when provided");
120
+ }
121
+ if (foreignFilter !== void 0) {
122
+ if (!(0, import_utils2.isFunction)(foreignFilter) && !(0, import_utils2.isPlainObject)(foreignFilter)) {
123
+ throw new Error(
124
+ `cascadeDeletePlugin invalid \`foreignFilter\` for model "${model}": expected a plain filter object or a resolver function`
125
+ );
126
+ }
127
+ if ((0, import_utils2.isPlainObject)(foreignFilter) && isEmptyFilterObject(foreignFilter)) {
128
+ throw new Error(`cascadeDeletePlugin ${EMPTY_FULL_FILTER_MESSAGE}`);
129
+ }
130
+ } else if (!isNonEmptyString(localField) || !isNonEmptyString(foreignField)) {
131
+ throw new Error(
132
+ `cascadeDeletePlugin for model "${model}" requires either \`foreignFilter\` or both \`localField\` and \`foreignField\``
133
+ );
134
+ }
135
+ if (extraForeignFilter !== void 0) {
136
+ if (!(0, import_utils2.isFunction)(extraForeignFilter) && !(0, import_utils2.isPlainObject)(extraForeignFilter)) {
137
+ throw new Error(
138
+ `cascadeDeletePlugin invalid \`extraForeignFilter\` for model "${model}": expected a plain filter object or a resolver function`
139
+ );
140
+ }
141
+ }
142
+ };
143
+ var assertFullFilterNotEmpty = (filter, modelName) => {
144
+ if (isEmptyFilterObject(filter)) {
145
+ throw new Error(`cascadeDeletePlugin for model "${modelName}" ${EMPTY_FULL_FILTER_MESSAGE}`);
146
+ }
147
+ };
148
+ var isMissingScalarKey = (value) => {
149
+ if (value === void 0 || value === null) return true;
150
+ if (typeof value === "string" && value.trim().length === 0) return true;
151
+ return false;
152
+ };
153
+ var unwrapKeyValue = (value) => {
154
+ if ((0, import_utils2.isPlainObject)(value)) {
155
+ const candidate = value._id;
156
+ if (candidate !== void 0 && candidate !== null) return candidate;
157
+ }
158
+ if ((0, import_utils2.isObject)(value)) {
159
+ try {
160
+ const candidate = value._id;
161
+ if (candidate !== void 0 && candidate !== null) return candidate;
162
+ } catch {
163
+ }
164
+ }
165
+ return value;
166
+ };
167
+ var normalizeKeyList = (localValue) => {
168
+ if (Array.isArray(localValue)) {
169
+ const keys = [];
170
+ for (const entry of localValue) {
171
+ const unwrapped2 = unwrapKeyValue(entry);
172
+ if (!isMissingScalarKey(unwrapped2)) keys.push(unwrapped2);
173
+ }
174
+ return keys.length > 0 ? keys : null;
175
+ }
176
+ const unwrapped = unwrapKeyValue(localValue);
177
+ if (isMissingScalarKey(unwrapped)) return null;
178
+ return [unwrapped];
179
+ };
180
+ var isPathDeselected = (owner, path) => {
181
+ try {
182
+ const candidate = owner;
183
+ if (typeof candidate.$isSelected === "function") {
184
+ const result = candidate.$isSelected(path);
185
+ if (typeof result === "boolean") return result === false;
186
+ }
187
+ if (typeof candidate.isSelected === "function") {
188
+ const result = candidate.isSelected(path);
189
+ if (typeof result === "boolean") return result === false;
190
+ }
191
+ } catch {
192
+ }
193
+ return false;
194
+ };
195
+ var buildRelationshipPredicate = (foreignField, localValue) => {
196
+ const keys = normalizeKeyList(localValue);
197
+ if (!keys) return null;
198
+ if (Array.isArray(localValue)) {
199
+ return { [foreignField]: { $in: keys } };
200
+ }
201
+ return { [foreignField]: keys[0] };
202
+ };
203
+ var combineWithRelationship = (relationship, extra) => {
204
+ if (!extra || isEmptyFilterObject(extra)) return relationship;
205
+ return { $and: [relationship, extra] };
206
+ };
92
207
  var applyQueryOptions = (query, options) => {
93
208
  let builder = query;
94
209
  if (options.select) {
@@ -103,8 +218,81 @@ var applyQueryOptions = (query, options) => {
103
218
  if (options.lean) {
104
219
  builder = builder.lean();
105
220
  }
221
+ if (options.session) {
222
+ builder = builder.session(options.session);
223
+ }
106
224
  return builder;
107
225
  };
226
+ var getOwningConnection = (owner) => {
227
+ const candidate = owner?.collection?.conn ?? owner?.constructor?.collection?.conn ?? null;
228
+ if (candidate && typeof candidate.model === "function") {
229
+ return candidate;
230
+ }
231
+ return import_mongoose3.default;
232
+ };
233
+ var getBoundSession = (owner) => {
234
+ try {
235
+ const session = owner?.$session?.() ?? null;
236
+ return session ?? null;
237
+ } catch {
238
+ return null;
239
+ }
240
+ };
241
+ var resolveExecutionContext = (owner, targetModelName, explicitSession) => {
242
+ const session = explicitSession ?? getBoundSession(owner) ?? null;
243
+ const connection = getOwningConnection(owner);
244
+ const Target = connection.model(targetModelName);
245
+ return { connection, Target, session };
246
+ };
247
+ var isInTransaction = (session) => {
248
+ try {
249
+ return typeof session?.inTransaction === "function" ? session.inTransaction() : false;
250
+ } catch {
251
+ return false;
252
+ }
253
+ };
254
+ var getSessionClient = (session) => {
255
+ if (!session) return null;
256
+ return session.client ?? null;
257
+ };
258
+ var getConnectionClient = (connection) => {
259
+ try {
260
+ if (connection === import_mongoose3.default) {
261
+ return import_mongoose3.default.connection.getClient?.() ?? null;
262
+ }
263
+ return connection.getClient?.() ?? null;
264
+ } catch {
265
+ return null;
266
+ }
267
+ };
268
+ var getTopologyType = (client) => {
269
+ try {
270
+ const topology = client?.topology;
271
+ const type = topology?.description?.type;
272
+ return typeof type === "string" ? type : null;
273
+ } catch {
274
+ return null;
275
+ }
276
+ };
277
+ var assertTransactionSupported = (context) => {
278
+ const { connection, session } = context;
279
+ if (!session) return;
280
+ const sessionClient = getSessionClient(session);
281
+ const connectionClient = getConnectionClient(connection);
282
+ if (sessionClient && connectionClient && sessionClient !== connectionClient) {
283
+ throw new Error(
284
+ "cascadeDeletePlugin does not support sessions bound to a different connection/client; pass a session from the owning model connection"
285
+ );
286
+ }
287
+ if (isInTransaction(session)) {
288
+ const topologyType = getTopologyType(sessionClient);
289
+ if (topologyType === "Single") {
290
+ throw new Error(
291
+ "cascadeDeletePlugin does not support transactions on a standalone MongoDB deployment; use a replica set or sharded cluster, or delete without a transaction"
292
+ );
293
+ }
294
+ }
295
+ };
108
296
  var supportsDeleteOne = (value) => (0, import_utils2.isObject)(value) && typeof value.deleteOne === "function";
109
297
  var supportsRemove = (value) => (0, import_utils2.isObject)(value) && typeof value.remove === "function";
110
298
  var mergeResults = (previousResults, modelName, currentResults) => {
@@ -117,56 +305,189 @@ var mergeResults = (previousResults, modelName, currentResults) => {
117
305
  [modelName]: currentResults
118
306
  };
119
307
  };
308
+ var resolveDependentFilter = (owner, config) => {
309
+ const { model, localField, foreignField, foreignFilter, extraForeignFilter } = config;
310
+ const document = owner.toObject({ virtuals: false });
311
+ if (foreignFilter !== void 0) {
312
+ const resolved = resolveFilter(foreignFilter, document);
313
+ if (resolved === null) return null;
314
+ assertFullFilterNotEmpty(resolved, model);
315
+ return resolved;
316
+ }
317
+ if (localField && foreignField) {
318
+ const localValue = owner.get(localField);
319
+ if (normalizeKeyList(localValue) === null) {
320
+ if (isPathDeselected(owner, localField)) {
321
+ throw new Error(
322
+ `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`
323
+ );
324
+ }
325
+ return null;
326
+ }
327
+ const relationship = buildRelationshipPredicate(foreignField, localValue);
328
+ if (!relationship) return null;
329
+ const extraFilter = resolveFilter(extraForeignFilter, document);
330
+ return combineWithRelationship(relationship, extraFilter);
331
+ }
332
+ return null;
333
+ };
334
+ var resolveTraversalLimits = (options) => ({
335
+ maxConcurrency: typeof options.maxConcurrency === "number" ? options.maxConcurrency : DEFAULT_MAX_CONCURRENCY,
336
+ batchSize: typeof options.batchSize === "number" ? options.batchSize : DEFAULT_BATCH_SIZE
337
+ });
338
+ var extractIdList = (rows) => rows.map((row) => {
339
+ if ((0, import_utils2.isPlainObject)(row)) return row._id;
340
+ if ((0, import_utils2.isObject)(row)) {
341
+ try {
342
+ const candidate = row._id;
343
+ if (candidate !== void 0) return candidate;
344
+ } catch {
345
+ }
346
+ }
347
+ return row;
348
+ });
349
+ var fetchDependentIdPage = async (Target, filter, session, lastId, batchSize) => {
350
+ const paged = lastId === void 0 ? filter : { $and: [filter, { _id: { $gt: lastId } }] };
351
+ let query = Target.find(paged).select("_id").sort({ _id: 1 }).limit(batchSize).lean();
352
+ if (session) query = query.session(session);
353
+ const rows = await query;
354
+ return extractIdList(Array.isArray(rows) ? rows : []);
355
+ };
356
+ var loadHydratedDependent = async (Target, id, session) => {
357
+ const query = Target.findById(id);
358
+ const result = session ? await query.session(session) : await query;
359
+ return result ?? null;
360
+ };
361
+ var runWithConcurrencyLimit = async (items, limit, task) => {
362
+ if (items.length === 0) return;
363
+ const workerCount = Math.max(1, Math.min(limit, items.length));
364
+ let next = 0;
365
+ let failed = false;
366
+ let firstError = null;
367
+ const workers = Array.from({ length: workerCount }, () => {
368
+ const run = async () => {
369
+ while (true) {
370
+ if (failed) return;
371
+ const index = next;
372
+ next += 1;
373
+ if (index >= items.length) return;
374
+ try {
375
+ await task(items[index]);
376
+ } catch (error) {
377
+ if (!failed) {
378
+ failed = true;
379
+ firstError = error;
380
+ }
381
+ throw error;
382
+ }
383
+ }
384
+ };
385
+ return run();
386
+ });
387
+ try {
388
+ await Promise.all(workers);
389
+ } catch {
390
+ throw firstError;
391
+ }
392
+ };
120
393
  function cascadeDeletePlugin(schema, options) {
394
+ assertPluginOptions(options);
121
395
  const { model, localField, foreignField, foreignFilter, extraForeignFilter } = options ?? {};
396
+ const filterConfig = {
397
+ model,
398
+ localField,
399
+ foreignField,
400
+ foreignFilter,
401
+ extraForeignFilter
402
+ };
403
+ const traversalLimits = resolveTraversalLimits(options ?? {});
122
404
  const findDependents = async function(queryOptions) {
123
- const Target = import_mongoose3.default.model(model);
124
- let query = null;
125
- const document = this.toObject({ virtuals: false });
126
- if (foreignFilter) {
127
- query = resolveFilter(foreignFilter, document);
128
- } else if (localField && foreignField) {
129
- const localValue = this.get(localField);
130
- const extraFilter = resolveFilter(extraForeignFilter, document) ?? {};
131
- query = {
132
- [foreignField]: Array.isArray(localValue) ? { $in: localValue } : localValue,
133
- ...extraFilter
134
- };
135
- }
405
+ const context = resolveExecutionContext(this, model, queryOptions?.session ?? null);
406
+ const { Target, session } = context;
407
+ const query = resolveDependentFilter(this, filterConfig);
136
408
  if (!query || !(0, import_utils2.isPlainObject)(query)) {
137
409
  return [];
138
410
  }
139
- return await applyQueryOptions(Target.find(query), queryOptions);
411
+ const mergedOptions = session ? { ...queryOptions, session } : queryOptions;
412
+ return await applyQueryOptions(Target.find(query), mergedOptions);
140
413
  };
141
414
  const findOrphans = async function(queryOptions) {
142
415
  if (!localField || !foreignField) return null;
143
- const Target = import_mongoose3.default.model(model);
416
+ const context = resolveExecutionContext(this, model, queryOptions?.session ?? null);
417
+ const { Target, session } = context;
144
418
  const schemaValue = Target.schema.obj[foreignField];
145
419
  if (!schemaValue) return null;
146
420
  const isMyRef = isReference(schemaValue, this.modelName);
147
421
  if (!isMyRef) return null;
148
- const ids = await this.distinct("_id");
149
- const extraFilter = resolveFilter(extraForeignFilter) ?? {};
150
- const query = {
151
- [foreignField]: { $not: { $in: ids } },
152
- ...extraFilter
422
+ const ids = session != null ? await this.distinct("_id", {}, { session }) : await this.distinct("_id");
423
+ const extraFilter = resolveFilter(extraForeignFilter);
424
+ const relationship = {
425
+ [foreignField]: { $not: { $in: ids } }
153
426
  };
154
- return await applyQueryOptions(Target.find(query), queryOptions);
427
+ const query = combineWithRelationship(
428
+ relationship,
429
+ extraFilter
430
+ );
431
+ const mergedOptions = session ? { ...queryOptions, session } : queryOptions;
432
+ return await applyQueryOptions(Target.find(query), mergedOptions);
155
433
  };
156
- const deleteDependents = async function() {
157
- const documents = await findDependents.call(this, { select: "_id" });
158
- await Promise.all(
159
- documents.map((document) => {
160
- if (supportsDeleteOne(document)) {
161
- return document.deleteOne();
162
- }
163
- if (supportsRemove(document)) {
164
- return document.remove();
434
+ const deleteDependents = async function(operationOptions) {
435
+ const context = resolveExecutionContext(this, model, operationOptions?.session ?? null);
436
+ assertTransactionSupported(context);
437
+ const { Target, session } = context;
438
+ const filter = resolveDependentFilter(this, filterConfig);
439
+ if (!filter || !(0, import_utils2.isPlainObject)(filter)) {
440
+ return;
441
+ }
442
+ const deleteSingle = async (document) => {
443
+ if (session != null && typeof document.$session === "function") {
444
+ try {
445
+ await document.$session?.(session);
446
+ } catch {
165
447
  }
166
- return Promise.resolve();
167
- })
168
- );
448
+ }
449
+ if (supportsDeleteOne(document)) {
450
+ return session != null ? document.deleteOne({ session }) : document.deleteOne();
451
+ }
452
+ if (supportsRemove(document)) {
453
+ return session != null ? document.remove({ session }) : document.remove();
454
+ }
455
+ return Promise.resolve();
456
+ };
457
+ const deleteById = async (id) => {
458
+ const hydrated = await loadHydratedDependent(Target, id, session);
459
+ if (!hydrated) return;
460
+ await deleteSingle(hydrated);
461
+ };
462
+ const effectiveConcurrency = session != null && isInTransaction(session) ? 1 : traversalLimits.maxConcurrency;
463
+ const seen = /* @__PURE__ */ new Set();
464
+ let lastId;
465
+ let firstPage = true;
466
+ for (; ; ) {
467
+ const ids = await fetchDependentIdPage(
468
+ Target,
469
+ filter,
470
+ session,
471
+ firstPage ? void 0 : lastId,
472
+ traversalLimits.batchSize
473
+ );
474
+ firstPage = false;
475
+ if (ids.length === 0) return;
476
+ const fresh = ids.filter((id) => {
477
+ const key = typeof id === "object" && id !== null ? String(id) : `${typeof id}:${String(id)}`;
478
+ if (seen.has(key)) return false;
479
+ seen.add(key);
480
+ return true;
481
+ });
482
+ await runWithConcurrencyLimit(fresh, effectiveConcurrency, deleteById);
483
+ lastId = ids[ids.length - 1];
484
+ if (ids.length < traversalLimits.batchSize) return;
485
+ }
169
486
  };
487
+ schema.pre("deleteOne", { document: true, query: false }, async function preDeleteOne(...args) {
488
+ const explicitSession = args[1]?.session ?? args[0]?.session ?? null;
489
+ assertTransactionSupported(resolveExecutionContext(this, model, explicitSession));
490
+ });
170
491
  schema.post("deleteOne", { document: true, query: false }, async function postDeleteOne() {
171
492
  await deleteDependents.call(this);
172
493
  });