@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/README.md CHANGED
@@ -465,7 +465,12 @@ const requests = await desk.listTickets({ status: 'open' });
465
465
  ```
466
466
 
467
467
  `getMe`, `updateMe`, `getTicket`, `listEvents`, `replyToTicket`, `resolveTicket`,
468
- `muteTicket` and attachment methods expose the existing customer routes.
468
+ `muteTicket` and attachment methods expose the existing customer routes. Name
469
+ each composed reply once with `newReplyId()` and pass it as `eventId` on every
470
+ send of that reply while its words and files stand unchanged, whatever an
471
+ earlier send answered (a lost response, a refusal): a reply an earlier send
472
+ posted is answered with that reply instead of being posted again. Name a
473
+ changed reply anew.
469
474
  `sendAttachment(forgeUrl, file, { signal, onProgress, onSessionCreated })` and
470
475
  `resumeAttachment({ sessionUrl }, file, { signal, onProgress })` use the same
471
476
  direct Forge transfer as `ingots.sendUpload`, without Core or customer credentials.
package/dist/index.cjs CHANGED
@@ -13098,9 +13098,14 @@ Array.from({ length: 1 << BRAND_BITS.size }, (_, mask) =>
13098
13098
  * histogram's bucket edges live here for the same reason. So do the one rule a tag is stored by
13099
13099
  * (ticketTag), which Core applies where it stores a tag and the console
13100
13100
  * applies where one is typed, and the one rule a typed or pasted sign-in
13101
- * code is read by (helpDeskPinDigits), which every sign-in form applies.
13101
+ * code is read by (helpDeskPinDigits), which every sign-in form applies. So
13102
+ * does the one way a client names a message it sends (newMessageId), which
13103
+ * the portal, the SDK and the console's composer each send their messages
13104
+ * under, and the one rule that a message sent again is the same message
13105
+ * (sameMessage), which keeps its name.
13102
13106
  *
13103
- * BROWSER-SAFE: data and pure functions; its imports are the platform's label
13107
+ * BROWSER-SAFE: data and pure functions, and newMessageId's count of the ids
13108
+ * its page named; its imports are the platform's label
13104
13109
  * rule a tag is built on (./display-text.js), the mail products whose fixed
13105
13110
  * From local parts no team alias may take (./mail-products.js) and the brand
13106
13111
  * rule no team alias may read as (./organization-name.js).
@@ -13211,6 +13216,30 @@ function helpDeskCountdown(seconds) {
13211
13216
  return `${Math.floor(whole / 60)}:${String(whole % 60).padStart(2, '0')}`;
13212
13217
  }
13213
13218
 
13219
+ /** How many message ids this page has named (newMessageId). */
13220
+ let messagesNamed = 0;
13221
+
13222
+ /**
13223
+ * A new id for a message its client sends: a customer's reply from the
13224
+ * portal or the SDK (`event_id`), a trainee's reply held for review
13225
+ * (`review_id`). The client names a message once and sends every retry of it
13226
+ * under the same id, so a send whose answer was lost and is made again is
13227
+ * answered with what the first send wrote instead of writing it twice.
13228
+ *
13229
+ * Counted, never drawn (docs/CONVENTIONS.md → Randomness: it only has to
13230
+ * differ): the page's time origin, the time it is named and the page's count
13231
+ * of the ids it named, so no two of one author's messages share one. The
13232
+ * server keeps a ticket's ids apart: one another record of the ticket holds
13233
+ * is refused.
13234
+ *
13235
+ * @returns {string} An id of a message event (`@sparkvault/app-sdk/ids` `ticketEvent`)
13236
+ */
13237
+ function newMessageId() {
13238
+ messagesNamed += 1;
13239
+ const origin = Math.round((globalThis.performance?.timeOrigin ?? 0) * 1000);
13240
+ return `hdev_m${origin.toString(36)}-${Date.now().toString(36)}-${messagesNamed.toString(36)}`;
13241
+ }
13242
+
13214
13243
  /**
13215
13244
  * Why a customer's file is refused by the desk's upload allowance per
13216
13245
  * customer (`customer_upload_limit_bytes`), as the 402 QUOTA_EXCEEDED that
@@ -16323,7 +16352,7 @@ function hostname(value) {
16323
16352
  }
16324
16353
  function resource(kind, value, field) {
16325
16354
  if (!isResourceIdOf(kind, value))
16326
- throw new ValidationError(`${field} must be a help desk ${kind} ID`, { field });
16355
+ throw new ValidationError(`${field} must be a help desk ${kind === 'ticketEvent' ? 'message' : kind} ID`, { field });
16327
16356
  return value;
16328
16357
  }
16329
16358
  function requestNumber(value) {
@@ -16795,9 +16824,14 @@ class HelpDeskClient {
16795
16824
  listEvents(number, cursor) {
16796
16825
  return this.send('GET', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets/${requestNumber(number)}/events`, undefined, { cursor });
16797
16826
  }
16798
- /** Replies have no client idempotency key: reconcile an uncertain response before retrying. */
16827
+ /** A new id for one composed reply, sent as `HelpDeskReplyOptions.eventId` with every send of it while it stands unchanged. */
16828
+ newReplyId() { return newMessageId(); }
16829
+ /** A reply sent under an `eventId` an earlier send of it posted answers that reply, posting nothing again. */
16799
16830
  replyToTicket(number, options, context) {
16800
- 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);
16831
+ const eventId = options.eventId === undefined ? undefined : resource('ticketEvent', options.eventId, 'eventId');
16832
+ return this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets/${requestNumber(number)}/replies`, {
16833
+ body: options.body, attachments: options.attachments ?? [], ...(eventId && { event_id: eventId }),
16834
+ }, undefined, true, context);
16801
16835
  }
16802
16836
  resolveTicket(number, context) { return this.send('POST', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets/${requestNumber(number)}/resolve`, undefined, undefined, true, context); }
16803
16837
  muteTicket(number, muted, context) { return this.send('PUT', apiPath `/v1/hd/desks/${this.desk.desk_id}/tickets/${requestNumber(number)}/mute`, { muted }, undefined, true, context); }
@@ -18856,18 +18890,29 @@ function openHelpDeskForm(client, options = {}) {
18856
18890
  }
18857
18891
 
18858
18892
  /** 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(' '));
18893
+ 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
18894
  const SEARCH_FIELD_WEIGHTS = [160, 140, 80, 60, 45, 10];
18895
+ // A match at least this strong comes from what an article is about (its title,
18896
+ // SEO title, keywords or summary), not its category label or body text.
18897
+ const SEARCH_STRONG_MATCH = 50;
18861
18898
  const SEARCH_MAX_QUERY_LENGTH = 300;
18862
18899
  const SEARCH_MAX_QUERY_TERMS = 12;
18863
18900
  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(' '));
18901
+ 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
18902
  const RECOMMEND_MAX_QUERY_LENGTH = 20000;
18866
- const RECOMMEND_MAX_KNOWN_TERMS = 36;
18867
18903
  const RECOMMEND_MAX_UNKNOWN_TERMS = 12;
18868
18904
 
18905
+ /**
18906
+ * Lowercase, accent-folded words. An English clitic stays with its word, typed
18907
+ * with a straight or curly apostrophe: 's, 'd, 'll, 're, 've and 'm drop
18908
+ * (Bee's is bee, I've is i) and n't joins (didn't is didnt), so a contraction
18909
+ * is one stop word rather than a fragment searched as a rare word.
18910
+ */
18869
18911
  function searchTokens(value) {
18870
- return String(value ?? '').toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '').match(/[\p{L}\p{N}]+/gu) || [];
18912
+ return String(value ?? '').toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '')
18913
+ .replace(/(\p{L})(?:['’ʼ](?:s|d|ll|re|ve|m))+(?![\p{L}\p{N}])/gu, '$1')
18914
+ .replace(/(\p{L})n['’ʼ]t(?![\p{L}\p{N}])/gu, '$1nt')
18915
+ .match(/[\p{L}\p{N}]+/gu) || [];
18871
18916
  }
18872
18917
  function searchCompare(left, right) {
18873
18918
  return left < right ? -1 : left > right ? 1 : 0;
@@ -18877,6 +18922,10 @@ function searchLowerBound(values, target) {
18877
18922
  while (lo < hi) { const mid = (lo + hi) >>> 1; if (values[mid] < target) lo = mid + 1; else hi = mid; }
18878
18923
  return lo;
18879
18924
  }
18925
+ /** A word's weight among the articles: 1 when every article holds it, more the fewer do. */
18926
+ function searchRarity(articles, holding) {
18927
+ return 1 + Math.log((articles + 1) / (holding + 1));
18928
+ }
18880
18929
  /** One insertion, deletion, substitution or adjacent transposition; never edit distance two. */
18881
18930
  function searchOneEdit(left, right) {
18882
18931
  if (left === right) return false;
@@ -18890,7 +18939,11 @@ function searchOneEdit(left, right) {
18890
18939
  return left.length > right.length ? left.slice(i + 1) === right.slice(i) : left.slice(i) === right.slice(i + 1);
18891
18940
  }
18892
18941
 
18893
- /** Prepare normalization, vocabulary and weighted postings once after the index downloads. */
18942
+ /**
18943
+ * Prepare normalization, vocabulary and weighted postings once after the index
18944
+ * downloads. A row's category_ids name its category and every category above
18945
+ * it, so filtering by a category includes its subcategories.
18946
+ */
18894
18947
  function prepareSearchIndex(rows) {
18895
18948
  const postings = new Map();
18896
18949
  const entries = (Array.isArray(rows) ? rows : []).map((article, index) => {
@@ -18904,8 +18957,11 @@ function prepareSearchIndex(rows) {
18904
18957
  }
18905
18958
  });
18906
18959
  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 };
18960
+ // The article's names, its title and SEO title, in the words a description is searched by.
18961
+ 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);
18962
+ return { article, fields, names, title: fields[0], categoryIds: Array.isArray(article.category_ids) ? article.category_ids : [], tie: `${article.path || ''}\u0000${article.id || ''}`, index };
18908
18963
  });
18964
+ for (const entry of entries) entry.names = entry.names.map(words => words.map(word => [word, searchRarity(entries.length, postings.get(word).size)]));
18909
18965
  const vocabulary = [...postings.keys()].sort(searchCompare);
18910
18966
  // A single edit preserves either the first or last character. These buckets
18911
18967
  // avoid scanning the entire vocabulary for every typo, including transpositions.
@@ -18920,11 +18976,13 @@ function prepareSearchIndex(rows) {
18920
18976
  return { entries, postings, vocabulary, typoBuckets };
18921
18977
  }
18922
18978
 
18923
- function searchTermMatches(prepared, term, mode) {
18979
+ /** The articles a term matches, each by its best word; `words` collects every word the term matched. */
18980
+ function searchTermMatches(prepared, term, mode, words = null) {
18924
18981
  const matches = new Map();
18925
18982
  const append = (word, multiplier, typo, minimumWeight = 0) => {
18926
18983
  for (const [index, weight] of prepared.postings.get(word) || []) {
18927
18984
  if (weight < minimumWeight) continue;
18985
+ words?.add(word);
18928
18986
  const score = Math.round(weight * multiplier);
18929
18987
  const previous = matches.get(index);
18930
18988
  if (!previous || score > previous.score || (score === previous.score && searchCompare(word, previous.word) < 0)) matches.set(index, { score, word, typo });
@@ -18963,7 +19021,7 @@ function searchRank(prepared, terms, phrase, categoryId, mode) {
18963
19021
  const results = [];
18964
19022
  for (const index of smallest.keys()) {
18965
19023
  const entry = prepared.entries[index];
18966
- if (categoryId !== null && entry.categoryId !== categoryId) continue;
19024
+ if (categoryId !== null && !entry.categoryIds.includes(categoryId)) continue;
18967
19025
  const parts = matches.map(map => map.get(index));
18968
19026
  if (parts.some(part => !part)) continue;
18969
19027
  let score = parts.reduce((sum, part) => sum + part.score, 0);
@@ -18973,65 +19031,119 @@ function searchRank(prepared, terms, phrase, categoryId, mode) {
18973
19031
  else if (` ${entry.fields[1]} `.includes(` ${phrase} `)) score += 1000;
18974
19032
  if (` ${entry.fields[3]} `.includes(` ${phrase} `)) score += 25;
18975
19033
  const typo = parts.some(part => part.typo);
18976
- results.push({ article: entry.article, score, matchedTerms: [...new Set(parts.map(part => part.word))], typo, entry });
19034
+ const strong = parts.some(part => part.score >= SEARCH_STRONG_MATCH);
19035
+ results.push({ article: entry.article, score, matchedTerms: [...new Set(parts.map(part => part.word))], typo, strong, entry });
18977
19036
  }
18978
19037
  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
19038
  return results;
18980
19039
  }
18981
19040
 
18982
- /** All query terms must match. Search falls back from exact/prefix to title substrings, then typos. */
19041
+ /**
19042
+ * The articles holding every meaningful word, falling back from exact/prefix
19043
+ * matches to title substrings, then typos; `complete` counts them. A query of
19044
+ * several words that no article holds in full reads as a question, and so does
19045
+ * one of three or more words that every complete match holds only in passing,
19046
+ * with no strong match (SEARCH_STRONG_MATCH): its partial matches are ranked
19047
+ * by relevance, as recommendations are. Otherwise a query of three or more
19048
+ * words lists those ranked matches after the articles holding every word, so
19049
+ * an article that merely holds them all does not hide the one the question is
19050
+ * about, and a query of one or two words lists only the articles holding them
19051
+ * all.
19052
+ */
18983
19053
  function searchKnowledgeBase(prepared, query, { limit = 20, offset = 0, categoryId = null } = {}) {
18984
19054
  const value = String(query ?? '').trim();
18985
- if (value.length < 2 || value.length > SEARCH_MAX_QUERY_LENGTH) return { results: [], total: 0 };
19055
+ if (value.length < 2 || value.length > SEARCH_MAX_QUERY_LENGTH) return { results: [], total: 0, complete: 0 };
18986
19056
  const raw = searchTokens(value);
18987
19057
  const meaningful = raw.filter(term => !SEARCH_STOP_WORDS.has(term));
18988
19058
  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');
19059
+ let ranked = [];
19060
+ // A longer query is not matched word for word: that bounds the work, and it
19061
+ // would rarely match.
19062
+ if (terms.length && terms.length <= SEARCH_MAX_QUERY_TERMS) {
19063
+ const phrase = terms.join(' ');
19064
+ ranked = searchRank(prepared, terms, phrase, categoryId, 'exact');
19065
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'substring');
19066
+ if (!ranked.length) ranked = searchRank(prepared, terms, phrase, categoryId, 'typo');
19067
+ }
19068
+ const complete = ranked.length;
19069
+ // Relevance ranking matches a single word through the same stages, so for one
19070
+ // word it could only drop some of the articles holding it. Two words are a
19071
+ // keyword search: the articles holding both, however weakly, answer it, not
19072
+ // articles naming one of them in a title.
19073
+ if (terms.length > 1 && (!complete || (terms.length >= 3 && !ranked.some(hit => hit.strong)))) {
19074
+ const related = recommendationRank(prepared, value, categoryId);
19075
+ if (related.length) ranked = related;
19076
+ } else if (terms.length >= 3) {
19077
+ const listed = new Set(ranked.map(hit => hit.entry.index));
19078
+ ranked = [...ranked, ...recommendationRank(prepared, value, categoryId).filter(hit => !listed.has(hit.entry.index))];
19079
+ }
18994
19080
  const start = Number.isSafeInteger(offset) && offset >= 0 ? offset : 0;
18995
19081
  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 };
19082
+ return { results: ranked.slice(start, start + size).map(({ article, score, matchedTerms, typo }) => ({ article, score, matchedTerms, typo })), total: ranked.length, complete };
18997
19083
  }
18998
19084
 
18999
- /** Select bounded, useful terms without making a long description an AND query. */
19085
+ /**
19086
+ * The words free text is searched by: every word the index holds, wherever it
19087
+ * comes, since in a large knowledge base nearly every everyday word is some
19088
+ * article's title word and no budget can tell the topic from the asides; and
19089
+ * a few words it does not hold (the most repeated, then the longest, then the
19090
+ * earliest) for prefix, substring and typo recovery. The text's length bounds
19091
+ * the work, as a word the index holds is matched only as itself or a prefix.
19092
+ */
19000
19093
  function recommendationTerms(prepared, issue) {
19001
19094
  const terms = new Map();
19002
19095
  const raw = searchTokens(String(issue ?? '').slice(0, RECOMMEND_MAX_QUERY_LENGTH));
19003
19096
  for (const term of raw) {
19004
19097
  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 });
19098
+ if (!terms.has(term)) terms.set(term, { term, frequency: 0, order: terms.size, known: prepared.postings.has(term) });
19006
19099
  terms.get(term).frequency++;
19007
19100
  }
19008
19101
  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);
19102
+ 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);
19103
+ return [...values.filter(value => value.known), ...unknown].sort((a, b) => a.order - b.order).map(value => value.term);
19104
+ }
19105
+ /** How much of an article's title or SEO title, by weight, the mentioned words name: 0 to 1. */
19106
+ function searchNamed(entry, mentioned) {
19107
+ let named = 0;
19108
+ for (const name of entry.names) {
19109
+ let covered = 0; let total = 0;
19110
+ for (const [word, weight] of name) { total += weight; if (mentioned.has(word)) covered += weight; }
19111
+ named = Math.max(named, covered / total);
19112
+ }
19113
+ return named;
19014
19114
  }
19015
-
19016
19115
  /**
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.
19116
+ * Rank articles for free text. Each matched word adds its strongest field's
19117
+ * weight times its rarity among the articles. An article qualifies when it
19118
+ * answers a quarter of the text's searchable weight with a title, SEO,
19119
+ * keyword or summary match, or half of it through its body alone, or when the
19120
+ * text names it, mentioning words that carry half the weight of its title or
19121
+ * SEO title: a long description's incidental words dilute every article's
19122
+ * share of it, but not how fully it names the one it is about. Being named
19123
+ * raises an article's score by up to double.
19021
19124
  */
19022
- function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null } = {}) {
19125
+ function recommendationRank(prepared, issue, categoryId) {
19023
19126
  const terms = recommendationTerms(prepared, issue);
19024
- if (!terms.length) return { results: [], total: 0 };
19025
19127
  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;
19128
+ const mentioned = new Set();
19129
+ const withinCategory = matches => categoryId === null ? matches : new Map([...matches].filter(([index]) => prepared.entries[index].categoryIds.includes(categoryId)));
19130
+ let totalWeight = 0;
19028
19131
  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'));
19132
+ // Recovery, as a substring and then a typo, is for a word the index does
19133
+ // not hold. A word it holds is matched only as itself or a prefix, even
19134
+ // where a category filter leaves it nothing: it is no misspelling of
19135
+ // another word, and a long description would otherwise scan the whole
19136
+ // vocabulary once for each of its words.
19137
+ let words; let matches = new Map();
19138
+ for (const mode of prepared.postings.has(term) ? ['exact'] : ['exact', 'substring', 'typo']) {
19139
+ words = new Set();
19140
+ matches = withinCategory(searchTermMatches(prepared, term, mode, words));
19141
+ if (matches.size) break;
19142
+ }
19032
19143
  if (!matches.size) continue;
19033
- const weight = 1 + Math.log((prepared.entries.length + 1) / (matches.size + 1));
19034
- totalWeight += weight; searchableTerms++;
19144
+ for (const word of words) mentioned.add(word);
19145
+ const weight = searchRarity(prepared.entries.length, matches.size);
19146
+ totalWeight += weight;
19035
19147
  for (const [index, part] of matches) {
19036
19148
  if (!candidates.has(index)) candidates.set(index, { entry: prepared.entries[index], score: 0, matchedTerms: [], count: 0, weight: 0, strongest: 0, typo: false });
19037
19149
  const hit = candidates.get(index);
@@ -19042,16 +19154,28 @@ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null
19042
19154
  }
19043
19155
  const ranked = [];
19044
19156
  for (const hit of candidates.values()) {
19045
- const coverage = hit.weight / totalWeight;
19046
- const strong = hit.strongest >= 50;
19157
+ const strong = hit.strongest >= SEARCH_STRONG_MATCH;
19047
19158
  // One clear keyword is useful. Within a paragraph, a weak body-only match
19048
19159
  // needs corroboration; category names alone must not recommend every page.
19049
19160
  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 });
19161
+ const answered = hit.weight / totalWeight;
19162
+ const named = searchNamed(hit.entry, mentioned);
19163
+ if (strong ? answered < 0.25 && named < 0.5 : answered < 0.5) continue;
19164
+ 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
19165
  }
19054
19166
  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);
19167
+ return ranked;
19168
+ }
19169
+
19170
+ /**
19171
+ * Recommend published answers for a paragraph using the same prepared postings,
19172
+ * normalization, field weights and bounded spelling recovery as normal search.
19173
+ * Unknown details do not veto an otherwise relevant answer. A hit's coverage
19174
+ * is the larger of the share of the paragraph it answers and how fully the
19175
+ * paragraph names it.
19176
+ */
19177
+ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null } = {}) {
19178
+ const ranked = recommendationRank(prepared, issue, categoryId);
19055
19179
  const size = Number.isSafeInteger(limit) && limit >= 0 ? Math.min(limit, 20) : 5;
19056
19180
  return { results: ranked.slice(0, size).map(({ article, score, matchedTerms, typo, coverage }) => ({ article, score, matchedTerms, typo, coverage })), total: ranked.length };
19057
19181
  }
@@ -19060,15 +19184,15 @@ function recommendKnowledgeBase(prepared, issue, { limit = 5, categoryId = null
19060
19184
  [
19061
19185
  `const SEARCH_STOP_WORDS=new Set(${JSON.stringify([...SEARCH_STOP_WORDS])});`,
19062
19186
  `const SEARCH_FIELD_WEIGHTS=${JSON.stringify(SEARCH_FIELD_WEIGHTS)};`,
19187
+ `const SEARCH_STRONG_MATCH=${SEARCH_STRONG_MATCH};`,
19063
19188
  `const SEARCH_MAX_QUERY_LENGTH=${SEARCH_MAX_QUERY_LENGTH};`,
19064
19189
  `const SEARCH_MAX_QUERY_TERMS=${SEARCH_MAX_QUERY_TERMS};`,
19065
19190
  `const SEARCH_MAX_TYPO_LENGTH=${SEARCH_MAX_TYPO_LENGTH};`,
19066
19191
  `const RECOMMEND_STOP_WORDS=new Set(${JSON.stringify([...RECOMMEND_STOP_WORDS])});`,
19067
19192
  `const RECOMMEND_MAX_QUERY_LENGTH=${RECOMMEND_MAX_QUERY_LENGTH};`,
19068
- `const RECOMMEND_MAX_KNOWN_TERMS=${RECOMMEND_MAX_KNOWN_TERMS};`,
19069
19193
  `const RECOMMEND_MAX_UNKNOWN_TERMS=${RECOMMEND_MAX_UNKNOWN_TERMS};`,
19070
- searchTokens, searchCompare, searchLowerBound, searchOneEdit, prepareSearchIndex,
19071
- searchTermMatches, searchRank, searchKnowledgeBase, recommendationTerms, recommendKnowledgeBase,
19194
+ searchTokens, searchCompare, searchLowerBound, searchRarity, searchOneEdit, prepareSearchIndex,
19195
+ searchTermMatches, searchRank, searchKnowledgeBase, recommendationTerms, searchNamed, recommendationRank, recommendKnowledgeBase,
19072
19196
  ].map(value => typeof value === 'function' ? value.toString() : value).join('\n') + '\nexport { prepareSearchIndex, searchKnowledgeBase, recommendKnowledgeBase };\n';
19073
19197
 
19074
19198
  /** One published-KB transport and shared local search engine for support entry points. */
@@ -26049,7 +26173,7 @@ class SparkVault {
26049
26173
  }
26050
26174
  /** Get the SDK version */
26051
26175
  static get version() {
26052
- return '15.11.3';
26176
+ return '15.11.5';
26053
26177
  }
26054
26178
  }
26055
26179
  if (typeof window !== 'undefined') {