forms-angular 0.12.0-beta.341 → 0.12.0-beta.343

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.
@@ -437,7 +437,10 @@ export class FormsAngular {
437
437
  return (new Array(1 + reqLength - String(score).length).join(str) + score);
438
438
  }
439
439
  let sortString = "";
440
- sortString += padLeft(obj.addHits || 9, 1);
440
+ sortString += padLeft(obj.addHits ?? 9, 1);
441
+ // Within the same number of hits, the more of the search string that matched the better (so in a search for
442
+ // "sue e", a record that only matched "sue" beats one that only matched "e")
443
+ sortString += padLeft(99 - Math.min(matchedChars(obj), 99), 2);
441
444
  sortString += padLeft(obj.searchImportance || 99, 2);
442
445
  sortString += padLeft(obj.weighting || 9999, 4);
443
446
  sortString += obj.text;
@@ -480,6 +483,15 @@ export class FormsAngular {
480
483
  }
481
484
  let synonymObj = resource.options?.synonyms?.find((s) => s.name.toLowerCase() === collectionNameLower);
482
485
  const synonymFilter = synonymObj?.filter;
486
+ if (searchFields.length > 0) {
487
+ // A search across all the fields at once, which finds the strongest matches (every word of a multi-word
488
+ // search, or an exact match for a single word) even when the per-field searches below are swamped
489
+ let combinedObj = { resource, combined: true };
490
+ if (synonymFilter) {
491
+ combinedObj.filter = synonymFilter;
492
+ }
493
+ searches.push(combinedObj);
494
+ }
483
495
  for (let m = 0; m < searchFields.length; m++) {
484
496
  let searchObj = {
485
497
  resource: resource,
@@ -496,49 +508,96 @@ export class FormsAngular {
496
508
  let results = [];
497
509
  let moreCount = 0;
498
510
  let searchCriteria;
499
- let searchStrings;
511
+ let combinedCriteria;
512
+ let searchStrings; // lower case, unescaped - for comparing with field values
500
513
  let multiMatchPossible = false;
501
- if (searchFor === "?") {
514
+ let startAnchor = "^";
515
+ // Support for searching anywhere in a field by starting with *
516
+ if (searchFor.slice(0, 1) === "*") {
517
+ startAnchor = "";
518
+ searchFor = searchFor.slice(1);
519
+ }
520
+ // Ignore empty "words" caused by leading, trailing or repeated spaces (which would otherwise match everything)
521
+ searchStrings = searchFor.toLowerCase().split(" ").filter((word) => word !== "");
522
+ if (searchFor === "?" || searchStrings.length === 0) {
502
523
  // interpret this as a wildcard (so there is no way to search for ?
503
524
  searchCriteria = null;
504
525
  }
505
526
  else {
506
- // Support for searching anywhere in a field by starting with *
507
- let startAnchor = "^";
508
- if (searchFor.slice(0, 1) === "*") {
509
- startAnchor = "";
510
- searchFor = searchFor.slice(1);
511
- }
512
- // THe snippet to escape the special characters comes from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
513
- searchFor = searchFor.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&");
514
- multiMatchPossible = searchFor.includes(" ");
515
- if (multiMatchPossible) {
516
- searchStrings = searchFor.split(" ");
517
- }
518
- let modifiedSearchStr = multiMatchPossible
519
- ? searchStrings.join("|")
520
- : searchFor;
521
- searchFor = searchFor.toLowerCase(); // For later case-insensitive comparison
527
+ multiMatchPossible = searchStrings.length > 1;
528
+ searchFor = searchStrings.join(" "); // For later case-insensitive comparison
529
+ // The snippet to escape the special characters comes from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
530
+ const escapedStrings = searchStrings.map((word) => word.replace(/[.*+\-?^${}()|[\]\\]/g, "\\$&"));
531
+ const regex = (pattern) => ({ $regex: pattern, $options: "i" });
532
+ const anyField = (fields, pattern) => ({
533
+ $or: fields.map((field) => ({ [field]: regex(pattern) })),
534
+ });
522
535
  // Removed the logic that preserved spaces when collection was specified because Louise asked me to.
523
- searchCriteria = {
524
- $regex: `${startAnchor}(${modifiedSearchStr})`,
525
- $options: "i",
526
- };
536
+ searchCriteria = regex(`${startAnchor}(${escapedStrings.join("|")})`);
537
+ combinedCriteria = multiMatchPossible
538
+ ? // every word matches at least one field
539
+ (fields) => ({ $and: escapedStrings.map((word) => anyField(fields, `${startAnchor}${word}`)) })
540
+ : // a field matches the search string exactly
541
+ (fields) => anyField(fields, `^${escapedStrings[0]}$`);
527
542
  }
528
- let handleSearchResultsFromIndex = function (err, docs, item, cb) {
529
- function handleSingleSearchResult(aDoc, cbdoc) {
530
- let thisId = aDoc._id.toString(), resultObject, resultPos;
531
- function handleResultsInList() {
543
+ function matchedChars(resultObject) {
544
+ return (resultObject.matched || []).reduce((total, i) => total + searchStrings[i].length, 0);
545
+ }
546
+ // Lower addHits sorts higher: one point for each extra word matched, two for matching the whole phrase in
547
+ // one field and one for an exact match
548
+ function calcAddHits(resultObject) {
549
+ return Math.max(9 -
550
+ Math.max((resultObject.matched?.length || 0) - 1, 0) -
551
+ (resultObject.wholePhrase ? 2 : 0) -
552
+ (resultObject.exact ? 1 : 0), 0);
553
+ }
554
+ // Record what this document matched on, and return true if the result has got stronger
555
+ function recordMatches(resultObject, aDoc, item) {
556
+ const before = calcAddHits(resultObject);
557
+ const charsBefore = matchedChars(resultObject);
558
+ resultObject.matched = resultObject.matched || [];
559
+ if (item.combined) {
560
+ if (multiMatchPossible) {
561
+ resultObject.matched = searchStrings.map((word, i) => i);
562
+ }
563
+ else {
564
+ resultObject.exact = true;
565
+ }
566
+ }
567
+ else {
568
+ const fieldValue = typeof aDoc[item.field] === "string" ? aDoc[item.field].toLowerCase() : undefined;
569
+ if (fieldValue !== undefined) {
532
570
  if (multiMatchPossible) {
533
- resultObject.matched = resultObject.matched || [];
534
571
  // record the index of string that matched, so we don't count it against another field
535
- for (let i = 0; i < searchStrings.length; i++) {
536
- if (aDoc[item.field]?.toLowerCase().indexOf(searchStrings[i]) === 0) {
537
- resultObject.matched.push(i);
538
- break;
572
+ // where more than one word matches (searching for "su sue" and finding "Susan") take the longest
573
+ let i = -1;
574
+ searchStrings.forEach((word, idx) => {
575
+ if (!resultObject.matched.includes(idx) &&
576
+ fieldValue.indexOf(word) === 0 &&
577
+ (i === -1 || word.length > searchStrings[i].length)) {
578
+ i = idx;
539
579
  }
580
+ });
581
+ if (i > -1) {
582
+ resultObject.matched.push(i);
540
583
  }
584
+ if (fieldValue.indexOf(searchFor) === 0) {
585
+ resultObject.wholePhrase = true;
586
+ }
587
+ }
588
+ else if (fieldValue === searchFor) {
589
+ resultObject.exact = true;
541
590
  }
591
+ }
592
+ }
593
+ resultObject.addHits = calcAddHits(resultObject);
594
+ return resultObject.addHits < before || matchedChars(resultObject) > charsBefore;
595
+ }
596
+ let handleSearchResultsFromIndex = function (err, docs, item, cb) {
597
+ function handleSingleSearchResult(aDoc, cbdoc) {
598
+ let thisId = aDoc._id.toString(), resultObject, resultPos;
599
+ function handleResultsInList() {
600
+ recordMatches(resultObject, aDoc, item);
542
601
  resultObject.resourceCollection = item.resource.resourceName;
543
602
  resultObject.searchImportance =
544
603
  item.resource.options.searchImportance || 99;
@@ -559,33 +618,18 @@ export class FormsAngular {
559
618
  }
560
619
  if (resultPos >= 0) {
561
620
  resultObject = Object.assign({}, results[resultPos]);
621
+ resultObject.matched = [...(resultObject.matched || [])];
562
622
  // If they have already matched then improve their weighting
563
- if (multiMatchPossible) {
564
- // record the index of string that matched, so we don't count it against another field
565
- for (let i = 0; i < searchStrings.length; i++) {
566
- if (!resultObject.matched.includes(i) &&
567
- aDoc[item.field]?.toLowerCase().indexOf(searchStrings[i]) === 0) {
568
- resultObject.matched.push(i);
569
- resultObject.addHits = Math.max((resultObject.addHits || 9) - 1, 0);
570
- // remove it from current position
571
- results.splice(resultPos, 1);
572
- // and re-insert where appropriate
573
- results.splice(_.sortedIndexBy(results, resultObject, calcResultValue), 0, resultObject);
574
- break;
575
- }
576
- }
623
+ if (recordMatches(resultObject, aDoc, item)) {
624
+ // remove it from current position
625
+ results.splice(resultPos, 1);
626
+ // and re-insert where appropriate
627
+ results.splice(_.sortedIndexBy(results, resultObject, calcResultValue), 0, resultObject);
577
628
  }
578
629
  cbdoc(null);
579
630
  }
580
631
  else {
581
632
  // Otherwise add them new...
582
- let addHits;
583
- if (multiMatchPossible) {
584
- // If they match the whole search phrase in one index they get smaller addHits (so they sort higher)
585
- if (aDoc[item.field]?.toLowerCase().indexOf(searchFor) === 0) {
586
- addHits = 7;
587
- }
588
- }
589
633
  let disambiguationId;
590
634
  const opts = item.resource.options;
591
635
  const disambiguationResource = opts.disambiguation?.resource;
@@ -597,7 +641,6 @@ export class FormsAngular {
597
641
  if (specialListingFormat) {
598
642
  specialListingFormat.apply(aDoc, [req]).then((resultObj) => {
599
643
  resultObject = resultObj;
600
- resultObject.addHits = addHits;
601
644
  resultObject.disambiguationResource = disambiguationResource;
602
645
  resultObject.disambiguationId = disambiguationId;
603
646
  handleResultsInList();
@@ -612,7 +655,6 @@ export class FormsAngular {
612
655
  resultObject = {
613
656
  id: aDoc._id,
614
657
  weighting: 9999,
615
- addHits,
616
658
  disambiguationResource,
617
659
  disambiguationId,
618
660
  text: description,
@@ -637,7 +679,21 @@ export class FormsAngular {
637
679
  this.searchFunc(searches, function (item, cb) {
638
680
  let searchDoc = {};
639
681
  let searchFilter = filter || item.filter;
640
- if (searchFilter) {
682
+ if (item.combined) {
683
+ if (!combinedCriteria) {
684
+ // wildcard search - the per-field searches will find everything
685
+ return cb();
686
+ }
687
+ if (searchFilter) {
688
+ that.hackVariables(searchFilter);
689
+ extend(searchDoc, searchFilter);
690
+ }
691
+ searchDoc["$and"] = [
692
+ ...(searchDoc["$and"] || []),
693
+ combinedCriteria(item.resource.options.searchFields),
694
+ ];
695
+ }
696
+ else if (searchFilter) {
641
697
  that.hackVariables(searchFilter);
642
698
  extend(searchDoc, searchFilter);
643
699
  if (searchFilter[item.field]) {
@@ -682,9 +738,11 @@ export class FormsAngular {
682
738
  callback(err);
683
739
  }
684
740
  else {
685
- // Strip weighting from the results
741
+ // Strip weighting and match details from the results
686
742
  results = _.map(results, function (aResult) {
687
743
  delete aResult.weighting;
744
+ delete aResult.wholePhrase;
745
+ delete aResult.exact;
688
746
  return aResult;
689
747
  });
690
748
  if (limit && results.length > limit) {
@@ -1041,31 +1099,44 @@ export class FormsAngular {
1041
1099
  }
1042
1100
  }
1043
1101
  }
1102
+ rejectForbiddenPipelineOperators(obj) {
1103
+ if (Array.isArray(obj)) {
1104
+ obj.forEach((elm) => this.rejectForbiddenPipelineOperators(elm));
1105
+ }
1106
+ else if (obj && typeof obj === "object" && !(obj instanceof Types.ObjectId) && !(obj instanceof Date)) {
1107
+ for (const key of Object.keys(obj)) {
1108
+ if (FormsAngular.forbiddenPipelineOperators.includes(key)) {
1109
+ throw new Error(`Unsupported pipeline operator ${key}`);
1110
+ }
1111
+ this.rejectForbiddenPipelineOperators(obj[key]);
1112
+ }
1113
+ }
1114
+ }
1044
1115
  async sanitisePipeline(aggregationParam, hiddenFields, findFuncQry, req) {
1045
1116
  let that = this;
1046
1117
  let array = Array.isArray(aggregationParam)
1047
1118
  ? aggregationParam
1048
1119
  : [aggregationParam];
1120
+ this.rejectForbiddenPipelineOperators(array);
1049
1121
  let retVal = [];
1050
1122
  let doneHiddenFields = false;
1123
+ const haveHiddenFields = hiddenFields && Object.keys(hiddenFields).length > 0;
1051
1124
  if (findFuncQry) {
1052
1125
  retVal.unshift({ $match: findFuncQry });
1053
1126
  }
1054
- async function sanitiseLookupPipeline(stage) {
1055
- // can't think of a way to exploit this (if you add a findFunc) but it is the responsibility of the user
1056
- // to ensure that the pipeline returns fields used by the findFunc
1057
- console.log(`In some scenarios $lookups that use pipelines may not provide all the fields used by the 'findFunc' of a collection.
1058
- If you get no results returned this might be the explanation.`);
1059
- /* Sanitise the pipeline we are doing a lookup with, removing hidden fields from that collection */
1060
- const lookupCollectionName = stage.$lookup.from;
1061
- const lookupResource = that.getResourceFromCollection(lookupCollectionName);
1062
- let lookupHiddenLookupFields = {};
1063
- if (lookupResource) {
1064
- if (lookupResource.options?.hide?.length > 0) {
1065
- lookupHiddenLookupFields = that.generateHiddenFields(lookupResource, false);
1066
- }
1067
- }
1068
- stage.$lookup.pipeline = await that.sanitisePipeline(stage.$lookup.pipeline, lookupHiddenLookupFields, findFuncQry, req);
1127
+ // Sanitise a pipeline that runs against a joined collection, restricting it with that collection's own findFunc
1128
+ // and removing that collection's hidden fields. Collections that are not resources are assumed to hold nothing
1129
+ // sensitive, so are not restricted.
1130
+ async function sanitiseJoinedPipeline(pipeline, resource) {
1131
+ let joinedHiddenFields = {};
1132
+ let joinedFindFuncQry;
1133
+ if (resource) {
1134
+ if (resource.options?.hide?.length > 0) {
1135
+ joinedHiddenFields = that.generateHiddenFields(resource, false);
1136
+ }
1137
+ joinedFindFuncQry = await that.doFindFuncPromise(req, resource);
1138
+ }
1139
+ return that.sanitisePipeline(pipeline || [], joinedHiddenFields, joinedFindFuncQry, req);
1069
1140
  }
1070
1141
  for (let pipelineSection = 0; pipelineSection < array.length; pipelineSection++) {
1071
1142
  let stage = array[pipelineSection];
@@ -1073,11 +1144,17 @@ export class FormsAngular {
1073
1144
  if (keys.length !== 1) {
1074
1145
  throw new Error("Invalid pipeline instruction");
1075
1146
  }
1147
+ if (!doneHiddenFields && keys[0] !== "$match") {
1148
+ // Leading $match stages may select on hidden fields, but nothing after them can see those fields
1149
+ if (haveHiddenFields) {
1150
+ retVal.push({ $project: hiddenFields });
1151
+ }
1152
+ doneHiddenFields = true;
1153
+ }
1076
1154
  switch (keys[0]) {
1077
1155
  case "$project":
1078
1156
  case "$addFields":
1079
1157
  case "$count":
1080
- case "$facet":
1081
1158
  case "$group":
1082
1159
  case "$unset":
1083
1160
  case "$limit":
@@ -1087,39 +1164,31 @@ export class FormsAngular {
1087
1164
  case "$unwind":
1088
1165
  // We don't care about these - they are all (as far as we know) safe
1089
1166
  break;
1167
+ case "$facet":
1168
+ // Each facet is a pipeline in its own right, running against the documents that reach this stage (which
1169
+ // have already been through our findFunc and had hidden fields removed), but it can join other collections
1170
+ for (const facetName of Object.keys(stage.$facet)) {
1171
+ stage.$facet[facetName] = await that.sanitisePipeline(stage.$facet[facetName], {}, undefined, req);
1172
+ }
1173
+ break;
1090
1174
  case "$unionWith":
1091
- /*
1092
- Sanitise the pipeline we are doing a union with, removing hidden fields from that collection
1093
- */
1094
1175
  if (!stage.$unionWith.coll) {
1095
1176
  stage.$unionWith = { coll: stage.$unionWith, pipeline: [] };
1096
1177
  }
1097
- const unionCollectionName = stage.$unionWith.coll;
1098
- const unionResource = that.getResourceFromCollection(unionCollectionName);
1099
- let unionHiddenLookupFields = {};
1100
- if (unionResource) {
1101
- if (unionResource.options?.hide?.length > 0) {
1102
- unionHiddenLookupFields = this.generateHiddenFields(unionResource, false);
1103
- }
1104
- }
1105
- stage.$unionWith.pipeline = await that.sanitisePipeline(stage.$unionWith.pipeline, unionHiddenLookupFields, findFuncQry, req);
1178
+ stage.$unionWith.pipeline = await sanitiseJoinedPipeline(stage.$unionWith.pipeline, that.getResourceFromCollection(stage.$unionWith.coll));
1106
1179
  break;
1107
1180
  case "$match":
1108
1181
  this.hackVariables(array[pipelineSection]["$match"]);
1109
- retVal.push(array[pipelineSection]);
1110
- if (!doneHiddenFields &&
1111
- Object.keys(hiddenFields) &&
1112
- Object.keys(hiddenFields).length > 0) {
1113
- // We can now project out the hidden fields (we wait for the $match to make sure we don't break
1114
- // a select that uses a hidden field
1115
- retVal.push({ $project: hiddenFields });
1116
- doneHiddenFields = true;
1117
- }
1118
- stage = null;
1119
1182
  break;
1120
1183
  case "$lookup":
1121
1184
  case "$graphLookup":
1122
1185
  let needFindFunc = true;
1186
+ const collectionName = stage[keys[0]].from;
1187
+ const lookupField = stage[keys[0]].as;
1188
+ if (typeof collectionName !== "string" || typeof lookupField !== "string" || (collectionName + lookupField).indexOf("$") !== -1) {
1189
+ throw new Error('No support for lookups where the "from" or "as" is anything other than a simple string');
1190
+ }
1191
+ const resource = that.getResourceFromCollection(collectionName);
1123
1192
  if (keys[0] === "$lookup") {
1124
1193
  let lookupProps = Object.keys(stage.$lookup);
1125
1194
  // First deal with simple $lookups with a single join field equality
@@ -1132,7 +1201,7 @@ export class FormsAngular {
1132
1201
  // nothing to do
1133
1202
  }
1134
1203
  else if (lookupProps.length === 5 && lookupProps.includes("pipeline")) {
1135
- await sanitiseLookupPipeline.call(this, stage);
1204
+ stage.$lookup.pipeline = await sanitiseJoinedPipeline(stage.$lookup.pipeline, resource);
1136
1205
  }
1137
1206
  else {
1138
1207
  throw new Error("Unsupported $lookup format");
@@ -1143,19 +1212,12 @@ export class FormsAngular {
1143
1212
  lookupProps.includes("let") &&
1144
1213
  lookupProps.includes("pipeline") &&
1145
1214
  lookupProps.includes("as")) {
1146
- await sanitiseLookupPipeline.call(this, stage);
1215
+ stage.$lookup.pipeline = await sanitiseJoinedPipeline(stage.$lookup.pipeline, resource);
1147
1216
  }
1148
1217
  else {
1149
1218
  throw new Error(`No support for $lookup of with properties ${lookupProps.join(', ')}`);
1150
1219
  }
1151
1220
  }
1152
- // hide any hiddenfields in the lookup collection
1153
- const collectionName = stage[keys[0]].from;
1154
- const lookupField = stage[keys[0]].as;
1155
- if ((collectionName + lookupField).indexOf("$") !== -1) {
1156
- throw new Error('No support for lookups where the "from" or "as" is anything other than a simple string');
1157
- }
1158
- const resource = that.getResourceFromCollection(collectionName);
1159
1221
  if (resource) {
1160
1222
  retVal.push(stage);
1161
1223
  stage = null;
@@ -1172,8 +1234,8 @@ export class FormsAngular {
1172
1234
  let allowNulls = false;
1173
1235
  // If the next stage is an $unwind
1174
1236
  let nextStageIsUnwind = false;
1175
- if (array.length >= pipelineSection) {
1176
- const nextStage = array[pipelineSection + 1];
1237
+ const nextStage = array[pipelineSection + 1];
1238
+ if (nextStage) {
1177
1239
  let nextKeys = Object.keys(nextStage);
1178
1240
  if (nextKeys.length !== 1) {
1179
1241
  throw new Error("Invalid pipeline instruction");
@@ -1228,11 +1290,9 @@ export class FormsAngular {
1228
1290
  retVal.push(stage);
1229
1291
  }
1230
1292
  }
1231
- if (!doneHiddenFields &&
1232
- Object.keys(hiddenFields) &&
1233
- Object.keys(hiddenFields).length > 0) {
1234
- // If there was no $match we still need to hide the hidden fields
1235
- retVal.unshift({ $project: hiddenFields });
1293
+ if (!doneHiddenFields && haveHiddenFields) {
1294
+ // The pipeline was nothing but $match stages
1295
+ retVal.push({ $project: hiddenFields });
1236
1296
  }
1237
1297
  return retVal;
1238
1298
  }
@@ -1305,7 +1365,7 @@ export class FormsAngular {
1305
1365
  });
1306
1366
  })
1307
1367
  .catch((err) => {
1308
- throw new Error("Error in sanitisePipeline " + err);
1368
+ cb(err);
1309
1369
  });
1310
1370
  },
1311
1371
  };
@@ -2228,6 +2288,9 @@ export class FormsAngular {
2228
2288
  return new Date(parseInt(timestamp, 16) * 1000);
2229
2289
  }
2230
2290
  }
2291
+ // Operators that run server-side JavaScript, which can read beyond the documents a findFunc allows. They are
2292
+ // rejected wherever they appear in a pipeline - as a stage, inside a $match, or nested in an expression.
2293
+ FormsAngular.forbiddenPipelineOperators = ["$where", "$function", "$accumulator"];
2231
2294
  export class ForeignKeyError extends global.Error {
2232
2295
  constructor(resourceName, foreignKeys) {
2233
2296
  super(`Cannot delete this ${resourceName}, as it is: ${foreignKeys.map((d) => ` the ${d.key} on ${d.resourceName} ${d.id}`).join("; ")}`);
@@ -18,6 +18,8 @@ declare module fngServer {
18
18
  searchImportance? : number;
19
19
  addHits?: number;
20
20
  matched: number[];
21
+ wholePhrase?: boolean; // a single field starts with the whole (multi-word) search phrase
22
+ exact?: boolean; // a single field exactly equals the (single-word) search string
21
23
  resourceCollection: string;
22
24
  // the next two are only set where the resource options includes disambiguation instructions and multiple search results with the same text value are found...:
23
25
  disambiguationId?: any; // this will identify the record (from another resource) that will be used to disambiguate them
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  },
7
7
  "description": "A form builder that sits on top of Angular.js, Twitter Bootstrap, jQuery UI, Angular-UI, Express and Mongoose. Opinionated or what?",
8
8
  "homepage": "http://forms-angular.org",
9
- "version": "0.12.0-beta.341",
9
+ "version": "0.12.0-beta.343",
10
10
  "packageManager": "npm@10.2.4",
11
11
  "type": "module",
12
12
  "engines": {