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