@sparkvault/sdk-js 15.11.3 → 15.11.4

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.mjs CHANGED
@@ -18852,18 +18852,29 @@ function openHelpDeskForm(client, options = {}) {
18852
18852
  }
18853
18853
 
18854
18854
  /** Dependency-free local search shared by the help center and embedded support. */
18855
- const SEARCH_STOP_WORDS = new Set('a an and are as at be been but by can do does for from had has have how i if in is it its me my of on or our should so that the their them there these they this to was we were what when where which who why will with would you your'.split(' '));
18855
+ const SEARCH_STOP_WORDS = new Set('a an and are as at be been but by can do does for from had has have how i if in is it its me my of on or our should so that the their them there these they this to was we were what when where which who why will with would you your aint arent cant couldnt didnt doesnt dont hadnt hasnt havent isnt mustnt neednt shant shouldnt wasnt werent wont wouldnt'.split(' '));
18856
18856
  const SEARCH_FIELD_WEIGHTS = [160, 140, 80, 60, 45, 10];
18857
+ // A match at least this strong comes from what an article is about (its title,
18858
+ // SEO title, keywords or summary), not its category label or body text.
18859
+ const SEARCH_STRONG_MATCH = 50;
18857
18860
  const SEARCH_MAX_QUERY_LENGTH = 300;
18858
18861
  const SEARCH_MAX_QUERY_TERMS = 12;
18859
18862
  const SEARCH_MAX_TYPO_LENGTH = 64;
18860
- const RECOMMEND_STOP_WORDS = new Set('also am anymore around back because could did didnt doesnt dont else even getting get gets got hello help hey hi im into just like looking lot much need needing now please really something thank thanks trying tried try using want wanted whenever whether without working'.split(' '));
18863
+ const RECOMMEND_STOP_WORDS = new Set('also am anymore around back because could did else even getting get gets got hello help hey hi im into just like looking lot much need needing now please really something thank thanks trying tried try using want wanted whenever whether without working'.split(' '));
18861
18864
  const RECOMMEND_MAX_QUERY_LENGTH = 20000;
18862
- const RECOMMEND_MAX_KNOWN_TERMS = 36;
18863
18865
  const RECOMMEND_MAX_UNKNOWN_TERMS = 12;
18864
18866
 
18867
+ /**
18868
+ * Lowercase, accent-folded words. An English clitic stays with its word, typed
18869
+ * with a straight or curly apostrophe: 's, 'd, 'll, 're, 've and 'm drop
18870
+ * (Bee's is bee, I've is i) and n't joins (didn't is didnt), so a contraction
18871
+ * is one stop word rather than a fragment searched as a rare word.
18872
+ */
18865
18873
  function searchTokens(value) {
18866
- return String(value ?? '').toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '').match(/[\p{L}\p{N}]+/gu) || [];
18874
+ return String(value ?? '').toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '')
18875
+ .replace(/(\p{L})(?:['’ʼ](?:s|d|ll|re|ve|m))+(?![\p{L}\p{N}])/gu, '$1')
18876
+ .replace(/(\p{L})n['’ʼ]t(?![\p{L}\p{N}])/gu, '$1nt')
18877
+ .match(/[\p{L}\p{N}]+/gu) || [];
18867
18878
  }
18868
18879
  function searchCompare(left, right) {
18869
18880
  return left < right ? -1 : left > right ? 1 : 0;
@@ -18873,6 +18884,10 @@ function searchLowerBound(values, target) {
18873
18884
  while (lo < hi) { const mid = (lo + hi) >>> 1; if (values[mid] < target) lo = mid + 1; else hi = mid; }
18874
18885
  return lo;
18875
18886
  }
18887
+ /** A word's weight among the articles: 1 when every article holds it, more the fewer do. */
18888
+ function searchRarity(articles, holding) {
18889
+ return 1 + Math.log((articles + 1) / (holding + 1));
18890
+ }
18876
18891
  /** One insertion, deletion, substitution or adjacent transposition; never edit distance two. */
18877
18892
  function searchOneEdit(left, right) {
18878
18893
  if (left === right) return false;
@@ -18886,7 +18901,11 @@ function searchOneEdit(left, right) {
18886
18901
  return left.length > right.length ? left.slice(i + 1) === right.slice(i) : left.slice(i) === right.slice(i + 1);
18887
18902
  }
18888
18903
 
18889
- /** Prepare normalization, vocabulary and weighted postings once after the index downloads. */
18904
+ /**
18905
+ * Prepare normalization, vocabulary and weighted postings once after the index
18906
+ * downloads. A row's category_ids name its category and every category above
18907
+ * it, so filtering by a category includes its subcategories.
18908
+ */
18890
18909
  function prepareSearchIndex(rows) {
18891
18910
  const postings = new Map();
18892
18911
  const entries = (Array.isArray(rows) ? rows : []).map((article, index) => {
@@ -18900,8 +18919,11 @@ function prepareSearchIndex(rows) {
18900
18919
  }
18901
18920
  });
18902
18921
  const fields = tokenFields.map(tokens => tokens.join(' '));
18903
- return { article, fields, title: fields[0], categoryId: article.category_id ?? article.categoryId ?? null, tie: `${article.path || ''}\u0000${article.id || ''}`, index };
18922
+ // The article's names, its title and SEO title, in the words a description is searched by.
18923
+ const names = tokenFields.slice(0, 2).map(tokens => [...new Set(tokens)].filter(word => !SEARCH_STOP_WORDS.has(word) && !RECOMMEND_STOP_WORDS.has(word))).filter(words => words.length);
18924
+ return { article, fields, names, title: fields[0], categoryIds: Array.isArray(article.category_ids) ? article.category_ids : [], tie: `${article.path || ''}\u0000${article.id || ''}`, index };
18904
18925
  });
18926
+ for (const entry of entries) entry.names = entry.names.map(words => words.map(word => [word, searchRarity(entries.length, postings.get(word).size)]));
18905
18927
  const vocabulary = [...postings.keys()].sort(searchCompare);
18906
18928
  // A single edit preserves either the first or last character. These buckets
18907
18929
  // avoid scanning the entire vocabulary for every typo, including transpositions.
@@ -18916,11 +18938,13 @@ function prepareSearchIndex(rows) {
18916
18938
  return { entries, postings, vocabulary, typoBuckets };
18917
18939
  }
18918
18940
 
18919
- function searchTermMatches(prepared, term, mode) {
18941
+ /** The articles a term matches, each by its best word; `words` collects every word the term matched. */
18942
+ function searchTermMatches(prepared, term, mode, words = null) {
18920
18943
  const matches = new Map();
18921
18944
  const append = (word, multiplier, typo, minimumWeight = 0) => {
18922
18945
  for (const [index, weight] of prepared.postings.get(word) || []) {
18923
18946
  if (weight < minimumWeight) continue;
18947
+ words?.add(word);
18924
18948
  const score = Math.round(weight * multiplier);
18925
18949
  const previous = matches.get(index);
18926
18950
  if (!previous || score > previous.score || (score === previous.score && searchCompare(word, previous.word) < 0)) matches.set(index, { score, word, typo });
@@ -18959,7 +18983,7 @@ function searchRank(prepared, terms, phrase, categoryId, mode) {
18959
18983
  const results = [];
18960
18984
  for (const index of smallest.keys()) {
18961
18985
  const entry = prepared.entries[index];
18962
- if (categoryId !== null && entry.categoryId !== categoryId) continue;
18986
+ if (categoryId !== null && !entry.categoryIds.includes(categoryId)) continue;
18963
18987
  const parts = matches.map(map => map.get(index));
18964
18988
  if (parts.some(part => !part)) continue;
18965
18989
  let score = parts.reduce((sum, part) => sum + part.score, 0);
@@ -18969,65 +18993,119 @@ function searchRank(prepared, terms, phrase, categoryId, mode) {
18969
18993
  else if (` ${entry.fields[1]} `.includes(` ${phrase} `)) score += 1000;
18970
18994
  if (` ${entry.fields[3]} `.includes(` ${phrase} `)) score += 25;
18971
18995
  const typo = parts.some(part => part.typo);
18972
- results.push({ article: entry.article, score, matchedTerms: [...new Set(parts.map(part => part.word))], typo, entry });
18996
+ const strong = parts.some(part => part.score >= SEARCH_STRONG_MATCH);
18997
+ results.push({ article: entry.article, score, matchedTerms: [...new Set(parts.map(part => part.word))], typo, strong, entry });
18973
18998
  }
18974
18999
  results.sort((left, right) => right.score - left.score || searchCompare(left.entry.title, right.entry.title) || searchCompare(left.entry.tie, right.entry.tie) || left.entry.index - right.entry.index);
18975
19000
  return results;
18976
19001
  }
18977
19002
 
18978
- /** All query terms must match. Search falls back from exact/prefix to title substrings, then typos. */
19003
+ /**
19004
+ * The articles holding every meaningful word, falling back from exact/prefix
19005
+ * matches to title substrings, then typos; `complete` counts them. A query of
19006
+ * several words that no article holds in full reads as a question, and so does
19007
+ * one of three or more words that every complete match holds only in passing,
19008
+ * with no strong match (SEARCH_STRONG_MATCH): its partial matches are ranked
19009
+ * by relevance, as recommendations are. Otherwise a query of three or more
19010
+ * words lists those ranked matches after the articles holding every word, so
19011
+ * an article that merely holds them all does not hide the one the question is
19012
+ * about, and a query of one or two words lists only the articles holding them
19013
+ * all.
19014
+ */
18979
19015
  function searchKnowledgeBase(prepared, query, { limit = 20, offset = 0, categoryId = null } = {}) {
18980
19016
  const value = String(query ?? '').trim();
18981
- if (value.length < 2 || value.length > SEARCH_MAX_QUERY_LENGTH) return { results: [], total: 0 };
19017
+ if (value.length < 2 || value.length > SEARCH_MAX_QUERY_LENGTH) return { results: [], total: 0, complete: 0 };
18982
19018
  const raw = searchTokens(value);
18983
19019
  const meaningful = raw.filter(term => !SEARCH_STOP_WORDS.has(term));
18984
19020
  const terms = [...new Set(meaningful.length ? meaningful : raw)];
18985
- if (!terms.length || terms.length > SEARCH_MAX_QUERY_TERMS) return { results: [], total: 0 };
18986
- const phrase = terms.join(' ');
18987
- let ranked = searchRank(prepared, terms, phrase, categoryId, 'exact');
18988
- if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'substring');
18989
- if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'typo');
19021
+ let ranked = [];
19022
+ // A longer query is not matched word for word: that bounds the work, and it
19023
+ // would rarely match.
19024
+ if (terms.length && terms.length <= SEARCH_MAX_QUERY_TERMS) {
19025
+ const phrase = terms.join(' ');
19026
+ ranked = searchRank(prepared, terms, phrase, categoryId, 'exact');
19027
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'substring');
19028
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'typo');
19029
+ }
19030
+ const complete = ranked.length;
19031
+ // Relevance ranking matches a single word through the same stages, so for one
19032
+ // word it could only drop some of the articles holding it. Two words are a
19033
+ // keyword search: the articles holding both, however weakly, answer it, not
19034
+ // articles naming one of them in a title.
19035
+ if (terms.length > 1 && (!complete || (terms.length >= 3 && !ranked.some(hit => hit.strong)))) {
19036
+ const related = recommendationRank(prepared, value, categoryId);
19037
+ if (related.length) ranked = related;
19038
+ } else if (terms.length >= 3) {
19039
+ const listed = new Set(ranked.map(hit => hit.entry.index));
19040
+ ranked = [...ranked, ...recommendationRank(prepared, value, categoryId).filter(hit => !listed.has(hit.entry.index))];
19041
+ }
18990
19042
  const start = Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
18991
19043
  const size = Number.isSafeInteger(limit) && limit >= 0 ? limit : 20;
18992
- return { results: ranked.slice(start, start + size).map(({ article, score, matchedTerms, typo }) => ({ article, score, matchedTerms, typo })), total: ranked.length };
19044
+ return { results: ranked.slice(start, start + size).map(({ article, score, matchedTerms, typo }) => ({ article, score, matchedTerms, typo })), total: ranked.length, complete };
18993
19045
  }
18994
19046
 
18995
- /** Select bounded, useful terms without making a long description an AND query. */
19047
+ /**
19048
+ * The words free text is searched by: every word the index holds, wherever it
19049
+ * comes, since in a large knowledge base nearly every everyday word is some
19050
+ * article's title word and no budget can tell the topic from the asides; and
19051
+ * a few words it does not hold (the most repeated, then the longest, then the
19052
+ * earliest) for prefix, substring and typo recovery. The text's length bounds
19053
+ * the work, as a word the index holds is matched only as itself or a prefix.
19054
+ */
18996
19055
  function recommendationTerms(prepared, issue) {
18997
19056
  const terms = new Map();
18998
19057
  const raw = searchTokens(String(issue ?? '').slice(0, RECOMMEND_MAX_QUERY_LENGTH));
18999
19058
  for (const term of raw) {
19000
19059
  if (term.length < 2 || term.length > SEARCH_MAX_TYPO_LENGTH || SEARCH_STOP_WORDS.has(term) || RECOMMEND_STOP_WORDS.has(term)) continue;
19001
- if (!terms.has(term)) terms.set(term, { term, frequency: 0, order: terms.size, documents: prepared.postings.get(term)?.size ?? 0 });
19060
+ if (!terms.has(term)) terms.set(term, { term, frequency: 0, order: terms.size, known: prepared.postings.has(term) });
19002
19061
  terms.get(term).frequency++;
19003
19062
  }
19004
19063
  const values = [...terms.values()];
19005
- // Rare indexed terms carry useful detail even when they occur after a long
19006
- // introduction. A separate small budget retains prefixes and misspellings.
19007
- const known = values.filter(value => value.documents).sort((a, b) => a.documents - b.documents || b.frequency - a.frequency || a.order - b.order).slice(0, RECOMMEND_MAX_KNOWN_TERMS);
19008
- const unknown = values.filter(value => !value.documents).sort((a, b) => b.frequency - a.frequency || b.term.length - a.term.length || a.order - b.order).slice(0, RECOMMEND_MAX_UNKNOWN_TERMS);
19009
- return [...known, ...unknown].sort((a, b) => a.order - b.order).map(value => value.term);
19064
+ const unknown = values.filter(value => !value.known).sort((a, b) => b.frequency - a.frequency || b.term.length - a.term.length || a.order - b.order).slice(0, RECOMMEND_MAX_UNKNOWN_TERMS);
19065
+ return [...values.filter(value => value.known), ...unknown].sort((a, b) => a.order - b.order).map(value => value.term);
19066
+ }
19067
+ /** How much of an article's title or SEO title, by weight, the mentioned words name: 0 to 1. */
19068
+ function searchNamed(entry, mentioned) {
19069
+ let named = 0;
19070
+ for (const name of entry.names) {
19071
+ let covered = 0; let total = 0;
19072
+ for (const [word, weight] of name) { total += weight; if (mentioned.has(word)) covered += weight; }
19073
+ named = Math.max(named, covered / total);
19074
+ }
19075
+ return named;
19010
19076
  }
19011
-
19012
19077
  /**
19013
- * Recommend published answers for a paragraph using the same prepared postings,
19014
- * normalization, field weights and bounded spelling recovery as normal search.
19015
- * Unknown details do not veto an otherwise relevant answer. Coverage and field
19016
- * strength keep incidental body mentions out of multi-word recommendations.
19078
+ * Rank articles for free text. Each matched word adds its strongest field's
19079
+ * weight times its rarity among the articles. An article qualifies when it
19080
+ * answers a quarter of the text's searchable weight with a title, SEO,
19081
+ * keyword or summary match, or half of it through its body alone, or when the
19082
+ * text names it, mentioning words that carry half the weight of its title or
19083
+ * SEO title: a long description's incidental words dilute every article's
19084
+ * share of it, but not how fully it names the one it is about. Being named
19085
+ * raises an article's score by up to double.
19017
19086
  */
19018
- function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null } = {}) {
19087
+ function recommendationRank(prepared, issue, categoryId) {
19019
19088
  const terms = recommendationTerms(prepared, issue);
19020
- if (!terms.length) return { results: [], total: 0 };
19021
19089
  const candidates = new Map();
19022
- const withinCategory = matches => categoryId === null ? matches : new Map([...matches].filter(([index]) => prepared.entries[index].categoryId === categoryId));
19023
- let totalWeight = 0; let searchableTerms = 0;
19090
+ const mentioned = new Set();
19091
+ const withinCategory = matches => categoryId === null ? matches : new Map([...matches].filter(([index]) => prepared.entries[index].categoryIds.includes(categoryId)));
19092
+ let totalWeight = 0;
19024
19093
  for (const term of terms) {
19025
- let matches = withinCategory(searchTermMatches(prepared, term, 'exact'));
19026
- if (!matches.size) matches = withinCategory(searchTermMatches(prepared, term, 'substring'));
19027
- if (!matches.size) matches = withinCategory(searchTermMatches(prepared, term, 'typo'));
19094
+ // Recovery, as a substring and then a typo, is for a word the index does
19095
+ // not hold. A word it holds is matched only as itself or a prefix, even
19096
+ // where a category filter leaves it nothing: it is no misspelling of
19097
+ // another word, and a long description would otherwise scan the whole
19098
+ // vocabulary once for each of its words.
19099
+ let words; let matches = new Map();
19100
+ for (const mode of prepared.postings.has(term) ? ['exact'] : ['exact', 'substring', 'typo']) {
19101
+ words = new Set();
19102
+ matches = withinCategory(searchTermMatches(prepared, term, mode, words));
19103
+ if (matches.size) break;
19104
+ }
19028
19105
  if (!matches.size) continue;
19029
- const weight = 1 + Math.log((prepared.entries.length + 1) / (matches.size + 1));
19030
- totalWeight += weight; searchableTerms++;
19106
+ for (const word of words) mentioned.add(word);
19107
+ const weight = searchRarity(prepared.entries.length, matches.size);
19108
+ totalWeight += weight;
19031
19109
  for (const [index, part] of matches) {
19032
19110
  if (!candidates.has(index)) candidates.set(index, { entry: prepared.entries[index], score: 0, matchedTerms: [], count: 0, weight: 0, strongest: 0, typo: false });
19033
19111
  const hit = candidates.get(index);
@@ -19038,16 +19116,28 @@ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null
19038
19116
  }
19039
19117
  const ranked = [];
19040
19118
  for (const hit of candidates.values()) {
19041
- const coverage = hit.weight / totalWeight;
19042
- const strong = hit.strongest >= 50;
19119
+ const strong = hit.strongest >= SEARCH_STRONG_MATCH;
19043
19120
  // One clear keyword is useful. Within a paragraph, a weak body-only match
19044
19121
  // needs corroboration; category names alone must not recommend every page.
19045
19122
  if (!strong && hit.count < 2 && !(terms.length === 1 && hit.strongest <= SEARCH_FIELD_WEIGHTS[5])) continue;
19046
- if (coverage < (strong ? 0.25 : 0.5)) continue;
19047
- const score = Math.round(hit.score + coverage * 100 + hit.count / searchableTerms * 50);
19048
- ranked.push({ article: hit.entry.article, score, matchedTerms: [...new Set(hit.matchedTerms)], typo: hit.typo, coverage, entry: hit.entry });
19123
+ const answered = hit.weight / totalWeight;
19124
+ const named = searchNamed(hit.entry, mentioned);
19125
+ if (strong ? answered < 0.25 && named < 0.5 : answered < 0.5) continue;
19126
+ ranked.push({ article: hit.entry.article, score: Math.round(hit.score * (1 + named)), matchedTerms: [...new Set(hit.matchedTerms)], typo: hit.typo, coverage: Math.max(answered, named), entry: hit.entry });
19049
19127
  }
19050
19128
  ranked.sort((a, b) => b.score - a.score || b.coverage - a.coverage || searchCompare(a.entry.title, b.entry.title) || searchCompare(a.entry.tie, b.entry.tie) || a.entry.index - b.entry.index);
19129
+ return ranked;
19130
+ }
19131
+
19132
+ /**
19133
+ * Recommend published answers for a paragraph using the same prepared postings,
19134
+ * normalization, field weights and bounded spelling recovery as normal search.
19135
+ * Unknown details do not veto an otherwise relevant answer. A hit's coverage
19136
+ * is the larger of the share of the paragraph it answers and how fully the
19137
+ * paragraph names it.
19138
+ */
19139
+ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null } = {}) {
19140
+ const ranked = recommendationRank(prepared, issue, categoryId);
19051
19141
  const size = Number.isSafeInteger(limit) && limit >= 0 ? Math.min(limit, 20) : 5;
19052
19142
  return { results: ranked.slice(0, size).map(({ article, score, matchedTerms, typo, coverage }) => ({ article, score, matchedTerms, typo, coverage })), total: ranked.length };
19053
19143
  }
@@ -19056,15 +19146,15 @@ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null
19056
19146
  [
19057
19147
  `const SEARCH_STOP_WORDS=new Set(${JSON.stringify([...SEARCH_STOP_WORDS])});`,
19058
19148
  `const SEARCH_FIELD_WEIGHTS=${JSON.stringify(SEARCH_FIELD_WEIGHTS)};`,
19149
+ `const SEARCH_STRONG_MATCH=${SEARCH_STRONG_MATCH};`,
19059
19150
  `const SEARCH_MAX_QUERY_LENGTH=${SEARCH_MAX_QUERY_LENGTH};`,
19060
19151
  `const SEARCH_MAX_QUERY_TERMS=${SEARCH_MAX_QUERY_TERMS};`,
19061
19152
  `const SEARCH_MAX_TYPO_LENGTH=${SEARCH_MAX_TYPO_LENGTH};`,
19062
19153
  `const RECOMMEND_STOP_WORDS=new Set(${JSON.stringify([...RECOMMEND_STOP_WORDS])});`,
19063
19154
  `const RECOMMEND_MAX_QUERY_LENGTH=${RECOMMEND_MAX_QUERY_LENGTH};`,
19064
- `const RECOMMEND_MAX_KNOWN_TERMS=${RECOMMEND_MAX_KNOWN_TERMS};`,
19065
19155
  `const RECOMMEND_MAX_UNKNOWN_TERMS=${RECOMMEND_MAX_UNKNOWN_TERMS};`,
19066
- searchTokens, searchCompare, searchLowerBound, searchOneEdit, prepareSearchIndex,
19067
- searchTermMatches, searchRank, searchKnowledgeBase, recommendationTerms, recommendKnowledgeBase,
19156
+ searchTokens, searchCompare, searchLowerBound, searchRarity, searchOneEdit, prepareSearchIndex,
19157
+ searchTermMatches, searchRank, searchKnowledgeBase, recommendationTerms, searchNamed, recommendationRank, recommendKnowledgeBase,
19068
19158
  ].map(value => typeof value === 'function' ? value.toString() : value).join('\n') + '\nexport { prepareSearchIndex, searchKnowledgeBase, recommendKnowledgeBase };\n';
19069
19159
 
19070
19160
  /** One published-KB transport and shared local search engine for support entry points. */
@@ -26045,7 +26135,7 @@ class SparkVault {
26045
26135
  }
26046
26136
  /** Get the SDK version */
26047
26137
  static get version() {
26048
- return '15.11.3';
26138
+ return '15.11.4';
26049
26139
  }
26050
26140
  }
26051
26141
  if (typeof window !== 'undefined') {