@sparkvault/sdk-js 15.11.3 → 15.11.5

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.d.ts CHANGED
@@ -3581,8 +3581,19 @@ interface HelpDeskTicketDetail extends HelpDeskTimeline {
3581
3581
  ticket: HelpDeskTicket;
3582
3582
  }
3583
3583
  interface HelpDeskReplyOptions {
3584
+ /** Help desk safe markup, not HTML. */
3584
3585
  body: string;
3585
3586
  attachments?: string[];
3587
+ /**
3588
+ * The id the reply is sent under (`HelpDeskClient.newReplyId()`), named once
3589
+ * per composed reply and sent with every send of it while its words and
3590
+ * files stand unchanged, whatever an earlier send answered (a lost
3591
+ * response, a refusal): a reply an earlier send posted is answered with
3592
+ * that reply instead of being posted again. Name a changed reply anew.
3593
+ * Without one the help desk names the reply itself, so a reply sent again
3594
+ * posts again.
3595
+ */
3596
+ eventId?: string;
3586
3597
  }
3587
3598
  interface HelpDeskReplyCreated {
3588
3599
  event_id: string;
@@ -3755,7 +3766,9 @@ declare class HelpDeskClient {
3755
3766
  response?: string;
3756
3767
  }): Promise<HelpDeskTicketDetail>;
3757
3768
  listEvents(number: number, cursor?: string): Promise<HelpDeskTimeline>;
3758
- /** Replies have no client idempotency key: reconcile an uncertain response before retrying. */
3769
+ /** A new id for one composed reply, sent as `HelpDeskReplyOptions.eventId` with every send of it while it stands unchanged. */
3770
+ newReplyId(): string;
3771
+ /** A reply sent under an `eventId` an earlier send of it posted answers that reply, posting nothing again. */
3759
3772
  replyToTicket(number: number, options: HelpDeskReplyOptions, context?: HelpDeskRequestContext): Promise<HelpDeskReplyCreated>;
3760
3773
  resolveTicket(number: number, context?: HelpDeskRequestContext): Promise<void>;
3761
3774
  muteTicket(number: number, muted: boolean, context?: HelpDeskRequestContext): Promise<void>;
package/dist/index.mjs CHANGED
@@ -13094,9 +13094,14 @@ Array.from({ length: 1 << BRAND_BITS.size }, (_, mask) =>
13094
13094
  * histogram's bucket edges live here for the same reason. So do the one rule a tag is stored by
13095
13095
  * (ticketTag), which Core applies where it stores a tag and the console
13096
13096
  * applies where one is typed, and the one rule a typed or pasted sign-in
13097
- * code is read by (helpDeskPinDigits), which every sign-in form applies.
13097
+ * code is read by (helpDeskPinDigits), which every sign-in form applies. So
13098
+ * does the one way a client names a message it sends (newMessageId), which
13099
+ * the portal, the SDK and the console's composer each send their messages
13100
+ * under, and the one rule that a message sent again is the same message
13101
+ * (sameMessage), which keeps its name.
13098
13102
  *
13099
- * BROWSER-SAFE: data and pure functions; its imports are the platform's label
13103
+ * BROWSER-SAFE: data and pure functions, and newMessageId's count of the ids
13104
+ * its page named; its imports are the platform's label
13100
13105
  * rule a tag is built on (./display-text.js), the mail products whose fixed
13101
13106
  * From local parts no team alias may take (./mail-products.js) and the brand
13102
13107
  * rule no team alias may read as (./organization-name.js).
@@ -13207,6 +13212,30 @@ function helpDeskCountdown(seconds) {
13207
13212
  return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, '0')}`;
13208
13213
  }
13209
13214
 
13215
+ /** How many message ids this page has named (newMessageId). */
13216
+ let messagesNamed = 0;
13217
+
13218
+ /**
13219
+ * A new id for a message its client sends: a customer's reply from the
13220
+ * portal or the SDK (`event_id`), a trainee's reply held for review
13221
+ * (`review_id`). The client names a message once and sends every retry of it
13222
+ * under the same id, so a send whose answer was lost and is made again is
13223
+ * answered with what the first send wrote instead of writing it twice.
13224
+ *
13225
+ * Counted, never drawn (docs/CONVENTIONS.md → Randomness: it only has to
13226
+ * differ): the page's time origin, the time it is named and the page's count
13227
+ * of the ids it named, so no two of one author's messages share one. The
13228
+ * server keeps a ticket's ids apart: one another record of the ticket holds
13229
+ * is refused.
13230
+ *
13231
+ * @returns {string} An id of a message event (`@sparkvault/app-sdk/ids` `ticketEvent`)
13232
+ */
13233
+ function newMessageId() {
13234
+ messagesNamed += 1;
13235
+ const origin = Math.round((globalThis.performance?.timeOrigin ?? 0) * 1000);
13236
+ return `hdev_m${origin.toString(36)}-${Date.now().toString(36)}-${messagesNamed.toString(36)}`;
13237
+ }
13238
+
13210
13239
  /**
13211
13240
  * Why a customer's file is refused by the desk's upload allowance per
13212
13241
  * customer (`customer_upload_limit_bytes`), as the 402 QUOTA_EXCEEDED that
@@ -16319,7 +16348,7 @@ function hostname(value) {
16319
16348
  }
16320
16349
  function resource(kind, value, field) {
16321
16350
  if (!isResourceIdOf(kind, value))
16322
- throw new ValidationError(`${field} must be a help desk ${kind} ID`, { field });
16351
+ throw new ValidationError(`${field} must be a help desk ${kind === 'ticketEvent' ? 'message' : kind} ID`, { field });
16323
16352
  return value;
16324
16353
  }
16325
16354
  function requestNumber(value) {
@@ -16791,9 +16820,14 @@ class HelpDeskClient {
16791
16820
  listEvents(number, cursor) {
16792
16821
  return this.send('GET', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets/${requestNumber(number)}/events`, undefined, { cursor });
16793
16822
  }
16794
- /** Replies have no client idempotency key: reconcile an uncertain response before retrying. */
16823
+ /** A new id for one composed reply, sent as `HelpDeskReplyOptions.eventId` with every send of it while it stands unchanged. */
16824
+ newReplyId() { return newMessageId(); }
16825
+ /** A reply sent under an `eventId` an earlier send of it posted answers that reply, posting nothing again. */
16795
16826
  replyToTicket(number, options, context) {
16796
- return this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets/${requestNumber(number)}/replies`, { body: options.body, attachments: options.attachments ?? [] }, undefined, true, context);
16827
+ const eventId = options.eventId === undefined ? undefined : resource('ticketEvent', options.eventId, 'eventId');
16828
+ return this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets/${requestNumber(number)}/replies`, {
16829
+ body: options.body, attachments: options.attachments ?? [], ...(eventId && { event_id: eventId }),
16830
+ }, undefined, true, context);
16797
16831
  }
16798
16832
  resolveTicket(number, context) { return this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets/${requestNumber(number)}/resolve`, undefined, undefined, true, context); }
16799
16833
  muteTicket(number, muted, context) { return this.send('PUT', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets/${requestNumber(number)}/mute`, { muted }, undefined, true, context); }
@@ -18852,18 +18886,29 @@ function openHelpDeskForm(client, options = {}) {
18852
18886
  }
18853
18887
 
18854
18888
  /** 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(' '));
18889
+ 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
18890
  const SEARCH_FIELD_WEIGHTS = [160, 140, 80, 60, 45, 10];
18891
+ // A match at least this strong comes from what an article is about (its title,
18892
+ // SEO title, keywords or summary), not its category label or body text.
18893
+ const SEARCH_STRONG_MATCH = 50;
18857
18894
  const SEARCH_MAX_QUERY_LENGTH = 300;
18858
18895
  const SEARCH_MAX_QUERY_TERMS = 12;
18859
18896
  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(' '));
18897
+ 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
18898
  const RECOMMEND_MAX_QUERY_LENGTH = 20000;
18862
- const RECOMMEND_MAX_KNOWN_TERMS = 36;
18863
18899
  const RECOMMEND_MAX_UNKNOWN_TERMS = 12;
18864
18900
 
18901
+ /**
18902
+ * Lowercase, accent-folded words. An English clitic stays with its word, typed
18903
+ * with a straight or curly apostrophe: 's, 'd, 'll, 're, 've and 'm drop
18904
+ * (Bee's is bee, I've is i) and n't joins (didn't is didnt), so a contraction
18905
+ * is one stop word rather than a fragment searched as a rare word.
18906
+ */
18865
18907
  function searchTokens(value) {
18866
- return String(value ?? '').toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '').match(/[\p{L}\p{N}]+/gu) || [];
18908
+ return String(value ?? '').toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '')
18909
+ .replace(/(\p{L})(?:['’ʼ](?:s|d|ll|re|ve|m))+(?![\p{L}\p{N}])/gu, '$1')
18910
+ .replace(/(\p{L})n['’ʼ]t(?![\p{L}\p{N}])/gu, '$1nt')
18911
+ .match(/[\p{L}\p{N}]+/gu) || [];
18867
18912
  }
18868
18913
  function searchCompare(left, right) {
18869
18914
  return left < right ? -1 : left > right ? 1 : 0;
@@ -18873,6 +18918,10 @@ function searchLowerBound(values, target) {
18873
18918
  while (lo < hi) { const mid = (lo + hi) >>> 1; if (values[mid] < target) lo = mid + 1; else hi = mid; }
18874
18919
  return lo;
18875
18920
  }
18921
+ /** A word's weight among the articles: 1 when every article holds it, more the fewer do. */
18922
+ function searchRarity(articles, holding) {
18923
+ return 1 + Math.log((articles + 1) / (holding + 1));
18924
+ }
18876
18925
  /** One insertion, deletion, substitution or adjacent transposition; never edit distance two. */
18877
18926
  function searchOneEdit(left, right) {
18878
18927
  if (left === right) return false;
@@ -18886,7 +18935,11 @@ function searchOneEdit(left, right) {
18886
18935
  return left.length > right.length ? left.slice(i + 1) === right.slice(i) : left.slice(i) === right.slice(i + 1);
18887
18936
  }
18888
18937
 
18889
- /** Prepare normalization, vocabulary and weighted postings once after the index downloads. */
18938
+ /**
18939
+ * Prepare normalization, vocabulary and weighted postings once after the index
18940
+ * downloads. A row's category_ids name its category and every category above
18941
+ * it, so filtering by a category includes its subcategories.
18942
+ */
18890
18943
  function prepareSearchIndex(rows) {
18891
18944
  const postings = new Map();
18892
18945
  const entries = (Array.isArray(rows) ? rows : []).map((article, index) => {
@@ -18900,8 +18953,11 @@ function prepareSearchIndex(rows) {
18900
18953
  }
18901
18954
  });
18902
18955
  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 };
18956
+ // The article's names, its title and SEO title, in the words a description is searched by.
18957
+ 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);
18958
+ return { article, fields, names, title: fields[0], categoryIds: Array.isArray(article.category_ids) ? article.category_ids : [], tie: `${article.path || ''}\u0000${article.id || ''}`, index };
18904
18959
  });
18960
+ for (const entry of entries) entry.names = entry.names.map(words => words.map(word => [word, searchRarity(entries.length, postings.get(word).size)]));
18905
18961
  const vocabulary = [...postings.keys()].sort(searchCompare);
18906
18962
  // A single edit preserves either the first or last character. These buckets
18907
18963
  // avoid scanning the entire vocabulary for every typo, including transpositions.
@@ -18916,11 +18972,13 @@ function prepareSearchIndex(rows) {
18916
18972
  return { entries, postings, vocabulary, typoBuckets };
18917
18973
  }
18918
18974
 
18919
- function searchTermMatches(prepared, term, mode) {
18975
+ /** The articles a term matches, each by its best word; `words` collects every word the term matched. */
18976
+ function searchTermMatches(prepared, term, mode, words = null) {
18920
18977
  const matches = new Map();
18921
18978
  const append = (word, multiplier, typo, minimumWeight = 0) => {
18922
18979
  for (const [index, weight] of prepared.postings.get(word) || []) {
18923
18980
  if (weight < minimumWeight) continue;
18981
+ words?.add(word);
18924
18982
  const score = Math.round(weight * multiplier);
18925
18983
  const previous = matches.get(index);
18926
18984
  if (!previous || score > previous.score || (score === previous.score && searchCompare(word, previous.word) < 0)) matches.set(index, { score, word, typo });
@@ -18959,7 +19017,7 @@ function searchRank(prepared, terms, phrase, categoryId, mode) {
18959
19017
  const results = [];
18960
19018
  for (const index of smallest.keys()) {
18961
19019
  const entry = prepared.entries[index];
18962
- if (categoryId !== null && entry.categoryId !== categoryId) continue;
19020
+ if (categoryId !== null && !entry.categoryIds.includes(categoryId)) continue;
18963
19021
  const parts = matches.map(map => map.get(index));
18964
19022
  if (parts.some(part => !part)) continue;
18965
19023
  let score = parts.reduce((sum, part) => sum + part.score, 0);
@@ -18969,65 +19027,119 @@ function searchRank(prepared, terms, phrase, categoryId, mode) {
18969
19027
  else if (` ${entry.fields[1]} `.includes(` ${phrase} `)) score += 1000;
18970
19028
  if (` ${entry.fields[3]} `.includes(` ${phrase} `)) score += 25;
18971
19029
  const typo = parts.some(part => part.typo);
18972
- results.push({ article: entry.article, score, matchedTerms: [...new Set(parts.map(part => part.word))], typo, entry });
19030
+ const strong = parts.some(part => part.score >= SEARCH_STRONG_MATCH);
19031
+ results.push({ article: entry.article, score, matchedTerms: [...new Set(parts.map(part => part.word))], typo, strong, entry });
18973
19032
  }
18974
19033
  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
19034
  return results;
18976
19035
  }
18977
19036
 
18978
- /** All query terms must match. Search falls back from exact/prefix to title substrings, then typos. */
19037
+ /**
19038
+ * The articles holding every meaningful word, falling back from exact/prefix
19039
+ * matches to title substrings, then typos; `complete` counts them. A query of
19040
+ * several words that no article holds in full reads as a question, and so does
19041
+ * one of three or more words that every complete match holds only in passing,
19042
+ * with no strong match (SEARCH_STRONG_MATCH): its partial matches are ranked
19043
+ * by relevance, as recommendations are. Otherwise a query of three or more
19044
+ * words lists those ranked matches after the articles holding every word, so
19045
+ * an article that merely holds them all does not hide the one the question is
19046
+ * about, and a query of one or two words lists only the articles holding them
19047
+ * all.
19048
+ */
18979
19049
  function searchKnowledgeBase(prepared, query, { limit = 20, offset = 0, categoryId = null } = {}) {
18980
19050
  const value = String(query ?? '').trim();
18981
- if (value.length < 2 || value.length > SEARCH_MAX_QUERY_LENGTH) return { results: [], total: 0 };
19051
+ if (value.length < 2 || value.length > SEARCH_MAX_QUERY_LENGTH) return { results: [], total: 0, complete: 0 };
18982
19052
  const raw = searchTokens(value);
18983
19053
  const meaningful = raw.filter(term => !SEARCH_STOP_WORDS.has(term));
18984
19054
  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');
19055
+ let ranked = [];
19056
+ // A longer query is not matched word for word: that bounds the work, and it
19057
+ // would rarely match.
19058
+ if (terms.length && terms.length <= SEARCH_MAX_QUERY_TERMS) {
19059
+ const phrase = terms.join(' ');
19060
+ ranked = searchRank(prepared, terms, phrase, categoryId, 'exact');
19061
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'substring');
19062
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'typo');
19063
+ }
19064
+ const complete = ranked.length;
19065
+ // Relevance ranking matches a single word through the same stages, so for one
19066
+ // word it could only drop some of the articles holding it. Two words are a
19067
+ // keyword search: the articles holding both, however weakly, answer it, not
19068
+ // articles naming one of them in a title.
19069
+ if (terms.length > 1 && (!complete || (terms.length >= 3 && !ranked.some(hit => hit.strong)))) {
19070
+ const related = recommendationRank(prepared, value, categoryId);
19071
+ if (related.length) ranked = related;
19072
+ } else if (terms.length >= 3) {
19073
+ const listed = new Set(ranked.map(hit => hit.entry.index));
19074
+ ranked = [...ranked, ...recommendationRank(prepared, value, categoryId).filter(hit => !listed.has(hit.entry.index))];
19075
+ }
18990
19076
  const start = Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
18991
19077
  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 };
19078
+ return { results: ranked.slice(start, start + size).map(({ article, score, matchedTerms, typo }) => ({ article, score, matchedTerms, typo })), total: ranked.length, complete };
18993
19079
  }
18994
19080
 
18995
- /** Select bounded, useful terms without making a long description an AND query. */
19081
+ /**
19082
+ * The words free text is searched by: every word the index holds, wherever it
19083
+ * comes, since in a large knowledge base nearly every everyday word is some
19084
+ * article's title word and no budget can tell the topic from the asides; and
19085
+ * a few words it does not hold (the most repeated, then the longest, then the
19086
+ * earliest) for prefix, substring and typo recovery. The text's length bounds
19087
+ * the work, as a word the index holds is matched only as itself or a prefix.
19088
+ */
18996
19089
  function recommendationTerms(prepared, issue) {
18997
19090
  const terms = new Map();
18998
19091
  const raw = searchTokens(String(issue ?? '').slice(0, RECOMMEND_MAX_QUERY_LENGTH));
18999
19092
  for (const term of raw) {
19000
19093
  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 });
19094
+ if (!terms.has(term)) terms.set(term, { term, frequency: 0, order: terms.size, known: prepared.postings.has(term) });
19002
19095
  terms.get(term).frequency++;
19003
19096
  }
19004
19097
  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);
19098
+ 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);
19099
+ return [...values.filter(value => value.known), ...unknown].sort((a, b) => a.order - b.order).map(value => value.term);
19100
+ }
19101
+ /** How much of an article's title or SEO title, by weight, the mentioned words name: 0 to 1. */
19102
+ function searchNamed(entry, mentioned) {
19103
+ let named = 0;
19104
+ for (const name of entry.names) {
19105
+ let covered = 0; let total = 0;
19106
+ for (const [word, weight] of name) { total += weight; if (mentioned.has(word)) covered += weight; }
19107
+ named = Math.max(named, covered / total);
19108
+ }
19109
+ return named;
19010
19110
  }
19011
-
19012
19111
  /**
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.
19112
+ * Rank articles for free text. Each matched word adds its strongest field's
19113
+ * weight times its rarity among the articles. An article qualifies when it
19114
+ * answers a quarter of the text's searchable weight with a title, SEO,
19115
+ * keyword or summary match, or half of it through its body alone, or when the
19116
+ * text names it, mentioning words that carry half the weight of its title or
19117
+ * SEO title: a long description's incidental words dilute every article's
19118
+ * share of it, but not how fully it names the one it is about. Being named
19119
+ * raises an article's score by up to double.
19017
19120
  */
19018
- function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null } = {}) {
19121
+ function recommendationRank(prepared, issue, categoryId) {
19019
19122
  const terms = recommendationTerms(prepared, issue);
19020
- if (!terms.length) return { results: [], total: 0 };
19021
19123
  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;
19124
+ const mentioned = new Set();
19125
+ const withinCategory = matches => categoryId === null ? matches : new Map([...matches].filter(([index]) => prepared.entries[index].categoryIds.includes(categoryId)));
19126
+ let totalWeight = 0;
19024
19127
  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'));
19128
+ // Recovery, as a substring and then a typo, is for a word the index does
19129
+ // not hold. A word it holds is matched only as itself or a prefix, even
19130
+ // where a category filter leaves it nothing: it is no misspelling of
19131
+ // another word, and a long description would otherwise scan the whole
19132
+ // vocabulary once for each of its words.
19133
+ let words; let matches = new Map();
19134
+ for (const mode of prepared.postings.has(term) ? ['exact'] : ['exact', 'substring', 'typo']) {
19135
+ words = new Set();
19136
+ matches = withinCategory(searchTermMatches(prepared, term, mode, words));
19137
+ if (matches.size) break;
19138
+ }
19028
19139
  if (!matches.size) continue;
19029
- const weight = 1 + Math.log((prepared.entries.length + 1) / (matches.size + 1));
19030
- totalWeight += weight; searchableTerms++;
19140
+ for (const word of words) mentioned.add(word);
19141
+ const weight = searchRarity(prepared.entries.length, matches.size);
19142
+ totalWeight += weight;
19031
19143
  for (const [index, part] of matches) {
19032
19144
  if (!candidates.has(index)) candidates.set(index, { entry: prepared.entries[index], score: 0, matchedTerms: [], count: 0, weight: 0, strongest: 0, typo: false });
19033
19145
  const hit = candidates.get(index);
@@ -19038,16 +19150,28 @@ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null
19038
19150
  }
19039
19151
  const ranked = [];
19040
19152
  for (const hit of candidates.values()) {
19041
- const coverage = hit.weight / totalWeight;
19042
- const strong = hit.strongest >= 50;
19153
+ const strong = hit.strongest >= SEARCH_STRONG_MATCH;
19043
19154
  // One clear keyword is useful. Within a paragraph, a weak body-only match
19044
19155
  // needs corroboration; category names alone must not recommend every page.
19045
19156
  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 });
19157
+ const answered = hit.weight / totalWeight;
19158
+ const named = searchNamed(hit.entry, mentioned);
19159
+ if (strong ? answered < 0.25 && named < 0.5 : answered < 0.5) continue;
19160
+ 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
19161
  }
19050
19162
  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);
19163
+ return ranked;
19164
+ }
19165
+
19166
+ /**
19167
+ * Recommend published answers for a paragraph using the same prepared postings,
19168
+ * normalization, field weights and bounded spelling recovery as normal search.
19169
+ * Unknown details do not veto an otherwise relevant answer. A hit's coverage
19170
+ * is the larger of the share of the paragraph it answers and how fully the
19171
+ * paragraph names it.
19172
+ */
19173
+ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null } = {}) {
19174
+ const ranked = recommendationRank(prepared, issue, categoryId);
19051
19175
  const size = Number.isSafeInteger(limit) && limit >= 0 ? Math.min(limit, 20) : 5;
19052
19176
  return { results: ranked.slice(0, size).map(({ article, score, matchedTerms, typo, coverage }) => ({ article, score, matchedTerms, typo, coverage })), total: ranked.length };
19053
19177
  }
@@ -19056,15 +19180,15 @@ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null
19056
19180
  [
19057
19181
  `const SEARCH_STOP_WORDS=new Set(${JSON.stringify([...SEARCH_STOP_WORDS])});`,
19058
19182
  `const SEARCH_FIELD_WEIGHTS=${JSON.stringify(SEARCH_FIELD_WEIGHTS)};`,
19183
+ `const SEARCH_STRONG_MATCH=${SEARCH_STRONG_MATCH};`,
19059
19184
  `const SEARCH_MAX_QUERY_LENGTH=${SEARCH_MAX_QUERY_LENGTH};`,
19060
19185
  `const SEARCH_MAX_QUERY_TERMS=${SEARCH_MAX_QUERY_TERMS};`,
19061
19186
  `const SEARCH_MAX_TYPO_LENGTH=${SEARCH_MAX_TYPO_LENGTH};`,
19062
19187
  `const RECOMMEND_STOP_WORDS=new Set(${JSON.stringify([...RECOMMEND_STOP_WORDS])});`,
19063
19188
  `const RECOMMEND_MAX_QUERY_LENGTH=${RECOMMEND_MAX_QUERY_LENGTH};`,
19064
- `const RECOMMEND_MAX_KNOWN_TERMS=${RECOMMEND_MAX_KNOWN_TERMS};`,
19065
19189
  `const RECOMMEND_MAX_UNKNOWN_TERMS=${RECOMMEND_MAX_UNKNOWN_TERMS};`,
19066
- searchTokens, searchCompare, searchLowerBound, searchOneEdit, prepareSearchIndex,
19067
- searchTermMatches, searchRank, searchKnowledgeBase, recommendationTerms, recommendKnowledgeBase,
19190
+ searchTokens, searchCompare, searchLowerBound, searchRarity, searchOneEdit, prepareSearchIndex,
19191
+ searchTermMatches, searchRank, searchKnowledgeBase, recommendationTerms, searchNamed, recommendationRank, recommendKnowledgeBase,
19068
19192
  ].map(value => typeof value === 'function' ? value.toString() : value).join('\n') + '\nexport { prepareSearchIndex, searchKnowledgeBase, recommendKnowledgeBase };\n';
19069
19193
 
19070
19194
  /** One published-KB transport and shared local search engine for support entry points. */
@@ -26045,7 +26169,7 @@ class SparkVault {
26045
26169
  }
26046
26170
  /** Get the SDK version */
26047
26171
  static get version() {
26048
- return '15.11.3';
26172
+ return '15.11.5';
26049
26173
  }
26050
26174
  }
26051
26175
  if (typeof window !== 'undefined') {