@atscript/db-mongo 0.1.183 → 0.1.185

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
@@ -385,20 +385,20 @@ var CollectionPatcher = class {
385
385
  const topLevelArray = flatType?.metadata?.get("db.__topLevelArray");
386
386
  const isObjectValue = typeof value === "object" && value !== null && !Array.isArray(value);
387
387
  if (isObjectValue && topLevelArray && !flatType?.metadata?.has("db.json")) this.parseArrayPatch(key, value, flatType);
388
- else if (isObjectValue && flatType?.metadata?.get("db.patch.strategy") === "merge") this.flattenPayload(value, key);
389
- else if (isObjectValue && flatType?.type.kind === "object" && !flatType.metadata?.has("db.json")) this._flattenReplaceObject(value, key, flatType);
388
+ else if (isObjectValue && this.collection.mergePaths.has(key)) this.flattenPayload(value, key);
389
+ else if (isObjectValue && (0, _atscript_db.storedObjectType)(flatType) && !flatType.metadata?.has("db.json")) this._flattenReplaceObject(value, key, flatType);
390
390
  else if (key !== "_id") this._setLeaf(key, value, flatType);
391
391
  }
392
392
  return this.updatePipeline;
393
393
  }
394
394
  /**
395
- * Walk the schema's props for a replace-strategy nested object so omitted
396
- * optional children become explicit nulls (parity with SQL `column = NULL`).
397
- * Required-missing leaves are caught earlier by the strict validator.
395
+ * Walk the schema's props for a replace-strategy nested object (a `T | null`
396
+ * one included, `storedObjectType`) so omitted optional children become
397
+ * explicit nulls (parity with SQL `column = NULL`). Required-missing leaves
398
+ * are caught earlier by the strict validator.
398
399
  */
399
400
  _flattenReplaceObject(value, prefix, flatType) {
400
- const propsMap = flatType.type.props;
401
- for (const [propKey, propType] of propsMap) {
401
+ for (const [propKey, propType] of (0, _atscript_db.storedObjectType)(flatType).type.props) {
402
402
  const childKey = `${prefix}.${propKey}`;
403
403
  const childValue = value[propKey];
404
404
  if (childValue === void 0) {
@@ -407,15 +407,17 @@ var CollectionPatcher = class {
407
407
  }
408
408
  const childIsObject = typeof childValue === "object" && childValue !== null && !Array.isArray(childValue);
409
409
  const propIsJson = propType.metadata?.has("db.json");
410
- const propIsMerge = propType.metadata?.get("db.patch.strategy") === "merge";
411
410
  const childFlatType = this.collection.flatMap.get(childKey);
412
411
  if (childIsObject && !propIsJson && childFlatType?.metadata?.get("db.__topLevelArray")) {
413
412
  this.parseArrayPatch(childKey, childValue, childFlatType);
414
413
  continue;
415
414
  }
416
- if (childIsObject && propType.type.kind === "object" && !propIsJson) {
417
- if (propIsMerge) this.flattenPayload(childValue, childKey);
418
- else this._flattenReplaceObject(childValue, childKey, propType);
415
+ if (childIsObject && this.collection.mergePaths.has(childKey)) {
416
+ this.flattenPayload(childValue, childKey);
417
+ continue;
418
+ }
419
+ if (childIsObject && (0, _atscript_db.storedObjectType)(propType) && !propIsJson) {
420
+ this._flattenReplaceObject(childValue, childKey, propType);
419
421
  continue;
420
422
  }
421
423
  this._setLeaf(childKey, childValue, propType);
@@ -442,8 +444,8 @@ var CollectionPatcher = class {
442
444
  return;
443
445
  }
444
446
  this._remove(key, toRemove, keys, flatType);
445
- this._update(key, toUpdate, keys, flatType);
446
- this._upsert(key, toUpsert, keys, flatType);
447
+ this._update(key, toUpdate, keys);
448
+ this._upsert(key, toUpsert, keys);
447
449
  this._insert(key, toInsert, keys, flatType);
448
450
  }
449
451
  /**
@@ -545,13 +547,13 @@ var CollectionPatcher = class {
545
547
  * or append when none has it
546
548
  * - key-less → append unless an equal element is stored
547
549
  */
548
- _upsert(key, input, keys, flatType) {
550
+ _upsert(key, input, keys) {
549
551
  if (!input?.length) return;
550
552
  if (keys.length === 0) {
551
553
  this._appendAbsent(key, input);
552
554
  return;
553
555
  }
554
- const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
556
+ const mergeStrategy = this.collection.mergePaths.has(key);
555
557
  this._appendUnless(key, input, this._keyStored(keys), { $map: {
556
558
  input: "$$value",
557
559
  as: "el",
@@ -569,9 +571,9 @@ var CollectionPatcher = class {
569
571
  * 0.1.180, as on every other adapter; before, the items were added to
570
572
  * the array as a set union)
571
573
  */
572
- _update(key, input, keys, flatType) {
574
+ _update(key, input, keys) {
573
575
  if (!input?.length || keys.length === 0) return;
574
- const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
576
+ const mergeStrategy = this.collection.mergePaths.has(key);
575
577
  this._set(key, { $reduce: {
576
578
  input: literal(input),
577
579
  initialValue: { $ifNull: [`$${key}`, []] },
@@ -1274,13 +1276,6 @@ function filterOptionsOf(host) {
1274
1276
  * name of its own (a dynamic Atlas mapping) is listed as `DEFAULT`. The vector
1275
1277
  * default is the first vector index.
1276
1278
  */
1277
- /** Classic `$text` relevance order: `textScore` descending, `_id` breaking ties (since 0.1.165). */
1278
- const RELEVANCE_SORT = { $sort: {
1279
- _score: -1,
1280
- _id: 1
1281
- } };
1282
- /** The order of an unranked search (`$rank: false`, since 0.1.175): the primary key. */
1283
- const UNRANKED_SORT = { $sort: { _id: 1 } };
1284
1279
  function getSearchIndexesImpl(host) {
1285
1280
  const result = [];
1286
1281
  const indexes = host.getMongoSearchIndexes();
@@ -1337,7 +1332,7 @@ function requireSearchStage(host, text, indexName, controls) {
1337
1332
  * an unresolvable one throws exactly as the leaf path does.
1338
1333
  *
1339
1334
  * `classicText` is deliberately dropped: it only drives the leaf runner's
1340
- * `_score` projection and relevance `$sort`, and no per-document score
1335
+ * relevance order (the `textScore` it sorts by), and no per-document score
1341
1336
  * survives `$group`. See `resolveAggregateSearch` in `@atscript/db/agg` for
1342
1337
  * the normative cross-adapter contract.
1343
1338
  */
@@ -1362,17 +1357,29 @@ async function searchWithCountImpl(host, text, query, indexName) {
1362
1357
  * orders by `_id` instead (an Atlas `$search` included).
1363
1358
  */
1364
1359
  function textRunOptions(plan, query) {
1365
- if (query.controls?.$rank === false) return { defaultSort: UNRANKED_SORT };
1366
- return plan.classicText ? {
1367
- classicText: true,
1368
- defaultSort: RELEVANCE_SORT
1369
- } : {};
1360
+ if (query.controls?.$rank === false) return { defaultOrder: UNRANKED_ORDER };
1361
+ return plan.classicText ? { defaultOrder: RELEVANCE_ORDER } : {};
1370
1362
  }
1371
1363
  /**
1372
- * Field the `vectorSearchScore` rides in through the pipeline. Renamed to the
1373
- * public `$score` after fetch — a field name cannot start with `$`.
1364
+ * Field a search score rides in through the pipeline: the `vectorSearchScore`
1365
+ * (renamed to the public `$score` after fetch — a field name cannot start
1366
+ * with `$`) or the `textScore` of a relevance order (dropped from the rows).
1374
1367
  */
1375
1368
  const SCORE_FIELD = "__atscript_score";
1369
+ /**
1370
+ * Classic `$text` relevance order: `textScore` descending, `_id` breaking ties
1371
+ * (since 0.1.165). The score is dropped after `$skip` / `$limit`, so a row
1372
+ * carries no score field (since 0.1.185; before, rows carried `_score`).
1373
+ */
1374
+ const RELEVANCE_ORDER = {
1375
+ stages: [{ $addFields: { [SCORE_FIELD]: { $meta: "textScore" } } }, { $sort: {
1376
+ [SCORE_FIELD]: -1,
1377
+ _id: 1
1378
+ } }],
1379
+ cleanup: { $project: { [SCORE_FIELD]: 0 } }
1380
+ };
1381
+ /** The order of an unranked search (`$rank: false`, since 0.1.175): the primary key. */
1382
+ const UNRANKED_ORDER = { stages: [{ $sort: { _id: 1 } }] };
1376
1383
  /** Vector search via $vectorSearch aggregation stage. */
1377
1384
  async function vectorSearchImpl(host, vector, query, indexName) {
1378
1385
  const controls = query.controls || {};
@@ -1400,15 +1407,12 @@ async function vectorSearchWithCountImpl(host, vector, query, indexName) {
1400
1407
  /**
1401
1408
  * The stages right after `$vectorSearch`: its score into {@link SCORE_FIELD}
1402
1409
  * (the `$meta` is read here, ahead of any `$facet`) and, with a threshold,
1403
- * into `_score` — kept for compatibility — with the `$match` on it.
1410
+ * the `$match` on it.
1404
1411
  */
1405
1412
  function vectorScoreStages(threshold) {
1406
- const score = { $meta: "vectorSearchScore" };
1407
- if (threshold === void 0) return [{ $addFields: { [SCORE_FIELD]: score } }];
1408
- return [{ $addFields: {
1409
- _score: score,
1410
- [SCORE_FIELD]: score
1411
- } }, { $match: { _score: { $gte: threshold } } }];
1413
+ const stages = [{ $addFields: { [SCORE_FIELD]: { $meta: "vectorSearchScore" } } }];
1414
+ if (threshold !== void 0) stages.push({ $match: { [SCORE_FIELD]: { $gte: threshold } } });
1415
+ return stages;
1412
1416
  }
1413
1417
  /**
1414
1418
  * Field name `$geoNear` writes the computed distance into. Renamed to the
@@ -1797,16 +1801,19 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
1797
1801
  index
1798
1802
  };
1799
1803
  }
1804
+ /** The order of a search: an explicit `$sort` (with its `$nulls` placement flags) replaces the default. */
1805
+ function searchOrder(controls, defaultOrder) {
1806
+ const explicit = require_mongo_accumulator.sortStages(controls);
1807
+ return explicit.stages.length > 0 || !defaultOrder ? explicit : defaultOrder;
1808
+ }
1800
1809
  /** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
1801
- async function runSearchPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1810
+ async function runSearchPipeline(host, stage, query, label, { vector, defaultOrder, filterStages } = {}) {
1802
1811
  const controls = query.controls || {};
1803
1812
  const pipeline = [stage];
1804
1813
  if (vector) pipeline.push(...vectorScoreStages(vector.threshold));
1805
- else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1806
1814
  pipeline.push(...filterStages ?? require_mongo_accumulator.mongoFilterStages(query.filter, filterOptionsOf(host)));
1807
- const { stages: sorted, cleanup } = require_mongo_accumulator.sortStages(controls);
1808
- if (sorted.length > 0) pipeline.push(...sorted);
1809
- else if (defaultSort) pipeline.push(defaultSort);
1815
+ const { stages: sorted, cleanup } = searchOrder(controls, defaultOrder);
1816
+ pipeline.push(...sorted);
1810
1817
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
1811
1818
  if (controls.$limit) pipeline.push({ $limit: controls.$limit });
1812
1819
  else pipeline.push({ $limit: 1e3 });
@@ -1825,13 +1832,11 @@ async function runSearchPipeline(host, stage, query, label, { vector, classicTex
1825
1832
  * `count: total` — the same counts `$$SEARCH_META` reports), concurrently
1826
1833
  * outside a transaction.
1827
1834
  */
1828
- async function runSearchWithCountPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1835
+ async function runSearchWithCountPipeline(host, stage, query, label, { vector, defaultOrder, filterStages } = {}) {
1829
1836
  const controls = query.controls || {};
1830
- const preStages = [];
1831
- if (vector) preStages.push(...vectorScoreStages(vector.threshold));
1832
- else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1833
- const { stages: dataStages, cleanup } = require_mongo_accumulator.sortStages(controls);
1834
- if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
1837
+ const preStages = vector ? vectorScoreStages(vector.threshold) : [];
1838
+ const { stages: sorted, cleanup } = searchOrder(controls, defaultOrder);
1839
+ const dataStages = [...sorted];
1835
1840
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1836
1841
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1837
1842
  if (cleanup) dataStages.push(cleanup);
@@ -2609,8 +2614,8 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2609
2614
  _hasExplicitId = false;
2610
2615
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
2611
2616
  _pendingUniqueFields = [];
2612
- /** {@link _patcherFlatMap}'s memo. */
2613
- _patcherFlatMapMemo;
2617
+ /** {@link _patcherMaps}' memo. */
2618
+ _patcherMapsMemo;
2614
2619
  constructor(db, client, options = {}) {
2615
2620
  super();
2616
2621
  this.db = db;
@@ -2926,7 +2931,7 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2926
2931
  /** Returns the context object used by CollectionPatcher. */
2927
2932
  getPatcherContext() {
2928
2933
  return {
2929
- flatMap: this._patcherFlatMap(),
2934
+ ...this._patcherMaps(),
2930
2935
  prepareId: (id) => this.prepareIdFromIdType(id),
2931
2936
  createValidator: (opts) => this._table.createValidator(opts)
2932
2937
  };
@@ -2936,21 +2941,26 @@ var MongoAdapter = class MongoAdapter extends _atscript_db.BaseDbAdapter {
2936
2941
  * with `@db.column` names already applied (`translatePatchKeys`), so a
2937
2942
  * renamed union / `@db.json` field is found — and replaced, not merged —
2938
2943
  * under its stored name. Derived fields are left out (they map to their
2939
- * source's path). Built once per flat map.
2944
+ * source's path). The merge-strategy paths are keyed the same way. Built
2945
+ * once per flat map.
2940
2946
  */
2941
- _patcherFlatMap() {
2947
+ _patcherMaps() {
2942
2948
  const src = this._table.flatMap;
2943
- let memo = this._patcherFlatMapMemo;
2949
+ let memo = this._patcherMapsMemo;
2944
2950
  if (memo?.src !== src) {
2945
2951
  const meta = this._table.getMetadata();
2946
2952
  const map = /* @__PURE__ */ new Map();
2947
2953
  for (const [path, type] of src) if (!meta.derivedFields.has(path)) map.set(meta.documentPath(path), type);
2948
- memo = this._patcherFlatMapMemo = {
2954
+ const mergePaths = new Set([...meta.mergePaths].map((path) => meta.documentPath(path)));
2955
+ memo = this._patcherMapsMemo = {
2949
2956
  src,
2950
- map
2957
+ maps: {
2958
+ flatMap: map,
2959
+ mergePaths
2960
+ }
2951
2961
  };
2952
2962
  }
2953
- return memo.map;
2963
+ return memo.maps;
2954
2964
  }
2955
2965
  async nativePatch(filter, patch, ops, expectedVersion, opts) {
2956
2966
  const mongoFilter = await this._buildCasFilter(filter, expectedVersion, "nativePatch");
package/dist/index.d.cts CHANGED
@@ -11,6 +11,8 @@ import { AggregateFn, BucketUnit } from "@uniqu/core";
11
11
  */
12
12
  interface TCollectionPatcherContext {
13
13
  flatMap: Map<string, TAtscriptAnnotatedType>;
14
+ /** The document paths whose merge strategy applies (`TableMetadata.mergePaths`). */
15
+ mergePaths: ReadonlySet<string>;
14
16
  prepareId(id: any): any;
15
17
  createValidator(opts?: Partial<TValidatorOptions>): Validator<any>;
16
18
  }
@@ -94,9 +96,10 @@ declare class CollectionPatcher {
94
96
  */
95
97
  private flattenPayload;
96
98
  /**
97
- * Walk the schema's props for a replace-strategy nested object so omitted
98
- * optional children become explicit nulls (parity with SQL `column = NULL`).
99
- * Required-missing leaves are caught earlier by the strict validator.
99
+ * Walk the schema's props for a replace-strategy nested object (a `T | null`
100
+ * one included, `storedObjectType`) so omitted optional children become
101
+ * explicit nulls (parity with SQL `column = NULL`). Required-missing leaves
102
+ * are caught earlier by the strict validator.
100
103
  */
101
104
  private _flattenReplaceObject;
102
105
  /**
@@ -345,8 +348,8 @@ declare class MongoAdapter extends BaseDbAdapter {
345
348
  protected _hasExplicitId: boolean;
346
349
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
347
350
  private _pendingUniqueFields;
348
- /** {@link _patcherFlatMap}'s memo. */
349
- private _patcherFlatMapMemo?;
351
+ /** {@link _patcherMaps}' memo. */
352
+ private _patcherMapsMemo?;
350
353
  constructor(db: Db, client?: MongoClient | undefined, options?: TMongoAdapterOptions);
351
354
  private get _client();
352
355
  /** Every adapter over this client (or database handle) shares one session (since 0.1.128). */
@@ -514,9 +517,10 @@ declare class MongoAdapter extends BaseDbAdapter {
514
517
  * with `@db.column` names already applied (`translatePatchKeys`), so a
515
518
  * renamed union / `@db.json` field is found — and replaced, not merged —
516
519
  * under its stored name. Derived fields are left out (they map to their
517
- * source's path). Built once per flat map.
520
+ * source's path). The merge-strategy paths are keyed the same way. Built
521
+ * once per flat map.
518
522
  */
519
- private _patcherFlatMap;
523
+ private _patcherMaps;
520
524
  nativePatch(filter: FilterExpr, patch: unknown, ops?: TFieldOps, expectedVersion?: number, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
521
525
  /**
522
526
  * `updateMany` with array operators (since 0.1.182): the pipeline
package/dist/index.d.mts CHANGED
@@ -11,6 +11,8 @@ import { TAtscriptAnnotatedType, TMetadataMap, TValidatorOptions, TValidatorPlug
11
11
  */
12
12
  interface TCollectionPatcherContext {
13
13
  flatMap: Map<string, TAtscriptAnnotatedType>;
14
+ /** The document paths whose merge strategy applies (`TableMetadata.mergePaths`). */
15
+ mergePaths: ReadonlySet<string>;
14
16
  prepareId(id: any): any;
15
17
  createValidator(opts?: Partial<TValidatorOptions>): Validator<any>;
16
18
  }
@@ -94,9 +96,10 @@ declare class CollectionPatcher {
94
96
  */
95
97
  private flattenPayload;
96
98
  /**
97
- * Walk the schema's props for a replace-strategy nested object so omitted
98
- * optional children become explicit nulls (parity with SQL `column = NULL`).
99
- * Required-missing leaves are caught earlier by the strict validator.
99
+ * Walk the schema's props for a replace-strategy nested object (a `T | null`
100
+ * one included, `storedObjectType`) so omitted optional children become
101
+ * explicit nulls (parity with SQL `column = NULL`). Required-missing leaves
102
+ * are caught earlier by the strict validator.
100
103
  */
101
104
  private _flattenReplaceObject;
102
105
  /**
@@ -345,8 +348,8 @@ declare class MongoAdapter extends BaseDbAdapter {
345
348
  protected _hasExplicitId: boolean;
346
349
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
347
350
  private _pendingUniqueFields;
348
- /** {@link _patcherFlatMap}'s memo. */
349
- private _patcherFlatMapMemo?;
351
+ /** {@link _patcherMaps}' memo. */
352
+ private _patcherMapsMemo?;
350
353
  constructor(db: Db, client?: MongoClient | undefined, options?: TMongoAdapterOptions);
351
354
  private get _client();
352
355
  /** Every adapter over this client (or database handle) shares one session (since 0.1.128). */
@@ -514,9 +517,10 @@ declare class MongoAdapter extends BaseDbAdapter {
514
517
  * with `@db.column` names already applied (`translatePatchKeys`), so a
515
518
  * renamed union / `@db.json` field is found — and replaced, not merged —
516
519
  * under its stored name. Derived fields are left out (they map to their
517
- * source's path). Built once per flat map.
520
+ * source's path). The merge-strategy paths are keyed the same way. Built
521
+ * once per flat map.
518
522
  */
519
- private _patcherFlatMap;
523
+ private _patcherMaps;
520
524
  nativePatch(filter: FilterExpr, patch: unknown, ops?: TFieldOps, expectedVersion?: number, opts?: TDbUpdateOptions): Promise<TDbUpdateResult>;
521
525
  /**
522
526
  * `updateMany` with array operators (since 0.1.182): the pipeline
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
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-CFVRBDiw.mjs";
2
2
  import { t as dynamicSearchEncryptedMessage } from "./search-messages-mQSpJ4GD.mjs";
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, parseDefaultLiteral, queryReadColumns, relationStaticFilter, resolveDesignType, searchIndexNotFoundMessage, searchTermInteger, tableNameOf, translateQueryTree, uniqueKeyTuple, unknownWithRelation, vectorIndexNotFoundMessage } from "@atscript/db";
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, parseDefaultLiteral, queryReadColumns, relationStaticFilter, resolveDesignType, searchIndexNotFoundMessage, searchTermInteger, storedObjectType, tableNameOf, translateQueryTree, uniqueKeyTuple, unknownWithRelation, vectorIndexNotFoundMessage } from "@atscript/db";
4
4
  import { MongoClient, ObjectId } from "mongodb";
5
5
  import { resolveAggregateSearch } from "@atscript/db/agg";
6
6
  //#region src/lib/path-utils.ts
@@ -384,20 +384,20 @@ var CollectionPatcher = class {
384
384
  const topLevelArray = flatType?.metadata?.get("db.__topLevelArray");
385
385
  const isObjectValue = typeof value === "object" && value !== null && !Array.isArray(value);
386
386
  if (isObjectValue && topLevelArray && !flatType?.metadata?.has("db.json")) this.parseArrayPatch(key, value, flatType);
387
- else if (isObjectValue && flatType?.metadata?.get("db.patch.strategy") === "merge") this.flattenPayload(value, key);
388
- else if (isObjectValue && flatType?.type.kind === "object" && !flatType.metadata?.has("db.json")) this._flattenReplaceObject(value, key, flatType);
387
+ else if (isObjectValue && this.collection.mergePaths.has(key)) this.flattenPayload(value, key);
388
+ else if (isObjectValue && storedObjectType(flatType) && !flatType.metadata?.has("db.json")) this._flattenReplaceObject(value, key, flatType);
389
389
  else if (key !== "_id") this._setLeaf(key, value, flatType);
390
390
  }
391
391
  return this.updatePipeline;
392
392
  }
393
393
  /**
394
- * Walk the schema's props for a replace-strategy nested object so omitted
395
- * optional children become explicit nulls (parity with SQL `column = NULL`).
396
- * Required-missing leaves are caught earlier by the strict validator.
394
+ * Walk the schema's props for a replace-strategy nested object (a `T | null`
395
+ * one included, `storedObjectType`) so omitted optional children become
396
+ * explicit nulls (parity with SQL `column = NULL`). Required-missing leaves
397
+ * are caught earlier by the strict validator.
397
398
  */
398
399
  _flattenReplaceObject(value, prefix, flatType) {
399
- const propsMap = flatType.type.props;
400
- for (const [propKey, propType] of propsMap) {
400
+ for (const [propKey, propType] of storedObjectType(flatType).type.props) {
401
401
  const childKey = `${prefix}.${propKey}`;
402
402
  const childValue = value[propKey];
403
403
  if (childValue === void 0) {
@@ -406,15 +406,17 @@ var CollectionPatcher = class {
406
406
  }
407
407
  const childIsObject = typeof childValue === "object" && childValue !== null && !Array.isArray(childValue);
408
408
  const propIsJson = propType.metadata?.has("db.json");
409
- const propIsMerge = propType.metadata?.get("db.patch.strategy") === "merge";
410
409
  const childFlatType = this.collection.flatMap.get(childKey);
411
410
  if (childIsObject && !propIsJson && childFlatType?.metadata?.get("db.__topLevelArray")) {
412
411
  this.parseArrayPatch(childKey, childValue, childFlatType);
413
412
  continue;
414
413
  }
415
- if (childIsObject && propType.type.kind === "object" && !propIsJson) {
416
- if (propIsMerge) this.flattenPayload(childValue, childKey);
417
- else this._flattenReplaceObject(childValue, childKey, propType);
414
+ if (childIsObject && this.collection.mergePaths.has(childKey)) {
415
+ this.flattenPayload(childValue, childKey);
416
+ continue;
417
+ }
418
+ if (childIsObject && storedObjectType(propType) && !propIsJson) {
419
+ this._flattenReplaceObject(childValue, childKey, propType);
418
420
  continue;
419
421
  }
420
422
  this._setLeaf(childKey, childValue, propType);
@@ -441,8 +443,8 @@ var CollectionPatcher = class {
441
443
  return;
442
444
  }
443
445
  this._remove(key, toRemove, keys, flatType);
444
- this._update(key, toUpdate, keys, flatType);
445
- this._upsert(key, toUpsert, keys, flatType);
446
+ this._update(key, toUpdate, keys);
447
+ this._upsert(key, toUpsert, keys);
446
448
  this._insert(key, toInsert, keys, flatType);
447
449
  }
448
450
  /**
@@ -544,13 +546,13 @@ var CollectionPatcher = class {
544
546
  * or append when none has it
545
547
  * - key-less → append unless an equal element is stored
546
548
  */
547
- _upsert(key, input, keys, flatType) {
549
+ _upsert(key, input, keys) {
548
550
  if (!input?.length) return;
549
551
  if (keys.length === 0) {
550
552
  this._appendAbsent(key, input);
551
553
  return;
552
554
  }
553
- const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
555
+ const mergeStrategy = this.collection.mergePaths.has(key);
554
556
  this._appendUnless(key, input, this._keyStored(keys), { $map: {
555
557
  input: "$$value",
556
558
  as: "el",
@@ -568,9 +570,9 @@ var CollectionPatcher = class {
568
570
  * 0.1.180, as on every other adapter; before, the items were added to
569
571
  * the array as a set union)
570
572
  */
571
- _update(key, input, keys, flatType) {
573
+ _update(key, input, keys) {
572
574
  if (!input?.length || keys.length === 0) return;
573
- const mergeStrategy = flatType.metadata?.get("db.patch.strategy") === "merge";
575
+ const mergeStrategy = this.collection.mergePaths.has(key);
574
576
  this._set(key, { $reduce: {
575
577
  input: literal(input),
576
578
  initialValue: { $ifNull: [`$${key}`, []] },
@@ -1273,13 +1275,6 @@ function filterOptionsOf(host) {
1273
1275
  * name of its own (a dynamic Atlas mapping) is listed as `DEFAULT`. The vector
1274
1276
  * default is the first vector index.
1275
1277
  */
1276
- /** Classic `$text` relevance order: `textScore` descending, `_id` breaking ties (since 0.1.165). */
1277
- const RELEVANCE_SORT = { $sort: {
1278
- _score: -1,
1279
- _id: 1
1280
- } };
1281
- /** The order of an unranked search (`$rank: false`, since 0.1.175): the primary key. */
1282
- const UNRANKED_SORT = { $sort: { _id: 1 } };
1283
1278
  function getSearchIndexesImpl(host) {
1284
1279
  const result = [];
1285
1280
  const indexes = host.getMongoSearchIndexes();
@@ -1336,7 +1331,7 @@ function requireSearchStage(host, text, indexName, controls) {
1336
1331
  * an unresolvable one throws exactly as the leaf path does.
1337
1332
  *
1338
1333
  * `classicText` is deliberately dropped: it only drives the leaf runner's
1339
- * `_score` projection and relevance `$sort`, and no per-document score
1334
+ * relevance order (the `textScore` it sorts by), and no per-document score
1340
1335
  * survives `$group`. See `resolveAggregateSearch` in `@atscript/db/agg` for
1341
1336
  * the normative cross-adapter contract.
1342
1337
  */
@@ -1361,17 +1356,29 @@ async function searchWithCountImpl(host, text, query, indexName) {
1361
1356
  * orders by `_id` instead (an Atlas `$search` included).
1362
1357
  */
1363
1358
  function textRunOptions(plan, query) {
1364
- if (query.controls?.$rank === false) return { defaultSort: UNRANKED_SORT };
1365
- return plan.classicText ? {
1366
- classicText: true,
1367
- defaultSort: RELEVANCE_SORT
1368
- } : {};
1359
+ if (query.controls?.$rank === false) return { defaultOrder: UNRANKED_ORDER };
1360
+ return plan.classicText ? { defaultOrder: RELEVANCE_ORDER } : {};
1369
1361
  }
1370
1362
  /**
1371
- * Field the `vectorSearchScore` rides in through the pipeline. Renamed to the
1372
- * public `$score` after fetch — a field name cannot start with `$`.
1363
+ * Field a search score rides in through the pipeline: the `vectorSearchScore`
1364
+ * (renamed to the public `$score` after fetch — a field name cannot start
1365
+ * with `$`) or the `textScore` of a relevance order (dropped from the rows).
1373
1366
  */
1374
1367
  const SCORE_FIELD = "__atscript_score";
1368
+ /**
1369
+ * Classic `$text` relevance order: `textScore` descending, `_id` breaking ties
1370
+ * (since 0.1.165). The score is dropped after `$skip` / `$limit`, so a row
1371
+ * carries no score field (since 0.1.185; before, rows carried `_score`).
1372
+ */
1373
+ const RELEVANCE_ORDER = {
1374
+ stages: [{ $addFields: { [SCORE_FIELD]: { $meta: "textScore" } } }, { $sort: {
1375
+ [SCORE_FIELD]: -1,
1376
+ _id: 1
1377
+ } }],
1378
+ cleanup: { $project: { [SCORE_FIELD]: 0 } }
1379
+ };
1380
+ /** The order of an unranked search (`$rank: false`, since 0.1.175): the primary key. */
1381
+ const UNRANKED_ORDER = { stages: [{ $sort: { _id: 1 } }] };
1375
1382
  /** Vector search via $vectorSearch aggregation stage. */
1376
1383
  async function vectorSearchImpl(host, vector, query, indexName) {
1377
1384
  const controls = query.controls || {};
@@ -1399,15 +1406,12 @@ async function vectorSearchWithCountImpl(host, vector, query, indexName) {
1399
1406
  /**
1400
1407
  * The stages right after `$vectorSearch`: its score into {@link SCORE_FIELD}
1401
1408
  * (the `$meta` is read here, ahead of any `$facet`) and, with a threshold,
1402
- * into `_score` — kept for compatibility — with the `$match` on it.
1409
+ * the `$match` on it.
1403
1410
  */
1404
1411
  function vectorScoreStages(threshold) {
1405
- const score = { $meta: "vectorSearchScore" };
1406
- if (threshold === void 0) return [{ $addFields: { [SCORE_FIELD]: score } }];
1407
- return [{ $addFields: {
1408
- _score: score,
1409
- [SCORE_FIELD]: score
1410
- } }, { $match: { _score: { $gte: threshold } } }];
1412
+ const stages = [{ $addFields: { [SCORE_FIELD]: { $meta: "vectorSearchScore" } } }];
1413
+ if (threshold !== void 0) stages.push({ $match: { [SCORE_FIELD]: { $gte: threshold } } });
1414
+ return stages;
1411
1415
  }
1412
1416
  /**
1413
1417
  * Field name `$geoNear` writes the computed distance into. Renamed to the
@@ -1796,16 +1800,19 @@ function buildVectorSearchStage(host, vector, indexName, limit, skip) {
1796
1800
  index
1797
1801
  };
1798
1802
  }
1803
+ /** The order of a search: an explicit `$sort` (with its `$nulls` placement flags) replaces the default. */
1804
+ function searchOrder(controls, defaultOrder) {
1805
+ const explicit = sortStages(controls);
1806
+ return explicit.stages.length > 0 || !defaultOrder ? explicit : defaultOrder;
1807
+ }
1799
1808
  /** Runs a search/vector pipeline and returns results. Shared by search + vectorSearch. */
1800
- async function runSearchPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1809
+ async function runSearchPipeline(host, stage, query, label, { vector, defaultOrder, filterStages } = {}) {
1801
1810
  const controls = query.controls || {};
1802
1811
  const pipeline = [stage];
1803
1812
  if (vector) pipeline.push(...vectorScoreStages(vector.threshold));
1804
- else if (classicText) pipeline.push({ $addFields: { _score: { $meta: "textScore" } } });
1805
1813
  pipeline.push(...filterStages ?? mongoFilterStages(query.filter, filterOptionsOf(host)));
1806
- const { stages: sorted, cleanup } = sortStages(controls);
1807
- if (sorted.length > 0) pipeline.push(...sorted);
1808
- else if (defaultSort) pipeline.push(defaultSort);
1814
+ const { stages: sorted, cleanup } = searchOrder(controls, defaultOrder);
1815
+ pipeline.push(...sorted);
1809
1816
  if (controls.$skip) pipeline.push({ $skip: controls.$skip });
1810
1817
  if (controls.$limit) pipeline.push({ $limit: controls.$limit });
1811
1818
  else pipeline.push({ $limit: 1e3 });
@@ -1824,13 +1831,11 @@ async function runSearchPipeline(host, stage, query, label, { vector, classicTex
1824
1831
  * `count: total` — the same counts `$$SEARCH_META` reports), concurrently
1825
1832
  * outside a transaction.
1826
1833
  */
1827
- async function runSearchWithCountPipeline(host, stage, query, label, { vector, classicText = false, defaultSort, filterStages } = {}) {
1834
+ async function runSearchWithCountPipeline(host, stage, query, label, { vector, defaultOrder, filterStages } = {}) {
1828
1835
  const controls = query.controls || {};
1829
- const preStages = [];
1830
- if (vector) preStages.push(...vectorScoreStages(vector.threshold));
1831
- else if (classicText) preStages.push({ $addFields: { _score: { $meta: "textScore" } } });
1832
- const { stages: dataStages, cleanup } = sortStages(controls);
1833
- if (dataStages.length === 0 && defaultSort) dataStages.push(defaultSort);
1836
+ const preStages = vector ? vectorScoreStages(vector.threshold) : [];
1837
+ const { stages: sorted, cleanup } = searchOrder(controls, defaultOrder);
1838
+ const dataStages = [...sorted];
1834
1839
  if (controls.$skip) dataStages.push({ $skip: controls.$skip });
1835
1840
  if (controls.$limit) dataStages.push({ $limit: controls.$limit });
1836
1841
  if (cleanup) dataStages.push(cleanup);
@@ -2608,8 +2613,8 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2608
2613
  _hasExplicitId = false;
2609
2614
  /** Unique fields accumulated during onFieldScanned, returned via getMetadataOverrides. */
2610
2615
  _pendingUniqueFields = [];
2611
- /** {@link _patcherFlatMap}'s memo. */
2612
- _patcherFlatMapMemo;
2616
+ /** {@link _patcherMaps}' memo. */
2617
+ _patcherMapsMemo;
2613
2618
  constructor(db, client, options = {}) {
2614
2619
  super();
2615
2620
  this.db = db;
@@ -2925,7 +2930,7 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2925
2930
  /** Returns the context object used by CollectionPatcher. */
2926
2931
  getPatcherContext() {
2927
2932
  return {
2928
- flatMap: this._patcherFlatMap(),
2933
+ ...this._patcherMaps(),
2929
2934
  prepareId: (id) => this.prepareIdFromIdType(id),
2930
2935
  createValidator: (opts) => this._table.createValidator(opts)
2931
2936
  };
@@ -2935,21 +2940,26 @@ var MongoAdapter = class MongoAdapter extends BaseDbAdapter {
2935
2940
  * with `@db.column` names already applied (`translatePatchKeys`), so a
2936
2941
  * renamed union / `@db.json` field is found — and replaced, not merged —
2937
2942
  * under its stored name. Derived fields are left out (they map to their
2938
- * source's path). Built once per flat map.
2943
+ * source's path). The merge-strategy paths are keyed the same way. Built
2944
+ * once per flat map.
2939
2945
  */
2940
- _patcherFlatMap() {
2946
+ _patcherMaps() {
2941
2947
  const src = this._table.flatMap;
2942
- let memo = this._patcherFlatMapMemo;
2948
+ let memo = this._patcherMapsMemo;
2943
2949
  if (memo?.src !== src) {
2944
2950
  const meta = this._table.getMetadata();
2945
2951
  const map = /* @__PURE__ */ new Map();
2946
2952
  for (const [path, type] of src) if (!meta.derivedFields.has(path)) map.set(meta.documentPath(path), type);
2947
- memo = this._patcherFlatMapMemo = {
2953
+ const mergePaths = new Set([...meta.mergePaths].map((path) => meta.documentPath(path)));
2954
+ memo = this._patcherMapsMemo = {
2948
2955
  src,
2949
- map
2956
+ maps: {
2957
+ flatMap: map,
2958
+ mergePaths
2959
+ }
2950
2960
  };
2951
2961
  }
2952
- return memo.map;
2962
+ return memo.maps;
2953
2963
  }
2954
2964
  async nativePatch(filter, patch, ops, expectedVersion, opts) {
2955
2965
  const mongoFilter = await this._buildCasFilter(filter, expectedVersion, "nativePatch");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/db-mongo",
3
- "version": "0.1.183",
3
+ "version": "0.1.185",
4
4
  "description": "Mongodb plugin for atscript.",
5
5
  "keywords": [
6
6
  "atscript",
@@ -46,19 +46,19 @@
46
46
  "access": "public"
47
47
  },
48
48
  "devDependencies": {
49
- "@atscript/core": "^0.2.13",
50
- "@atscript/typescript": "^0.2.13",
49
+ "@atscript/core": "^0.2.14",
50
+ "@atscript/typescript": "^0.2.14",
51
51
  "@uniqu/core": "^0.2.2",
52
52
  "mongodb": "^6.17.0",
53
53
  "mongodb-memory-server-core": "^10.0.0",
54
- "unplugin-atscript": "^0.2.13"
54
+ "unplugin-atscript": "^0.2.14"
55
55
  },
56
56
  "peerDependencies": {
57
- "@atscript/core": "^0.2.13",
58
- "@atscript/typescript": "^0.2.13",
57
+ "@atscript/core": "^0.2.14",
58
+ "@atscript/typescript": "^0.2.14",
59
59
  "@uniqu/core": "^0.2.2",
60
60
  "mongodb": "^6.17.0",
61
- "@atscript/db": "^0.1.183"
61
+ "@atscript/db": "^0.1.185"
62
62
  },
63
63
  "scripts": {
64
64
  "build": "vp pack",