scripture-guide 1.0.95 → 1.1.1

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
@@ -61,6 +61,7 @@ lookupReference('1 Nephi 3:7', { language: 'en', canon: 'lds' });
61
61
  | `options` | string \| object | If string, treated as language code |
62
62
  | `options.language` | string | Language code |
63
63
  | `options.canon` | string | Canon: `'lds'`, `'rlds'`, etc. |
64
+ | `options.maxVerses` | number | The most verses one range expands to (default 1000). A longer range is cut there |
64
65
 
65
66
  > **Backward Compatibility:** The old 3-parameter signature `lookupReference(query, language, config)` is deprecated but still supported.
66
67
 
@@ -1,4 +1,4 @@
1
- /* scripture-guide v1.0.95 */
1
+ /* scripture-guide v1.1.1 */
2
2
  var __defProp = Object.defineProperty;
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
@@ -45,6 +45,7 @@ __export(scriptures_exports, {
45
45
  setCanon: () => setCanon,
46
46
  setLang: () => setLanguage,
47
47
  setLanguage: () => setLanguage,
48
+ toSlug: () => toSlug,
48
49
  verseId2Ref: () => generateReference
49
50
  });
50
51
  module.exports = __toCommonJS(scriptures_exports);
@@ -898,7 +899,7 @@ var structure_default = {
898
899
  "first_verse_id": 17317
899
900
  },
900
901
  {
901
- "key": "solomon_s_song",
902
+ "key": "song_of_solomon",
902
903
  "order": 22,
903
904
  "chapters": 8,
904
905
  "verses": [
@@ -2538,9 +2539,11 @@ var en_default = {
2538
2539
  ]
2539
2540
  },
2540
2541
  "song_of_solomon": {
2541
- "name": "Song of Solomon",
2542
- "pattern": "(?<!solomon's )(the )*song*\\.*(?: *of *solomon)*",
2542
+ "name": "Solomon's Song",
2543
+ "pattern": "(?<!solomon['\u2019]?s )(the )*song*\\.*(?: *of *solomon)*",
2543
2544
  "alt": [
2545
+ "solomon\u2019s song",
2546
+ "solomons song",
2544
2547
  "song",
2545
2548
  "sos",
2546
2549
  "ss",
@@ -3249,6 +3252,16 @@ var en_default3 = {
3249
3252
  "cited at",
3250
3253
  "also"
3251
3254
  ],
3255
+ "capitalized_only": [
3256
+ "is",
3257
+ "am",
3258
+ "he",
3259
+ "re",
3260
+ "la",
3261
+ "co",
3262
+ "col",
3263
+ "act"
3264
+ ],
3252
3265
  "pre_rules": [
3253
3266
  [
3254
3267
  "\\bgospel\\s+(?:of|according\\s+to)\\s+",
@@ -3310,6 +3323,10 @@ var en_default3 = {
3310
3323
  "\\bfourth\\s+(?=[A-Za-z])",
3311
3324
  "4 "
3312
3325
  ],
3326
+ [
3327
+ "(\\d)\\s+&\\s+",
3328
+ "$1; "
3329
+ ],
3313
3330
  [
3314
3331
  "[.]{2,}",
3315
3332
  ";"
@@ -31294,7 +31311,8 @@ function buildRegexData() {
31294
31311
  books,
31295
31312
  pre_rules: en_default3.pre_rules || [],
31296
31313
  post_rules: en_default3.post_rules || [],
31297
- joiners: en_default3.joiners || []
31314
+ joiners: en_default3.joiners || [],
31315
+ capitalized_only: en_default3.capitalized_only || []
31298
31316
  };
31299
31317
  }
31300
31318
  function transformBooks(bibleBooks, ldsBooks) {
@@ -31464,10 +31482,12 @@ var rangesOverlap = (range1, range2) => {
31464
31482
  var removeOverlaps = (matches, content, preferenceResolver = null) => {
31465
31483
  if (matches.length <= 1) return matches;
31466
31484
  const result = [];
31485
+ const sorted = matches.every((m, i) => i === 0 || m[0] >= matches[i - 1][0]);
31486
+ let includedMaxEnd = -Infinity;
31467
31487
  for (let i = 0; i < matches.length; i++) {
31468
31488
  const current = matches[i];
31469
31489
  let shouldInclude = true;
31470
- for (const included of result) {
31490
+ if (!sorted || includedMaxEnd > current[0]) for (const included of result) {
31471
31491
  if (rangesOverlap(current, included)) {
31472
31492
  shouldInclude = false;
31473
31493
  break;
@@ -31476,6 +31496,7 @@ var removeOverlaps = (matches, content, preferenceResolver = null) => {
31476
31496
  if (shouldInclude) {
31477
31497
  for (let j = i + 1; j < matches.length; j++) {
31478
31498
  const next = matches[j];
31499
+ if (sorted && next[0] >= current[1]) break;
31479
31500
  if (rangesOverlap(current, next)) {
31480
31501
  if (preferenceResolver) {
31481
31502
  const preferred = preferenceResolver(current, next, content);
@@ -31496,10 +31517,27 @@ var removeOverlaps = (matches, content, preferenceResolver = null) => {
31496
31517
  }
31497
31518
  if (shouldInclude) {
31498
31519
  result.push(current);
31520
+ includedMaxEnd = Math.max(includedMaxEnd, current[1]);
31499
31521
  }
31500
31522
  }
31501
31523
  return result;
31502
31524
  };
31525
+ var spanCoverage = (spans) => {
31526
+ const sorted = [...spans || []].sort((a, b) => a[0] - b[0]);
31527
+ const maxEnd = [];
31528
+ for (let i = 0; i < sorted.length; i++) maxEnd.push(Math.max(sorted[i][1], i ? maxEnd[i - 1] : -Infinity));
31529
+ return (position) => {
31530
+ let lo = 0, hi = sorted.length - 1, last = -1;
31531
+ while (lo <= hi) {
31532
+ const mid = lo + hi >> 1;
31533
+ if (sorted[mid][0] <= position) {
31534
+ last = mid;
31535
+ lo = mid + 1;
31536
+ } else hi = mid - 1;
31537
+ }
31538
+ return last >= 0 && maxEnd[last] > position;
31539
+ };
31540
+ };
31503
31541
  var calculateGaps = (matches) => {
31504
31542
  return matches.reduce((prev, current, index) => {
31505
31543
  if (index === 0) return prev;
@@ -31543,7 +31581,7 @@ var mergeAdjacentMatches = (matches, gapMergeFlags, compatibilityCheck = null) =
31543
31581
  if (prevIndex.length > 2 && current.length > 2) {
31544
31582
  const startPos = prevIndex[0];
31545
31583
  const endPos = current[1];
31546
- const combinedText = prevIndex[2] + ";" + current[2];
31584
+ const combinedText = prevIndex[2] + "; " + current[2];
31547
31585
  const combinedVerseIds = [...prevIndex[3] || [], ...current[3] || []];
31548
31586
  const merged = [startPos, endPos, combinedText, combinedVerseIds];
31549
31587
  prev[prev.length - 1] = merged;
@@ -31560,6 +31598,7 @@ var mergeAdjacentMatches = (matches, gapMergeFlags, compatibilityCheck = null) =
31560
31598
  };
31561
31599
  var gapCanMerge = (gapString, joiners) => {
31562
31600
  if (!/\S/.test(gapString)) return true;
31601
+ if (/^\s*\./.test(gapString)) return false;
31563
31602
  const list = Array.isArray(joiners) ? joiners : joiners && joiners.patterns || [];
31564
31603
  let residue = gapString;
31565
31604
  for (const joiner of list) {
@@ -31616,24 +31655,29 @@ var findMatches = (content, books, lang_extra) => {
31616
31655
  normalizedContent = normalizedContent.replace(new RegExp(entity, "g"), unicode);
31617
31656
  });
31618
31657
  const tail = lang_extra.tail ? new RegExp(lang_extra.tail, "ig") : /[^0-9]+$/;
31619
- const preBookMatch = lang_extra.book || `(First|I|1|1st|Second|II|2|2nd|Third|III|3|3rd|Fourth|IV|4|4th)*\\s*(books* of)*\\s*`;
31658
+ const preBookMatch = lang_extra.book || `(?:(?:First|Second|Third|Fourth|1st|2nd|3rd|4th|III|II|IV|I|[1-4])\\s*)?(?:books? of\\s*)?`;
31620
31659
  const matchingBooks = findMatchingBooks(normalizedContent, books);
31621
31660
  const gap = "[ \\t]*(?:\\n(?![ \\t]*\\n)[ \\t]*)?(?:,[ \\t]*sec(?:tion)?\\.?[ \\t]*)?\\(?[ \\t]*(?=[0-9])";
31622
31661
  const core = "(?:[0-9:.;,~\u2014\u2013-]|[ \\t]|\\n(?![ \\t]*\\n)|and\\b|cf\\b|\\()*[0-9]";
31623
31662
  const postBookMatch = lang_extra.chapter || gap + core;
31663
+ const capitalizedOnlyAbbreviations = new Set(
31664
+ (lang_extra.capitalizedOnly || []).map((i) => String(i).toLowerCase())
31665
+ );
31624
31666
  const fullBookMatches = matchingBooks.map((bookMatch) => {
31625
31667
  const patternString = preBookMatch + bookMatch;
31626
31668
  const pattern = new RegExp(patternString, "ig");
31627
31669
  const stringMatch = pattern.test(normalizedContent) ? patternString : null;
31628
31670
  return stringMatch;
31629
31671
  }).filter((x) => !!x);
31630
- const bookSubStrings = fullBookMatches.map((bookMatch) => {
31672
+ const allBookSubStrings = fullBookMatches.map((bookMatch) => {
31631
31673
  const substrings = normalizedContent.match(new RegExp(bookMatch, "ig")).flat();
31632
31674
  return substrings;
31633
- }).flat().reduce((prev, current) => {
31634
- if (prev.includes(current)) return prev;
31635
- return [...prev, current];
31636
- }, []).filter((i) => !!i).map((substring) => {
31675
+ }).flat();
31676
+ const bookSubStrings = [...new Set(allBookSubStrings)].filter((i) => !!i).filter((substring) => {
31677
+ const token = substring.trim();
31678
+ if (!capitalizedOnlyAbbreviations.has(token.toLowerCase())) return true;
31679
+ return token !== token.toLowerCase();
31680
+ }).map((substring) => {
31637
31681
  substring = substring.trim();
31638
31682
  let positions = [];
31639
31683
  let index = normalizedContent.indexOf(substring);
@@ -31653,39 +31697,54 @@ var findMatches = (content, books, lang_extra) => {
31653
31697
  return [substring, positions];
31654
31698
  }).filter((i) => !!i);
31655
31699
  const possiblyOverlappingMatches = bookSubStrings.map(([substring, positions]) => {
31700
+ let pattern = null;
31701
+ try {
31702
+ pattern = new RegExp(substring + postBookMatch, "iy");
31703
+ } catch (e) {
31704
+ return [];
31705
+ }
31656
31706
  return positions.map(
31657
31707
  (i) => {
31658
- let pattern = null;
31659
- try {
31660
- pattern = new RegExp(substring + postBookMatch, "ig");
31661
- } catch (e) {
31662
- return null;
31663
- }
31664
- const match = normalizedContent.slice(i).match(pattern)?.[0]?.replace(tail, "").trim();
31708
+ pattern.lastIndex = i;
31709
+ const match = pattern.exec(normalizedContent)?.[0]?.replace(tail, "").trim();
31665
31710
  if (!match) return null;
31666
31711
  const len = match.length;
31667
31712
  const pos = i;
31668
31713
  const [posIn, posOut] = [pos, pos + len];
31714
+ if (/[0-9]$/.test(match) && /[A-Z]/.test(normalizedContent[posOut] || "")) return null;
31669
31715
  return [match, posIn, posOut];
31670
31716
  }
31671
31717
  );
31672
31718
  }).flat().filter((i) => !!i);
31719
+ const byStart = [...possiblyOverlappingMatches].sort((a, b) => a[1] - b[1]);
31720
+ const maxEndUpTo = [];
31721
+ byStart.forEach(([, , e1], i) => maxEndUpTo.push(Math.max(e1, i ? maxEndUpTo[i - 1] : -Infinity)));
31722
+ const cutPoint = (string, end) => {
31723
+ let lo = 0, hi = byStart.length - 1, first = byStart.length;
31724
+ while (lo <= hi) {
31725
+ const mid = lo + hi >> 1;
31726
+ if (maxEndUpTo[mid] > end) {
31727
+ first = mid;
31728
+ hi = mid - 1;
31729
+ } else lo = mid + 1;
31730
+ }
31731
+ for (let k = first; k < byStart.length && byStart[k][1] < end; k++) {
31732
+ const [s, s1, e1] = byStart[k];
31733
+ if (s !== string && e1 > end) return s1;
31734
+ }
31735
+ return end;
31736
+ };
31673
31737
  const matchesWithReferences = possiblyOverlappingMatches.map(([string, start, end]) => {
31674
- const overLappingItems = possiblyOverlappingMatches.filter(([s, s1, e1]) => s !== string && s1 < end && e1 > end);
31675
- const hasOverlap = overLappingItems.length > 0;
31676
- const newEnd = hasOverlap ? Math.min(...overLappingItems.map(([s, s1, e1]) => s1)) : end;
31738
+ const newEnd = cutPoint(string, end);
31677
31739
  const newString = normalizedContent.slice(start, newEnd);
31678
31740
  return newString.replace(tail, "").trim();
31679
31741
  }).filter((i) => !!i);
31680
- const matches = matchesWithReferences.map((string) => {
31742
+ const matches = [...new Set(matchesWithReferences)].map((string) => {
31681
31743
  const pattern = new RegExp(string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "ig");
31682
31744
  const matches2 = normalizedContent.match(pattern)?.map((i) => i.trim().replace(tail, ""));
31683
31745
  return matches2;
31684
- }).flat().reduce((prev, current) => {
31685
- if (prev.includes(current)) return prev;
31686
- return [...prev, current];
31687
- }, []).filter((i) => !!i);
31688
- return matches;
31746
+ }).flat();
31747
+ return [...new Set(matches)].filter((i) => !!i);
31689
31748
  };
31690
31749
  function findMatchIndexes(content, matches, lookupReference2, lang_extra) {
31691
31750
  const tail = lang_extra.tail ? new RegExp(lang_extra.tail, "ig") : /[^0-9]+$/;
@@ -31708,6 +31767,7 @@ function findMatchIndexes(content, matches, lookupReference2, lang_extra) {
31708
31767
  const next = array[index + 1];
31709
31768
  if (next && next[0] < end && next[1] > end) {
31710
31769
  end = next[0];
31770
+ end = start + content.slice(start, end).replace(tail, "").length;
31711
31771
  }
31712
31772
  return [start, end];
31713
31773
  });
@@ -31755,7 +31815,7 @@ var processReferenceDetection = (content, books, lang_extra, lookupReference2, c
31755
31815
  var collectReferencesWithContext = (content, books, lang_extra, lookupReference2, options) => {
31756
31816
  const explicitMatches = findMatches(content, books, lang_extra);
31757
31817
  const explicitIndices = findMatchIndexes(content, explicitMatches, lookupReference2, lang_extra) || [];
31758
- const impliedMatches = findImpliedReferences(content, explicitMatches, explicitIndices, lookupReference2, options);
31818
+ const impliedMatches = findImpliedReferences(content, explicitMatches, explicitIndices, lookupReference2, options, lang_extra);
31759
31819
  const explicitMatchesWithRefs = explicitIndices.map(([start, end]) => {
31760
31820
  const originalText = content.substring(start, end);
31761
31821
  const verification = lookupReference2(originalText);
@@ -31846,7 +31906,21 @@ var getNearestBookContext = (position, bookContexts, maxDistance) => {
31846
31906
  }
31847
31907
  return bestContext;
31848
31908
  };
31849
- var findImpliedReferences = (content, explicitMatches, explicitIndices, lookupReference2, options) => {
31909
+ var CITATION_CONNECTIVES = ["including", "namely", "e.g", "i.e"];
31910
+ var bindsToBookContext = (tail, joiners) => {
31911
+ const trimmed = tail.replace(/\s+$/, "");
31912
+ if (!trimmed) return true;
31913
+ if (/[;&([]$/.test(trimmed)) return true;
31914
+ const list = Array.isArray(joiners) ? joiners : joiners && joiners.patterns || [];
31915
+ const words = /* @__PURE__ */ new Set([
31916
+ ...list.filter((j) => typeof j === "string" && /[a-z]/i.test(j)).map((j) => j.toLowerCase().replace(/\.+$/, "").split(/\s+/).pop()),
31917
+ ...CITATION_CONNECTIVES
31918
+ ]);
31919
+ const lastWord = (trimmed.match(/[A-Za-z.']+$/) || [""])[0].toLowerCase().replace(/[.']+$/, "");
31920
+ return lastWord !== "" && words.has(lastWord);
31921
+ };
31922
+ var findImpliedReferences = (content, explicitMatches, explicitIndices, lookupReference2, options, lang_extra = {}) => {
31923
+ const joiners = lang_extra && (lang_extra.unrestrictedJoiners || lang_extra.joiners) || ["and", ";", ",", "&", "compare", "see also", "see", "cf", "c.f.", "cited at", "also"];
31850
31924
  const matches = [];
31851
31925
  const bookContexts = findBookContexts(content, explicitMatches, explicitIndices, lookupReference2);
31852
31926
  const verseGroupPattern = /\b(?:vv?\.?\s*|vs\.?\s*|verses?\s+)([\d:,\s–—-]+?)(?=\s*[).;\n]|$)/gi;
@@ -31865,19 +31939,21 @@ var findImpliedReferences = (content, explicitMatches, explicitIndices, lookupRe
31865
31939
  }
31866
31940
  }
31867
31941
  const chapterVersePattern = /\b(\d+):(\d+(?:[–—-]\d+)?(?:\s*,\s*\d+(?:[–—-]\d+)?)*)/g;
31942
+ const insideExplicit = spanCoverage(explicitIndices || []);
31868
31943
  while ((match = chapterVersePattern.exec(content)) !== null) {
31869
31944
  const fullMatch = match[0];
31870
31945
  const chapter = match[1];
31871
31946
  const verses = match[2];
31872
31947
  const position = match.index;
31873
- const isPartOfExplicit = explicitIndices && explicitIndices.some(
31874
- ([start, end]) => position >= start && position < end
31875
- );
31948
+ const isPartOfExplicit = insideExplicit(position);
31876
31949
  if (isPartOfExplicit) {
31877
31950
  continue;
31878
31951
  }
31952
+ if (/^\s*(?:[ap]\.?\s?m\b\.?|o['’]?clock\b)/i.test(content.slice(position + fullMatch.length))) {
31953
+ continue;
31954
+ }
31879
31955
  const context = getNearestBookContext(position, bookContexts, options.maxContextDistance);
31880
- if (context) {
31956
+ if (context && (options.strictImpliedBooks === false || bindsToBookContext(content.slice(context.endPosition, position), joiners))) {
31881
31957
  const impliedRef = `${context.book} ${chapter}:${verses}`;
31882
31958
  const verification = lookupReference2(impliedRef);
31883
31959
  if (verification.verse_ids && verification.verse_ids.length > 0) {
@@ -31974,6 +32050,11 @@ var convertCanon = (verseIds, options = {}) => {
31974
32050
  return result;
31975
32051
  };
31976
32052
 
32053
+ // src/slug.mjs
32054
+ function toSlug(ref) {
32055
+ return ref.trim().toLowerCase().replace(/[־᠆‐‒–—―﹣-‑]+/gu, "-").replace(/[\s:]+/g, ".").replace(/\.+/g, ".").replace(/;\./g, ";").replace(/,\./g, ",").replace(/\.;/g, ";").replace(/\.,/g, ",");
32056
+ }
32057
+
31977
32058
  // src/config.mjs
31978
32059
  var MAX_RANGE_SIZE = 1e3;
31979
32060
  var MAX_CHAPTER = 200;
@@ -32007,11 +32088,20 @@ for (const [canonKey, canonData] of Object.entries(extraCanons)) {
32007
32088
  });
32008
32089
  }
32009
32090
  }
32010
- var indexCache = {
32011
- refIndex: null,
32012
- refIndexHash: null,
32013
- verseIdIndex: null,
32014
- verseIdIndexHash: null
32091
+ var INDEX_CACHE_LIMIT = 4;
32092
+ var refIndexCache = /* @__PURE__ */ new Map();
32093
+ var verseIdIndexCache = /* @__PURE__ */ new Map();
32094
+ var cachedIndex = (cache, key, build) => {
32095
+ if (cache.has(key)) {
32096
+ const value2 = cache.get(key);
32097
+ cache.delete(key);
32098
+ cache.set(key, value2);
32099
+ return value2;
32100
+ }
32101
+ const value = build();
32102
+ cache.set(key, value);
32103
+ if (cache.size > INDEX_CACHE_LIMIT) cache.delete(cache.keys().next().value);
32104
+ return value;
32015
32105
  };
32016
32106
  var hashConfig = (config) => {
32017
32107
  return (config?.language || "en") + ":" + (config?.canon || DEFAULTS.canon);
@@ -32088,7 +32178,8 @@ var lookupReference = function(query, optionsOrLanguage = {}, legacyConfig = nul
32088
32178
  const effectiveLanguage = getEffectiveLanguage(language);
32089
32179
  const { convertTo, includeParallel } = lookupConfig;
32090
32180
  const canon = lookupConfig.canon || getEffectiveCanon();
32091
- const lookupResult = lookupInLanguage(query, effectiveLanguage, canon);
32181
+ const limit = rangeLimit(lookupConfig.maxVerses);
32182
+ const lookupResult = lookupInLanguage(query, effectiveLanguage, canon, limit);
32092
32183
  const verse_ids = lookupResult.verse_ids;
32093
32184
  const errors = lookupResult.errors;
32094
32185
  if (verse_ids?.length) {
@@ -32117,7 +32208,7 @@ var lookupReference = function(query, optionsOrLanguage = {}, legacyConfig = nul
32117
32208
  return result;
32118
32209
  }
32119
32210
  if (!lookupConfig.noMulti) {
32120
- const fallbackResult = lookupWithLanguageFallback(query, effectiveLanguage, canon);
32211
+ const fallbackResult = lookupWithLanguageFallback(query, effectiveLanguage, canon, limit);
32121
32212
  if (fallbackResult.verse_ids.length === 0 && errors) {
32122
32213
  fallbackResult.error = errors.join("; ");
32123
32214
  }
@@ -32130,14 +32221,17 @@ var lookupReference = function(query, optionsOrLanguage = {}, legacyConfig = nul
32130
32221
  error: errors ? errors.join("; ") : void 0
32131
32222
  };
32132
32223
  };
32133
- var lookupInLanguage = function(query, language, canon = null) {
32224
+ var rangeLimit = function(maxVerses) {
32225
+ return Number.isInteger(maxVerses) && maxVerses > 0 ? maxVerses : MAX_RANGE_SIZE;
32226
+ };
32227
+ var lookupInLanguage = function(query, language, canon = null, limit = MAX_RANGE_SIZE) {
32134
32228
  const config = getLanguageConfig(language, canon);
32135
32229
  let ref = cleanReference(query, config);
32136
32230
  let refs = splitReferences(ref, config);
32137
32231
  let verse_ids = [];
32138
32232
  let errors = [];
32139
32233
  for (let i in refs) {
32140
- const result = lookupSingleRef(refs[i], config);
32234
+ const result = lookupSingleRef(refs[i], config, limit);
32141
32235
  if (result && result.error) {
32142
32236
  errors.push(result.error);
32143
32237
  } else if (Array.isArray(result)) {
@@ -32151,10 +32245,17 @@ var lookupInLanguage = function(query, language, canon = null) {
32151
32245
  errors: errors.length > 0 ? errors : void 0
32152
32246
  };
32153
32247
  };
32154
- var lookupWithLanguageFallback = function(query, targetLanguage, canon = null) {
32248
+ var detectionLookup = function(language) {
32249
+ const seen = /* @__PURE__ */ new Map();
32250
+ return (query) => {
32251
+ if (!seen.has(query)) seen.set(query, lookupReference(query, { language, noMulti: true }));
32252
+ return seen.get(query);
32253
+ };
32254
+ };
32255
+ var lookupWithLanguageFallback = function(query, targetLanguage, canon = null, limit = MAX_RANGE_SIZE) {
32155
32256
  const fallbackLanguages = targetLanguage !== "en" ? ["en", ...Object.keys(raw_lang).filter((lang) => lang !== "en" && lang !== targetLanguage)] : Object.keys(raw_lang).filter((lang) => lang !== targetLanguage);
32156
32257
  for (const lang of fallbackLanguages) {
32157
- const lookupResult = lookupInLanguage(query, lang, canon);
32258
+ const lookupResult = lookupInLanguage(query, lang, canon, limit);
32158
32259
  const verse_ids = lookupResult.verse_ids;
32159
32260
  if (verse_ids?.length) {
32160
32261
  const refInTargetLanguage = generateReference(verse_ids, { language: targetLanguage, canon });
@@ -32171,9 +32272,9 @@ var lookupWithLanguageFallback = function(query, targetLanguage, canon = null) {
32171
32272
  "verse_ids": []
32172
32273
  };
32173
32274
  };
32174
- var lookupSingleRef = function(ref, config) {
32275
+ var lookupSingleRef = function(ref, config, limit = MAX_RANGE_SIZE) {
32175
32276
  const booksWithDashRegex = /^(joseph|조셉)/i;
32176
- if (!booksWithDashRegex.test(ref) && ref.match(/[—-](\d\s)*[\D]/ig)) return lookupMultiBookRange(ref, config);
32277
+ if (!booksWithDashRegex.test(ref) && ref.match(/[—-](\d\s)*[\D]/ig)) return lookupMultiBookRange(ref, config, limit);
32177
32278
  let book = getBook(ref, config);
32178
32279
  if (!book) {
32179
32280
  return {
@@ -32182,7 +32283,7 @@ var lookupSingleRef = function(ref, config) {
32182
32283
  };
32183
32284
  }
32184
32285
  let ranges = getRanges(ref, book);
32185
- let verse_ids = loadVerseIds(book, ranges, config);
32286
+ let verse_ids = loadVerseIds(book, ranges, config, limit);
32186
32287
  return verse_ids;
32187
32288
  };
32188
32289
  var validateVerseIdsMixed = function(verse_ids) {
@@ -32218,7 +32319,7 @@ var generateReference = function(verse_ids, optionsOrLanguage = {}, legacyOption
32218
32319
  let ref = refs.join("; ");
32219
32320
  return ref;
32220
32321
  };
32221
- var lookupMultiBookRange = function(cleanRef, config) {
32322
+ var lookupMultiBookRange = function(cleanRef, config, limit = MAX_RANGE_SIZE) {
32222
32323
  let range = cleanRef.split(/[—-]/);
32223
32324
  if (!range[0].match(/[:]/)) {
32224
32325
  if (range[0].match(/\d+\s*$/)) range[0] = range[0].trim() + ":1";
@@ -32239,7 +32340,7 @@ var lookupMultiBookRange = function(cleanRef, config) {
32239
32340
  let end = lookupSingleRef(range[1], config)[0];
32240
32341
  let all_verse_ids = [];
32241
32342
  for (let i = start; i <= end; i++) {
32242
- if (all_verse_ids.length >= MAX_RANGE_SIZE) break;
32343
+ if (all_verse_ids.length >= limit) break;
32243
32344
  all_verse_ids.push(i);
32244
32345
  }
32245
32346
  return all_verse_ids;
@@ -32252,41 +32353,44 @@ var strToHash = function(str) {
32252
32353
  }
32253
32354
  return `==${hash}==`;
32254
32355
  };
32356
+ var cleanRulesCache = /* @__PURE__ */ new WeakMap();
32357
+ var cleanRules = function(config) {
32358
+ let rules = cleanRulesCache.get(config);
32359
+ if (rules) return rules;
32360
+ const pre = (config.raw_regex.pre_rules || []).map((rule) => [new RegExp(rule.pattern ?? rule[0], "ig"), rule.replacement ?? rule[1] ?? ""]);
32361
+ const [wordBreak, buffer] = config.raw_regex.spacing || ["\\b", ""];
32362
+ let srcbooks = config.raw_regex.books;
32363
+ let dstbooks = buffer ? config.raw_regex.books.map((i) => [i[1], i[1]]) : [];
32364
+ let bookMatchList = [...dstbooks, ...srcbooks].sort((a, b) => b[0].length - a[0].length);
32365
+ let hashCypher = {};
32366
+ for (const [, book] of bookMatchList) hashCypher[book] = strToHash(book);
32367
+ const bookRules = bookMatchList.map(([pattern, book]) => [new RegExp(wordBreak + buffer + pattern + buffer + "\\.*" + wordBreak, "ig"), hashCypher[book] || book]);
32368
+ const hashes = Object.values(hashCypher);
32369
+ rules = { pre, buffer, books: Object.keys(hashCypher), hashes, bookRules, hashRe: new RegExp(hashes.join("|"), "g") };
32370
+ cleanRulesCache.set(config, rules);
32371
+ return rules;
32372
+ };
32255
32373
  var cleanReference = function(messyReference, config) {
32256
32374
  let ref = messyReference.replace(/[\s]+/g, " ").trim();
32257
32375
  ref = ref.replace(/(\d)\s+and\s+(\d)/g, "$1,$2");
32258
32376
  ref = ref.replace(/[()]/g, " ");
32259
32377
  ref = ref.replace(/\bsec(?:tion)?\b\.?/ig, " ");
32260
- let regex = config.raw_regex.pre_rules;
32261
- for (let i in regex) {
32262
- var re = new RegExp(regex[i].pattern ?? regex[i][0], "ig");
32263
- ref = ref.replace(re, regex[i].replacement ?? regex[i][1] ?? "");
32264
- }
32378
+ ref = ref.replace(/(\d)[.](?=(?:\d[.\s]*)?\p{L})/gu, "$1 ");
32379
+ ref = ref.replace(/(\d)\s+(?=\d[\s.]*\p{L}[\p{L}\s.&'-]{0,40}?[\s.]\d)/gu, "$1; ");
32380
+ const rules = cleanRules(config);
32381
+ for (const [re, replacement] of rules.pre) ref = ref.replace(re, replacement);
32265
32382
  ref = ref.replace(/(\d+)[.](\d+)/g, "$1:$2");
32266
32383
  ref = ref.replace(/[.]/g, "");
32267
32384
  ref = ref.replace(/;/g, "; ");
32268
32385
  ref = ref.replace(/^([0-9;,:-]+)(\d+)/g, "$1 $2");
32269
32386
  ref = ref.replace(/([–-])(\D+)/g, " $1 $2 ");
32270
- const [wordBreak, buffer] = config.raw_regex.spacing || ["\\b", ""];
32271
- let srcbooks = config.raw_regex.books;
32272
- let dstbooks = buffer ? config.raw_regex.books.map((i) => [i[1], i[1]]) : [];
32273
- let bookMatchList = [...dstbooks, ...srcbooks].sort((a, b) => b[0].length - a[0].length);
32274
- regex = bookMatchList;
32275
- let hashCypher = {};
32276
- for (let i in regex) {
32277
- const [, book] = regex[i];
32278
- const hash = strToHash(book);
32279
- hashCypher[book] = hash;
32280
- }
32281
- for (let i in regex) {
32282
- var re = new RegExp(wordBreak + buffer + regex[i][0] + buffer + "\\.*" + wordBreak, "ig");
32283
- let replacement = hashCypher[regex[i][1]] || regex[i][1];
32387
+ const { buffer, books, hashes } = rules;
32388
+ for (const [re, replacement] of rules.bookRules) {
32284
32389
  ref = (buffer + ref + buffer).replace(re, replacement).trim();
32285
32390
  }
32286
- const books = Object.keys(hashCypher);
32287
- const hashes = Object.values(hashCypher);
32391
+ ref = ref.replace(/(\d)\s*(==\d+==)(?=\s*\d)/g, "$1; $2");
32288
32392
  ref = ref.replace(
32289
- new RegExp(hashes.join("|"), "g"),
32393
+ rules.hashRe,
32290
32394
  function(match) {
32291
32395
  const bookValue = books[hashes.indexOf(match)];
32292
32396
  return bookValue + " ";
@@ -32314,6 +32418,11 @@ var splitReferences = function(compoundReference, config) {
32314
32418
  let completeRefs = [];
32315
32419
  for (let i in refs) {
32316
32420
  const ref = refs[i];
32421
+ const multiBook = ref.match(/^(.*?\D)\s*\d[\d:,]*\s*[—-]\s*((?:\d\s*)?\D+?)\s*\d[\d:,]*$/);
32422
+ if (multiBook && bookExists(multiBook[1].trim(), config) && bookExists(multiBook[2].trim(), config)) {
32423
+ completeRefs.push(ref.trim());
32424
+ continue;
32425
+ }
32317
32426
  let pieces = ref.split(/([0-9:,-]+)$/);
32318
32427
  const firstPiece = pieces[0].trim();
32319
32428
  runningBook = bookExists(firstPiece, config) ? firstPiece : runningBook;
@@ -32416,11 +32525,11 @@ var getRanges = function(ref) {
32416
32525
  ;
32417
32526
  return ranges;
32418
32527
  };
32419
- var loadVerseIds = function(book, ranges, config) {
32528
+ var loadVerseIds = function(book, ranges, config, limit = MAX_RANGE_SIZE) {
32420
32529
  let refIndex = loadRefIndex(config);
32421
32530
  let verseList = [];
32422
32531
  for (let i in ranges) {
32423
- if (verseList.length >= MAX_RANGE_SIZE) break;
32532
+ if (verseList.length >= limit) break;
32424
32533
  let range = ranges[i];
32425
32534
  let matches = range.match(/(\d+): *([\dX]+)-*([\dX]*)/);
32426
32535
  if (!matches) continue;
@@ -32434,7 +32543,7 @@ var loadVerseIds = function(book, ranges, config) {
32434
32543
  start = Math.max(1, Math.min(start, MAX_VERSE));
32435
32544
  end = Math.max(start, Math.min(end, MAX_VERSE));
32436
32545
  for (let verse_num = start; verse_num <= end; verse_num++) {
32437
- if (verseList.length >= MAX_RANGE_SIZE) break;
32546
+ if (verseList.length >= limit) break;
32438
32547
  if (refIndex[book]?.[chapter]?.[verse_num]) {
32439
32548
  verseList.push(refIndex[book][chapter][verse_num]);
32440
32549
  }
@@ -32524,10 +32633,9 @@ var loadRefsFromRanges = function(ranges, config) {
32524
32633
  return refs;
32525
32634
  };
32526
32635
  var loadRefIndex = function(config) {
32527
- const configHash = hashConfig(config);
32528
- if (indexCache.refIndex && indexCache.refIndexHash === configHash) {
32529
- return indexCache.refIndex;
32530
- }
32636
+ return cachedIndex(refIndexCache, hashConfig(config), () => buildRefIndex(config));
32637
+ };
32638
+ var buildRefIndex = function(config) {
32531
32639
  let refIndex = {};
32532
32640
  let verse_id = 1;
32533
32641
  let book_list = Object.keys(config.raw_index);
@@ -32544,15 +32652,12 @@ var loadRefIndex = function(config) {
32544
32652
  }
32545
32653
  }
32546
32654
  }
32547
- indexCache.refIndex = refIndex;
32548
- indexCache.refIndexHash = configHash;
32549
32655
  return refIndex;
32550
32656
  };
32551
32657
  var loadVerseIdIndex = function(config) {
32552
- const configHash = hashConfig(config);
32553
- if (indexCache.verseIdIndex && indexCache.verseIdIndexHash === configHash) {
32554
- return indexCache.verseIdIndex;
32555
- }
32658
+ return cachedIndex(verseIdIndexCache, hashConfig(config), () => buildVerseIdIndex(config));
32659
+ };
32660
+ var buildVerseIdIndex = function(config) {
32556
32661
  let verseIdIndex = [null];
32557
32662
  let book_list = Object.keys(config.raw_index);
32558
32663
  for (let a in book_list) {
@@ -32565,8 +32670,6 @@ var loadVerseIdIndex = function(config) {
32565
32670
  }
32566
32671
  }
32567
32672
  }
32568
- indexCache.verseIdIndex = verseIdIndex;
32569
- indexCache.verseIdIndexHash = configHash;
32570
32673
  return verseIdIndex;
32571
32674
  };
32572
32675
  var bookExists = function(book, config) {
@@ -32596,7 +32699,7 @@ var restrictJoinersToStructural = (lang_extra) => {
32596
32699
  } else {
32597
32700
  joiners = [...STRUCTURAL_JOINERS];
32598
32701
  }
32599
- return { ...src, joiners };
32702
+ return { ...src, joiners, unrestrictedJoiners: src.joiners };
32600
32703
  };
32601
32704
  var detectReferences = (content, callBack, options = null) => {
32602
32705
  if (typeof options === "string" || options === null) {
@@ -32610,7 +32713,10 @@ var detectReferences = (content, callBack, options = null) => {
32610
32713
  maxContextDistance: 500,
32611
32714
  enableImpliedBooks: true,
32612
32715
  enableVerseAbbrev: true,
32613
- chainAcrossMarkers: true
32716
+ chainAcrossMarkers: true,
32717
+ // A bare "6:3" binds to an earlier book only when the token before it is
32718
+ // citation material. false restores pre-1.0.98 distance-only binding.
32719
+ strictImpliedBooks: true
32614
32720
  };
32615
32721
  const finalOptions = { ...defaultOptions, ...options };
32616
32722
  callBack = callBack ? callBack : (i) => {
@@ -32623,9 +32729,9 @@ var detectReferences = (content, callBack, options = null) => {
32623
32729
  const books = [...dst, ...src];
32624
32730
  const langExtra = finalOptions.chainAcrossMarkers === false ? restrictJoinersToStructural(config.lang_extra) : config.lang_extra;
32625
32731
  if (finalOptions.contextAware) {
32626
- return detectReferencesWithContext(content, books, langExtra, (query) => lookupReference(query, effectiveLanguage), callBack, finalOptions, generateReference);
32732
+ return detectReferencesWithContext(content, books, langExtra, detectionLookup(effectiveLanguage), callBack, finalOptions, generateReference);
32627
32733
  }
32628
- return processReferenceDetection(content, books, langExtra, (query) => lookupReference(query, effectiveLanguage), callBack);
32734
+ return processReferenceDetection(content, books, langExtra, detectionLookup(effectiveLanguage), callBack);
32629
32735
  };
32630
32736
  var findReferences = (content, options = null) => {
32631
32737
  if (typeof options === "string" || options === null) {
@@ -32640,7 +32746,10 @@ var findReferences = (content, options = null) => {
32640
32746
  enableVerseAbbrev: true,
32641
32747
  abbreviations: true,
32642
32748
  chapterOnly: true,
32643
- chainAcrossMarkers: true
32749
+ chainAcrossMarkers: true,
32750
+ // A bare "6:3" binds to an earlier book only when the token before it is
32751
+ // citation material. false restores pre-1.0.98 distance-only binding.
32752
+ strictImpliedBooks: true
32644
32753
  };
32645
32754
  const finalOptions = { ...defaultOptions, ...options };
32646
32755
  const effectiveLanguage = getEffectiveLanguage(finalOptions.language);
@@ -32648,7 +32757,7 @@ var findReferences = (content, options = null) => {
32648
32757
  const src = config.raw_regex.books.map((i) => i[0]);
32649
32758
  const dst = [...new Set(config.raw_regex.books.map((i) => i[1]))];
32650
32759
  const books = [...dst, ...src];
32651
- const lookup = (query) => lookupReference(query, effectiveLanguage);
32760
+ const lookup = detectionLookup(effectiveLanguage);
32652
32761
  const langExtra = finalOptions.chainAcrossMarkers === false ? restrictJoinersToStructural(config.lang_extra) : config.lang_extra;
32653
32762
  const found = finalOptions.contextAware ? collectReferencesWithContext(content, books, langExtra, lookup, finalOptions) : collectReferences(content, books, langExtra, lookup);
32654
32763
  let records = found.filter((m) => m.verse_ids.length > 0).map(({ start, end, text, verse_ids }) => ({
@@ -32739,9 +32848,15 @@ var applyDetectionFlags = (records, opts) => {
32739
32848
  }
32740
32849
  return out;
32741
32850
  };
32851
+ var languageConfigCache = /* @__PURE__ */ new Map();
32742
32852
  var getLanguageConfig = function(language, canon = null) {
32743
32853
  const effectiveLanguage = language && raw_lang[language] ? language : "en";
32744
32854
  const effectiveCanon = canon && extraCanons[canon] ? canon : DEFAULTS.canon;
32855
+ const key = `${effectiveLanguage}|${effectiveCanon}`;
32856
+ if (!languageConfigCache.has(key)) languageConfigCache.set(key, buildLanguageConfig(effectiveLanguage, effectiveCanon));
32857
+ return languageConfigCache.get(key);
32858
+ };
32859
+ var buildLanguageConfig = function(effectiveLanguage, effectiveCanon) {
32745
32860
  const config = {
32746
32861
  language: effectiveLanguage,
32747
32862
  canon: effectiveCanon,
@@ -32752,6 +32867,7 @@ var getLanguageConfig = function(language, canon = null) {
32752
32867
  };
32753
32868
  if (effectiveLanguage === "en" || !raw_lang[effectiveLanguage]) {
32754
32869
  config.lang_extra.joiners = config.raw_regex.joiners;
32870
+ config.lang_extra.capitalizedOnly = config.raw_regex.capitalized_only || [];
32755
32871
  return applyCanonOverride(config, effectiveCanon);
32756
32872
  }
32757
32873
  const langData2 = raw_lang[effectiveLanguage];