@atscript/db-mongo 0.1.167 → 0.1.168

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/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_mongo_accumulator = require("./mongo-accumulator-BW-RNFg0.cjs");
2
+ const require_mongo_accumulator = require("./mongo-accumulator-BOwAFmrt.cjs");
3
3
  const require_search_messages = require("./search-messages-BqLxxrb8.cjs");
4
4
  let _atscript_db = require("@atscript/db");
5
5
  let mongodb = require("mongodb");
@@ -1265,7 +1265,7 @@ function buildSearchStage(host, text, indexName, controls) {
1265
1265
  stage: { $match: equalities.length === 0 ? { _id: { $in: [] } } : equalities.length === 1 ? equalities[0] : { $or: equalities } },
1266
1266
  classicText: false
1267
1267
  };
1268
- const textMatch = { $text: { $search: text } };
1268
+ const textMatch = { $text: { $search: index.match === "all" ? mongoRequireEveryTerm(text) : text } };
1269
1269
  return {
1270
1270
  stage: { $match: equalities.length > 0 ? { $or: [textMatch, ...equalities] } : textMatch },
1271
1271
  classicText: true
@@ -1611,6 +1611,24 @@ async function runSearchWithMeta(host, stage, dataStages, label) {
1611
1611
  count: Number(total ?? 0)
1612
1612
  };
1613
1613
  }
1614
+ /**
1615
+ * A `$text` search with every word required (`@db.index.fulltext.match
1616
+ * "all"`, since 0.1.168): each word becomes a phrase — MongoDB AND-s phrases,
1617
+ * matching them as written (no stemming). A `"quoted phrase"` stays one phrase;
1618
+ * a word is split on non-letter, non-digit characters first.
1619
+ */
1620
+ function mongoRequireEveryTerm(text) {
1621
+ const parts = [];
1622
+ for (const match of text.matchAll(/"([^"]*)"|(\S+)/g)) {
1623
+ if (match[1] !== void 0) {
1624
+ const phrase = match[1].replace(/["\\]/g, " ").trim();
1625
+ if (phrase) parts.push(`"${phrase}"`);
1626
+ continue;
1627
+ }
1628
+ for (const piece of match[2].split(/[^\p{L}\p{N}]+/u)) if (piece) parts.push(`"${piece}"`);
1629
+ }
1630
+ return parts.join(" ");
1631
+ }
1614
1632
  //#endregion
1615
1633
  //#region src/lib/mongo-schema-sync.ts
1616
1634
  const DESTRUCTIVE_OPTION_KEYS = new Set([
@@ -1739,6 +1757,7 @@ async function recreateTableImpl(host) {
1739
1757
  }
1740
1758
  async function renameTableImpl(host, oldName) {
1741
1759
  const newName = host.resolveTableName(false);
1760
+ if (!await getObjectKindImpl(host, oldName) && await getObjectKindImpl(host, newName)) return;
1742
1761
  host._log("renameTable", oldName, "→", newName);
1743
1762
  await host.db.renameCollection(oldName, newName);
1744
1763
  host.clearCollectionCache();
@@ -1902,7 +1921,8 @@ async function syncIndexesImpl(host, opts, dryRun = false) {
1902
1921
  type: mongoType,
1903
1922
  fields,
1904
1923
  weights,
1905
- ...partialFilterExpression ? { partialFilterExpression } : {}
1924
+ ...partialFilterExpression ? { partialFilterExpression } : {},
1925
+ ...index.type === "fulltext" && index.language ? { defaultLanguage: index.language } : {}
1906
1926
  });
1907
1927
  }
1908
1928
  for (const [key, index] of host._mongoIndexes.entries()) if (index.type === "text") {
@@ -1935,7 +1955,7 @@ async function syncIndexesImpl(host, opts, dryRun = false) {
1935
1955
  const fieldsMatch = local.type === "text" || objMatch(local.fields, remote.key);
1936
1956
  const weightsMatch = objMatch(local.weights || {}, remote.weights || {});
1937
1957
  const wantedCollation = indexCollation(host, local);
1938
- const optionsMatch = local.type === "text" || local.type === "unique" === (remote.unique === true) && partialFilterEqual(local.partialFilterExpression, remote.partialFilterExpression) && (sameCollation(wantedCollation, remote.collation) || !wantedCollation && sameCollation(remote.collation, await collectionDefaultCollation()));
1958
+ const optionsMatch = local.type === "text" ? textLanguage(local.defaultLanguage) === textLanguage(remote.default_language) : local.type === "unique" === (remote.unique === true) && partialFilterEqual(local.partialFilterExpression, remote.partialFilterExpression) && (sameCollation(wantedCollation, remote.collation) || !wantedCollation && sameCollation(remote.collation, await collectionDefaultCollation()));
1939
1959
  const violation = fieldsMatch && weightsMatch && optionsMatch ? void 0 : local.type === "unique" && remote.unique === true ? await findUniqueViolation(host, local, wantedCollation) : void 0;
1940
1960
  if (fieldsMatch && weightsMatch && optionsMatch) indexesToCreate.delete(remote.name);
1941
1961
  else if (violation !== void 0) {
@@ -1985,7 +2005,8 @@ async function syncIndexesImpl(host, opts, dryRun = false) {
1985
2005
  label = `create text index "${key}"`;
1986
2006
  indexOptions = {
1987
2007
  weights: value.weights,
1988
- name: key
2008
+ name: key,
2009
+ ...value.defaultLanguage ? { default_language: value.defaultLanguage } : {}
1989
2010
  };
1990
2011
  break;
1991
2012
  case "2dsphere":
@@ -2215,6 +2236,10 @@ function vectorFieldsMatch(left, right) {
2215
2236
  }
2216
2237
  return true;
2217
2238
  }
2239
+ /** A text index's language as MongoDB applies it: `english` when none is set. */
2240
+ function textLanguage(language) {
2241
+ return language ?? "english";
2242
+ }
2218
2243
  //#endregion
2219
2244
  //#region src/lib/validate-plugins.ts
2220
2245
  const validateMongoIdPlugin = (ctx, def, value) => {
@@ -2415,7 +2440,7 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2415
2440
  if (!query.controls?.$having) return !forCount && query.controls?.$skip ? void 0 : row;
2416
2441
  const stages = emptyGroupStages(query, row, forCount);
2417
2442
  const probe = buildMatchedProbe(query, searchStage, this._predicateFilterOpts);
2418
- const run = (pipeline) => wrapInvalidQuery(() => this.aggregatePipeline(pipeline).toArray());
2443
+ const run = (pipeline) => wrapInvalidQuery(() => this.aggregatePipeline(pipeline, aggregateOptions(pipeline)).toArray());
2419
2444
  const [matched, applied] = this.isInTransaction() ? [await run(probe), void 0] : await Promise.all([run(probe), stages ? run(stages) : void 0]);
2420
2445
  if (matched.length > 0) return void 0;
2421
2446
  if (!stages) return row;
@@ -2483,6 +2508,25 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2483
2508
  return true;
2484
2509
  }
2485
2510
  /**
2511
+ * Conditional aggregates (`$where`): the condition as an aggregation
2512
+ * expression inside each accumulator (`$cond`), in SQL's three-valued logic
2513
+ * (`whereToExpr`). @since 0.1.168
2514
+ */
2515
+ supportsConditionalAggregates() {
2516
+ return true;
2517
+ }
2518
+ /** `countDistinct` over a field list: `$addToSet` of the value arrays, then `$size`. @since 0.1.168 */
2519
+ supportsDistinctFieldLists() {
2520
+ return true;
2521
+ }
2522
+ /**
2523
+ * Two-level aggregates (`$from`): the inner level's grouped stages, then the
2524
+ * outer level's over their documents, in one pipeline (`allowDiskUse`). @since 0.1.168
2525
+ */
2526
+ supportsNestedAggregates() {
2527
+ return true;
2528
+ }
2529
+ /**
2486
2530
  * `$nulls` placement (since 0.1.153): a placed `$sort` / `$rowOrder` key
2487
2531
  * gets a null-or-missing flag ordered before it (`mongo-sort.ts`) — reads
2488
2532
  * then run as a pipeline with a blocking sort instead of `find().sort()`.
@@ -2803,7 +2847,8 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2803
2847
  name: index.name,
2804
2848
  type: "text",
2805
2849
  fields: Object.fromEntries(index.fields.filter((f) => !f.integer).map((f) => [f.name, "text"])),
2806
- weights: Object.fromEntries(index.fields.filter((f) => f.weight && !f.integer).map((f) => [f.name, f.weight]))
2850
+ weights: Object.fromEntries(index.fields.filter((f) => f.weight && !f.integer).map((f) => [f.name, f.weight])),
2851
+ ...index.match ? { match: index.match } : {}
2807
2852
  };
2808
2853
  if (index === defaultFulltext) defaultIndex = converted;
2809
2854
  if (!this._searchIndexesMap.has(index.name)) this._searchIndexesMap.set(index.name, converted);
package/dist/index.d.cts CHANGED
@@ -167,6 +167,10 @@ interface TPlainIndex {
167
167
  * unique indexes (all fields required) and non-unique indexes.
168
168
  */
169
169
  partialFilterExpression?: Record<string, unknown>;
170
+ /** Text indexes: `@db.index.fulltext.language` → the index's `default_language` (since 0.1.168). */
171
+ defaultLanguage?: string;
172
+ /** Text indexes: `@db.index.fulltext.match` (since 0.1.168). */
173
+ match?: "all" | "any";
170
174
  }
171
175
  interface TSearchIndex {
172
176
  key: string;
@@ -367,6 +371,19 @@ declare class MongoAdapter extends BaseDbAdapter {
367
371
  aggregateFns(): ReadonlySet<AggregateFn>;
368
372
  /** Arithmetic in an aggregate `$select` (`{ $expr }`, `{ $fn, $expr }`). */
369
373
  supportsAggregateExpressions(): boolean;
374
+ /**
375
+ * Conditional aggregates (`$where`): the condition as an aggregation
376
+ * expression inside each accumulator (`$cond`), in SQL's three-valued logic
377
+ * (`whereToExpr`). @since 0.1.168
378
+ */
379
+ supportsConditionalAggregates(): boolean;
380
+ /** `countDistinct` over a field list: `$addToSet` of the value arrays, then `$size`. @since 0.1.168 */
381
+ supportsDistinctFieldLists(): boolean;
382
+ /**
383
+ * Two-level aggregates (`$from`): the inner level's grouped stages, then the
384
+ * outer level's over their documents, in one pipeline (`allowDiskUse`). @since 0.1.168
385
+ */
386
+ supportsNestedAggregates(): boolean;
370
387
  /**
371
388
  * `$nulls` placement (since 0.1.153): a placed `$sort` / `$rowOrder` key
372
389
  * gets a null-or-missing flag ordered before it (`mongo-sort.ts`) — reads
package/dist/index.d.mts CHANGED
@@ -167,6 +167,10 @@ interface TPlainIndex {
167
167
  * unique indexes (all fields required) and non-unique indexes.
168
168
  */
169
169
  partialFilterExpression?: Record<string, unknown>;
170
+ /** Text indexes: `@db.index.fulltext.language` → the index's `default_language` (since 0.1.168). */
171
+ defaultLanguage?: string;
172
+ /** Text indexes: `@db.index.fulltext.match` (since 0.1.168). */
173
+ match?: "all" | "any";
170
174
  }
171
175
  interface TSearchIndex {
172
176
  key: string;
@@ -367,6 +371,19 @@ declare class MongoAdapter extends BaseDbAdapter {
367
371
  aggregateFns(): ReadonlySet<AggregateFn>;
368
372
  /** Arithmetic in an aggregate `$select` (`{ $expr }`, `{ $fn, $expr }`). */
369
373
  supportsAggregateExpressions(): boolean;
374
+ /**
375
+ * Conditional aggregates (`$where`): the condition as an aggregation
376
+ * expression inside each accumulator (`$cond`), in SQL's three-valued logic
377
+ * (`whereToExpr`). @since 0.1.168
378
+ */
379
+ supportsConditionalAggregates(): boolean;
380
+ /** `countDistinct` over a field list: `$addToSet` of the value arrays, then `$size`. @since 0.1.168 */
381
+ supportsDistinctFieldLists(): boolean;
382
+ /**
383
+ * Two-level aggregates (`$from`): the inner level's grouped stages, then the
384
+ * outer level's over their documents, in one pipeline (`allowDiskUse`). @since 0.1.168
385
+ */
386
+ supportsNestedAggregates(): boolean;
370
387
  /**
371
388
  * `$nulls` placement (since 0.1.153): a placed `$sort` / `$rowOrder` key
372
389
  * gets a null-or-missing flag ordered before it (`mongo-sort.ts`) — reads
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as buildMongoQuery, c as planStages, f as sortStages, g as queryNodeToExpr, h as orNull, i as buildMongoFilter, l as correlate, n as distinctCountExpr, o as collationOfAdapter, p as exprToMongo, r as REL_FILTER_TEMP_PREFIX, s as mongoFilterStages, t as buildAccumulator, u as hasNullsPlacement } from "./mongo-accumulator-DMPFOscc.mjs";
1
+ import { a as buildMongoQuery, c as planStages, f as sortStages, h as queryNodeToExpr, i as buildMongoFilter, l as correlate, m as orNull, n as distinctCountExpr, o as collationOfAdapter, p as exprToMongo, r as REL_FILTER_TEMP_PREFIX, s as mongoFilterStages, t as buildAccumulator, u as hasNullsPlacement } from "./mongo-accumulator-D4drEz0-.mjs";
2
2
  import { t as dynamicSearchEncryptedMessage } from "./search-messages-mQSpJ4GD.mjs";
3
3
  import { ALL_AGGREGATE_FNS, ALL_BUCKET_UNITS, ALL_VIEW_CAPABILITIES, BaseDbAdapter, DbError, DbSpace, andFilters, bucketTimeZoneUnavailable, computeInsights, constraintViolation, containsRelationFilter, createChangeRecorder, createFailureCollector, defaultFulltextIndex, geoIndexNotFoundMessage, getDbFieldOp, getKeyProps, getPath, isAtscriptDbView, isFieldRef, isPlainObject, isViewType, queryReadColumns, relationStaticFilter, resolveDesignType, searchIndexNotFoundMessage, searchTermInteger, tableNameOf, translateQueryTree, uniqueKeyTuple, vectorIndexNotFoundMessage } from "@atscript/db";
4
4
  import { MongoBulkWriteError, MongoClient, MongoServerError, ObjectId } from "mongodb";
@@ -1264,7 +1264,7 @@ function buildSearchStage(host, text, indexName, controls) {
1264
1264
  stage: { $match: equalities.length === 0 ? { _id: { $in: [] } } : equalities.length === 1 ? equalities[0] : { $or: equalities } },
1265
1265
  classicText: false
1266
1266
  };
1267
- const textMatch = { $text: { $search: text } };
1267
+ const textMatch = { $text: { $search: index.match === "all" ? mongoRequireEveryTerm(text) : text } };
1268
1268
  return {
1269
1269
  stage: { $match: equalities.length > 0 ? { $or: [textMatch, ...equalities] } : textMatch },
1270
1270
  classicText: true
@@ -1610,6 +1610,24 @@ async function runSearchWithMeta(host, stage, dataStages, label) {
1610
1610
  count: Number(total ?? 0)
1611
1611
  };
1612
1612
  }
1613
+ /**
1614
+ * A `$text` search with every word required (`@db.index.fulltext.match
1615
+ * "all"`, since 0.1.168): each word becomes a phrase — MongoDB AND-s phrases,
1616
+ * matching them as written (no stemming). A `"quoted phrase"` stays one phrase;
1617
+ * a word is split on non-letter, non-digit characters first.
1618
+ */
1619
+ function mongoRequireEveryTerm(text) {
1620
+ const parts = [];
1621
+ for (const match of text.matchAll(/"([^"]*)"|(\S+)/g)) {
1622
+ if (match[1] !== void 0) {
1623
+ const phrase = match[1].replace(/["\\]/g, " ").trim();
1624
+ if (phrase) parts.push(`"${phrase}"`);
1625
+ continue;
1626
+ }
1627
+ for (const piece of match[2].split(/[^\p{L}\p{N}]+/u)) if (piece) parts.push(`"${piece}"`);
1628
+ }
1629
+ return parts.join(" ");
1630
+ }
1613
1631
  //#endregion
1614
1632
  //#region src/lib/mongo-schema-sync.ts
1615
1633
  const DESTRUCTIVE_OPTION_KEYS = new Set([
@@ -1738,6 +1756,7 @@ async function recreateTableImpl(host) {
1738
1756
  }
1739
1757
  async function renameTableImpl(host, oldName) {
1740
1758
  const newName = host.resolveTableName(false);
1759
+ if (!await getObjectKindImpl(host, oldName) && await getObjectKindImpl(host, newName)) return;
1741
1760
  host._log("renameTable", oldName, "→", newName);
1742
1761
  await host.db.renameCollection(oldName, newName);
1743
1762
  host.clearCollectionCache();
@@ -1901,7 +1920,8 @@ async function syncIndexesImpl(host, opts, dryRun = false) {
1901
1920
  type: mongoType,
1902
1921
  fields,
1903
1922
  weights,
1904
- ...partialFilterExpression ? { partialFilterExpression } : {}
1923
+ ...partialFilterExpression ? { partialFilterExpression } : {},
1924
+ ...index.type === "fulltext" && index.language ? { defaultLanguage: index.language } : {}
1905
1925
  });
1906
1926
  }
1907
1927
  for (const [key, index] of host._mongoIndexes.entries()) if (index.type === "text") {
@@ -1934,7 +1954,7 @@ async function syncIndexesImpl(host, opts, dryRun = false) {
1934
1954
  const fieldsMatch = local.type === "text" || objMatch(local.fields, remote.key);
1935
1955
  const weightsMatch = objMatch(local.weights || {}, remote.weights || {});
1936
1956
  const wantedCollation = indexCollation(host, local);
1937
- const optionsMatch = local.type === "text" || local.type === "unique" === (remote.unique === true) && partialFilterEqual(local.partialFilterExpression, remote.partialFilterExpression) && (sameCollation(wantedCollation, remote.collation) || !wantedCollation && sameCollation(remote.collation, await collectionDefaultCollation()));
1957
+ const optionsMatch = local.type === "text" ? textLanguage(local.defaultLanguage) === textLanguage(remote.default_language) : local.type === "unique" === (remote.unique === true) && partialFilterEqual(local.partialFilterExpression, remote.partialFilterExpression) && (sameCollation(wantedCollation, remote.collation) || !wantedCollation && sameCollation(remote.collation, await collectionDefaultCollation()));
1938
1958
  const violation = fieldsMatch && weightsMatch && optionsMatch ? void 0 : local.type === "unique" && remote.unique === true ? await findUniqueViolation(host, local, wantedCollation) : void 0;
1939
1959
  if (fieldsMatch && weightsMatch && optionsMatch) indexesToCreate.delete(remote.name);
1940
1960
  else if (violation !== void 0) {
@@ -1984,7 +2004,8 @@ async function syncIndexesImpl(host, opts, dryRun = false) {
1984
2004
  label = `create text index "${key}"`;
1985
2005
  indexOptions = {
1986
2006
  weights: value.weights,
1987
- name: key
2007
+ name: key,
2008
+ ...value.defaultLanguage ? { default_language: value.defaultLanguage } : {}
1988
2009
  };
1989
2010
  break;
1990
2011
  case "2dsphere":
@@ -2214,6 +2235,10 @@ function vectorFieldsMatch(left, right) {
2214
2235
  }
2215
2236
  return true;
2216
2237
  }
2238
+ /** A text index's language as MongoDB applies it: `english` when none is set. */
2239
+ function textLanguage(language) {
2240
+ return language ?? "english";
2241
+ }
2217
2242
  //#endregion
2218
2243
  //#region src/lib/validate-plugins.ts
2219
2244
  const validateMongoIdPlugin = (ctx, def, value) => {
@@ -2414,7 +2439,7 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2414
2439
  if (!query.controls?.$having) return !forCount && query.controls?.$skip ? void 0 : row;
2415
2440
  const stages = emptyGroupStages(query, row, forCount);
2416
2441
  const probe = buildMatchedProbe(query, searchStage, this._predicateFilterOpts);
2417
- const run = (pipeline) => wrapInvalidQuery(() => this.aggregatePipeline(pipeline).toArray());
2442
+ const run = (pipeline) => wrapInvalidQuery(() => this.aggregatePipeline(pipeline, aggregateOptions(pipeline)).toArray());
2418
2443
  const [matched, applied] = this.isInTransaction() ? [await run(probe), void 0] : await Promise.all([run(probe), stages ? run(stages) : void 0]);
2419
2444
  if (matched.length > 0) return void 0;
2420
2445
  if (!stages) return row;
@@ -2482,6 +2507,25 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2482
2507
  return true;
2483
2508
  }
2484
2509
  /**
2510
+ * Conditional aggregates (`$where`): the condition as an aggregation
2511
+ * expression inside each accumulator (`$cond`), in SQL's three-valued logic
2512
+ * (`whereToExpr`). @since 0.1.168
2513
+ */
2514
+ supportsConditionalAggregates() {
2515
+ return true;
2516
+ }
2517
+ /** `countDistinct` over a field list: `$addToSet` of the value arrays, then `$size`. @since 0.1.168 */
2518
+ supportsDistinctFieldLists() {
2519
+ return true;
2520
+ }
2521
+ /**
2522
+ * Two-level aggregates (`$from`): the inner level's grouped stages, then the
2523
+ * outer level's over their documents, in one pipeline (`allowDiskUse`). @since 0.1.168
2524
+ */
2525
+ supportsNestedAggregates() {
2526
+ return true;
2527
+ }
2528
+ /**
2485
2529
  * `$nulls` placement (since 0.1.153): a placed `$sort` / `$rowOrder` key
2486
2530
  * gets a null-or-missing flag ordered before it (`mongo-sort.ts`) — reads
2487
2531
  * then run as a pipeline with a blocking sort instead of `find().sort()`.
@@ -2802,7 +2846,8 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2802
2846
  name: index.name,
2803
2847
  type: "text",
2804
2848
  fields: Object.fromEntries(index.fields.filter((f) => !f.integer).map((f) => [f.name, "text"])),
2805
- weights: Object.fromEntries(index.fields.filter((f) => f.weight && !f.integer).map((f) => [f.name, f.weight]))
2849
+ weights: Object.fromEntries(index.fields.filter((f) => f.weight && !f.integer).map((f) => [f.name, f.weight])),
2850
+ ...index.match ? { match: index.match } : {}
2806
2851
  };
2807
2852
  if (index === defaultFulltext) defaultIndex = converted;
2808
2853
  if (!this._searchIndexesMap.has(index.name)) this._searchIndexesMap.set(index.name, converted);
@@ -127,6 +127,181 @@ function exprToMongo(node, operand) {
127
127
  default: return args.reduceRight((rest, arg) => ({ $ifNull: [arg, rest] }));
128
128
  }
129
129
  }
130
+ const TRUE_COND = { $literal: true };
131
+ const FALSE_COND = { $literal: false };
132
+ /**
133
+ * A condition's value inside an expression: a `$`-string would read as a
134
+ * field path and an object as an expression object — both stay literals.
135
+ */
136
+ function valueOf(value) {
137
+ return value !== null && typeof value === "object" && !(value instanceof Date) ? { $literal: value } : literal(value);
138
+ }
139
+ const not = (cond) => ({ $not: [cond] });
140
+ const allOf = (items) => items.length === 0 ? TRUE_COND : items.length === 1 ? items[0] : { $and: items };
141
+ const anyOf = (items) => items.length === 0 ? FALSE_COND : items.length === 1 ? items[0] : { $or: items };
142
+ /** `test(x)` for a scalar `x`; for an array, true when ANY element passes (the query filter's array reading). */
143
+ function eachValue(x, test) {
144
+ return { $cond: [
145
+ { $isArray: x },
146
+ { $anyElementTrue: [{ $map: {
147
+ input: x,
148
+ as: "v",
149
+ in: test("$$v")
150
+ } }] },
151
+ test(x)
152
+ ] };
153
+ }
154
+ /** A `$regex` value — a RegExp, a `/pattern/flags` string or a bare pattern — as pattern + flags. */
155
+ function parseRegexString(value) {
156
+ if (value instanceof RegExp) return {
157
+ pattern: value.source,
158
+ flags: value.flags
159
+ };
160
+ const str = String(value);
161
+ const match = str.match(/^\/(.+)\/([gimsuy]*)$/);
162
+ if (match) return {
163
+ pattern: match[1],
164
+ flags: match[2]
165
+ };
166
+ return {
167
+ pattern: str,
168
+ flags: ""
169
+ };
170
+ }
171
+ /** `$regexMatch` options: the PCRE flags it accepts (`g` / `u` / `y` mean nothing there). */
172
+ function regexParts(value) {
173
+ const { pattern, flags } = parseRegexString(value);
174
+ const options = flags.replace(/[^imsx]/g, "");
175
+ return options ? {
176
+ regex: pattern,
177
+ options
178
+ } : { regex: pattern };
179
+ }
180
+ /**
181
+ * A pattern over the DECIMAL TEXT of an integer operand (`INTEGER_REGEX_OP`)
182
+ * — the query filter's and a `$where` condition's rendering. The inner
183
+ * `$convert` to long is required (a double prints as `1e+16`); a
184
+ * non-numeric / missing value converts to null → `$regexMatch` is false.
185
+ */
186
+ function integerRegexExpr(input, value) {
187
+ return { $regexMatch: {
188
+ input: { $toString: { $convert: {
189
+ input,
190
+ to: "long",
191
+ onError: null,
192
+ onNull: null
193
+ } } },
194
+ ...regexParts(value)
195
+ } };
196
+ }
197
+ /** A pattern match: a string value (or an array holding one) that matches; any other value does not. */
198
+ function regexCond(x, value) {
199
+ const parts = regexParts(value);
200
+ return eachValue(x, (v) => ({ $cond: [
201
+ { $eq: [{ $type: v }, "string"] },
202
+ { $regexMatch: {
203
+ input: v,
204
+ ...parts
205
+ } },
206
+ false
207
+ ] }));
208
+ }
209
+ /**
210
+ * `x = value` as the query filter reads it: `null` matches null, missing and
211
+ * an array holding null; a RegExp matches like `$regex`; any other value
212
+ * matches an equal value or an array holding one.
213
+ */
214
+ function eqCond(x, value) {
215
+ if (value === null || value === void 0) return { $cond: [
216
+ { $isArray: x },
217
+ { $in: [null, x] },
218
+ isNullExpr(x)
219
+ ] };
220
+ if (value instanceof RegExp) return regexCond(x, value);
221
+ const v = valueOf(value);
222
+ if (Array.isArray(value)) return { $eq: [x, v] };
223
+ return { $cond: [
224
+ { $isArray: x },
225
+ { $in: [v, x] },
226
+ { $eq: [x, v] }
227
+ ] };
228
+ }
229
+ /** The comparison-class test of a range operand: only values of the operand's BSON class compare. */
230
+ function sameClass(v, value) {
231
+ if (typeof value === "number" || typeof value === "bigint") return { $isNumber: v };
232
+ return { $eq: [{ $type: v }, { $type: valueOf(value) }] };
233
+ }
234
+ /**
235
+ * `x <op> value` for `$gt` / `$gte` / `$lt` / `$lte` as the query filter reads
236
+ * it: only a value of the operand's type class compares (no cross-type order),
237
+ * an array matches when an element does; against `null`, `$gte` / `$lte` are
238
+ * `= null` and `$gt` / `$lt` match nothing.
239
+ */
240
+ function rangeCond(x, op, value) {
241
+ if (value === null || value === void 0) return op === "$gte" || op === "$lte" ? eqCond(x, null) : FALSE_COND;
242
+ const v = valueOf(value);
243
+ return eachValue(x, (el) => ({ $and: [sameClass(el, value), { [op]: [el, v] }] }));
244
+ }
245
+ function comparisonCond(x, op, value) {
246
+ switch (op) {
247
+ case "$eq": return eqCond(x, value);
248
+ case "$ne": return not(eqCond(x, value));
249
+ case "$exists": return value ? not(eqCond(x, null)) : eqCond(x, null);
250
+ case "$in":
251
+ case "$nin": {
252
+ const any = anyOf((Array.isArray(value) ? value : [value]).map((v) => eqCond(x, v)));
253
+ return op === "$in" ? any : not(any);
254
+ }
255
+ case "$regex": return regexCond(x, value);
256
+ case _atscript_db.INTEGER_REGEX_OP: return integerRegexExpr(x, value);
257
+ case "$gt":
258
+ case "$gte":
259
+ case "$lt":
260
+ case "$lte": return rangeCond(x, op, value);
261
+ default: throw new _atscript_db.DbError("INVALID_QUERY", [{
262
+ path: "$select",
263
+ message: `Operator "${op}" is not supported in a $where condition`
264
+ }]);
265
+ }
266
+ }
267
+ const condVisitor = {
268
+ comparison: (field, op, value) => comparisonCond(`$${field}`, op, value),
269
+ and: (children) => allOf(children),
270
+ or: (children) => anyOf(children),
271
+ not: (child) => not(child),
272
+ relation: (field) => {
273
+ throw new _atscript_db.DbError("INVALID_QUERY", [{
274
+ path: field,
275
+ message: "Relational predicates are not supported in a $where condition"
276
+ }]);
277
+ }
278
+ };
279
+ /**
280
+ * The condition of a conditional aggregate (`$where`: a uniqu filter,
281
+ * translated — physical names, storage values) as an aggregation expression
282
+ * that holds exactly for the documents the same filter returns on this
283
+ * adapter (since 0.1.168) — `aggregate(f, x | w)` aggregates what
284
+ * `aggregate(f ∧ w, x)` does:
285
+ *
286
+ * - `= v` / `$in` match an equal value or an array holding one; `= null`
287
+ * matches null, missing and an array holding null;
288
+ * - `$ne` / `$nin` / `$not` are the plain negation (so they match null and
289
+ * missing values);
290
+ * - `$gt` / `$gte` / `$lt` / `$lte` compare values of the operand's type class
291
+ * only (an array: any element); `$gt` / `$lt` against `null` match nothing;
292
+ * - `$exists` is "holds a value"; `$regex` → `$regexMatch` over string values
293
+ * (MongoDB 4.2+);
294
+ * - an empty `$or` / `$in` is false, an empty `$and` / `$nin` true.
295
+ *
296
+ * Collation: values compare byte-wise — like the filter of a grouped
297
+ * aggregate on this adapter, whose pipeline runs without an operation-wide
298
+ * collation. Never returns a bare boolean (a constant is `{ $literal: … }`).
299
+ *
300
+ * @since 0.1.168
301
+ */
302
+ function whereToExpr(where) {
303
+ return (0, _atscript_db.walkFilter)(where, condVisitor) ?? TRUE_COND;
304
+ }
130
305
  //#endregion
131
306
  //#region src/lib/mongo-sort.ts
132
307
  /**
@@ -247,22 +422,6 @@ function correlate(prefix, pairs) {
247
422
  //#endregion
248
423
  //#region src/lib/mongo-filter.ts
249
424
  const EMPTY = {};
250
- function parseRegexString(value) {
251
- if (value instanceof RegExp) return {
252
- pattern: value.source,
253
- flags: value.flags
254
- };
255
- const str = String(value);
256
- const match = str.match(/^\/(.+)\/([gimsuy]*)$/);
257
- if (match) return {
258
- pattern: match[1],
259
- flags: match[2]
260
- };
261
- return {
262
- pattern: str,
263
- flags: ""
264
- };
265
- }
266
425
  /**
267
426
  * Earth radius in meters used by MongoDB's `$centerSphere` radians conversion
268
427
  * (Mongo documents dividing by 6378.1 km).
@@ -279,20 +438,7 @@ const mongoVisitor = {
279
438
  $options: flags
280
439
  } } : { [field]: { $regex: pattern } };
281
440
  }
282
- if (op === _atscript_db.INTEGER_REGEX_OP) {
283
- const { pattern, flags } = parseRegexString(value);
284
- const options = flags.replace(/[^imsx]/g, "");
285
- return { $expr: { $regexMatch: {
286
- input: { $toString: { $convert: {
287
- input: `$${field}`,
288
- to: "long",
289
- onError: null,
290
- onNull: null
291
- } } },
292
- regex: pattern,
293
- ...options ? { options } : {}
294
- } } };
295
- }
441
+ if (op === _atscript_db.INTEGER_REGEX_OP) return { $expr: integerRegexExpr(`$${field}`, value) };
296
442
  if (op === "$geoWithin") {
297
443
  const { center, radius } = value;
298
444
  return { [field]: { $geoWithin: { $centerSphere: [center, radius / EARTH_RADIUS_M] } } };
@@ -588,7 +734,10 @@ function stagesOf(plan, unset) {
588
734
  * skip null / missing values);
589
735
  * - `countDistinct(f)` → `{ $addToSet: { $ifNull: [f, "$$REMOVE"] } }`, a
590
736
  * SET of the non-null values (`$$REMOVE` adds nothing) the caller turns
591
- * into its size with {@link distinctCountExpr}.
737
+ * into its size with {@link distinctCountExpr}; over a field list
738
+ * (`countDistinct` only — the caller rejects any other `fn`), the SET of
739
+ * the rows' value arrays, a row with any null / missing field (or failing
740
+ * `where`) adding nothing.
592
741
  *
593
742
  * `where` (a conditional aggregate's row predicate, an aggregation
594
743
  * expression) swaps the source for `{ $cond: [where, src, null] }` — the
@@ -596,25 +745,31 @@ function stagesOf(plan, unset) {
596
745
  * the counts `{ $sum: { $cond: [where (and not null), 1, 0] } }`.
597
746
  *
598
747
  * @param fn - The aggregate function (re-asserted: `INVALID_QUERY` when unknown).
599
- * @param src - The source operand (`"$path"`), or `"*"` for `count(*)`.
748
+ * @param src - The source operand (`"$path"` or an expression), `"*"` for
749
+ * `count(*)`, or a list of `"$path"` operands for `countDistinct`.
600
750
  * @param where - Row predicate of a conditional aggregate.
601
751
  * @param path - Error path of the re-assertion.
602
752
  */
603
753
  function buildAccumulator(fn, src, where, path) {
604
754
  (0, _atscript_db_agg.assertAggregateFn)(fn, path);
755
+ if (Array.isArray(src)) return { $addToSet: { $cond: [
756
+ { $and: [...src.map((field) => notNullExpr(field)), ...where !== void 0 ? [where] : []] },
757
+ src,
758
+ "$$REMOVE"
759
+ ] } };
605
760
  if (fn === "count") {
606
- if (src === "*") return { $sum: where ? { $cond: [
761
+ if (src === "*") return { $sum: where !== void 0 ? { $cond: [
607
762
  where,
608
763
  1,
609
764
  0
610
765
  ] } : 1 };
611
766
  return { $sum: { $cond: [
612
- where ? { $and: [where, notNullExpr(src)] } : notNullExpr(src),
767
+ where !== void 0 ? { $and: [where, notNullExpr(src)] } : notNullExpr(src),
613
768
  1,
614
769
  0
615
770
  ] } };
616
771
  }
617
- const value = where ? { $cond: [
772
+ const value = where !== void 0 ? { $cond: [
618
773
  where,
619
774
  src,
620
775
  null
@@ -690,12 +845,6 @@ Object.defineProperty(exports, "mongoFilterStages", {
690
845
  return mongoFilterStages;
691
846
  }
692
847
  });
693
- Object.defineProperty(exports, "notNullExpr", {
694
- enumerable: true,
695
- get: function() {
696
- return notNullExpr;
697
- }
698
- });
699
848
  Object.defineProperty(exports, "orNull", {
700
849
  enumerable: true,
701
850
  get: function() {
@@ -726,3 +875,9 @@ Object.defineProperty(exports, "sortStages", {
726
875
  return sortStages;
727
876
  }
728
877
  });
878
+ Object.defineProperty(exports, "whereToExpr", {
879
+ enumerable: true,
880
+ get: function() {
881
+ return whereToExpr;
882
+ }
883
+ });