@dogsbay/search 0.2.0-beta.151 → 0.2.0-beta.153

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/query.js CHANGED
@@ -1,13 +1,17 @@
1
- import { FORMAT, file, key } from "./format.js";
1
+ import { FACET_NAME, FORMAT, file, key } from "./format.js";
2
2
  import { shardKey, stemFor, tokenize } from "./text.js";
3
- function parseQuery(q) {
3
+ function parseQuery(q, opts = {}) {
4
4
  const groups = [];
5
5
  const not = [];
6
6
  const phrases = [];
7
7
  let strict = false;
8
8
  const filters = { tag: [], section: [] };
9
9
  const notFilters = { tag: [], section: [] };
10
- const tokens = [...q.matchAll(/(?<!\S)(-?)(tag|section):(?:"([^"]*)"?|(\S*))|(-?)"([^"]*)"?|(\S+)/gi)].map((m) => ({
10
+ const facets = /* @__PURE__ */ Object.create(null);
11
+ const notFacets = /* @__PURE__ */ Object.create(null);
12
+ const names = ["tag", "section", ...new Set((opts.facets ?? []).filter((n) => FACET_NAME.test(n) && n !== "tag" && n !== "section"))];
13
+ const pattern = new RegExp(`(?<!\\S)(-?)(${names.join("|")}):(?:"([^"]*)"?|(?!\\/\\/)(\\S*))|(-?)"([^"]*)"?|(\\S+)`, "gi");
14
+ const tokens = [...q.matchAll(pattern)].map((m) => ({
11
15
  facetNeg: m[1] === "-",
12
16
  facet: m[2]?.toLowerCase(),
13
17
  value: m[3] ?? m[4],
@@ -20,7 +24,9 @@ function parseQuery(q) {
20
24
  for (const [i, m] of tokens.entries()) {
21
25
  if (m.facet) {
22
26
  const v = facetValue(m.value ?? "");
23
- if (v) (m.facetNeg ? notFilters : filters)[m.facet].push(v);
27
+ if (!v) continue;
28
+ if (m.facet === "tag" || m.facet === "section") (m.facetNeg ? notFilters : filters)[m.facet].push(v);
29
+ else ((m.facetNeg ? notFacets : facets)[m.facet] ??= []).push(v);
24
30
  continue;
25
31
  }
26
32
  const word = m.word;
@@ -74,11 +80,21 @@ function parseQuery(q) {
74
80
  groups.push({ terms: [t], prefix: last && t.length >= 2 && (j === terms.length - 1 || compound && (t === whole || t === joined)) });
75
81
  }
76
82
  const highlight = [...new Set(groups.flatMap((g) => g.terms))];
77
- return { groups, not, phrases, strict, highlight, filters, notFilters };
83
+ return { groups, not, phrases, strict, highlight, filters, notFilters, ...Object.keys(facets).length ? { facets } : {}, ...Object.keys(notFacets).length ? { notFacets } : {} };
78
84
  }
79
85
  async function query(q, data) {
80
86
  const meta = await data.meta();
81
- const p = typeof q === "string" ? parseQuery(q) : q;
87
+ const p = typeof q === "string" ? parseQuery(q, { facets: facetNames([meta]) }) : q;
88
+ const excluded = await excludedDocs(p, meta, data);
89
+ const keep = facetFilter(p, meta);
90
+ if (!p.groups.length) return filteredDocs(meta, excluded, keep);
91
+ const perGroup = [];
92
+ for (const g of p.groups) perGroup.push(await scoreGroup(g, meta, data));
93
+ const and = combineGroups(perGroup, meta, excluded, keep, "and").sort(byScore);
94
+ return and.length || p.strict ? and : combineGroups(perGroup, meta, excluded, keep, "or").sort(byScore);
95
+ }
96
+ const byScore = (a, b) => b.score - a.score;
97
+ async function excludedDocs(p, meta, data) {
82
98
  const excluded = /* @__PURE__ */ new Set();
83
99
  for (const set of p.not) {
84
100
  let docs;
@@ -92,33 +108,29 @@ async function query(q, data) {
92
108
  }
93
109
  for (const d of docs ?? []) excluded.add(d);
94
110
  }
95
- const keep = facetFilter(p, meta);
96
- if (!p.groups.length) {
97
- if (!keep) return [];
98
- const out = [];
99
- meta.docs.forEach(([title, url, section], d) => keep(d) && !excluded.has(d) && out.push({ id: d, title, url, section: meta.sections[section] ?? "", score: 1 }));
100
- return out;
101
- }
102
- const perGroup = [];
103
- for (const g of p.groups) perGroup.push(await scoreGroup(g, meta, data));
104
- const combine = (mode) => {
105
- const total = /* @__PURE__ */ new Map();
106
- const hits = /* @__PURE__ */ new Map();
107
- for (const m of perGroup)
108
- for (const [d, s] of m) {
109
- total.set(d, (total.get(d) ?? 0) + s);
110
- hits.set(d, (hits.get(d) ?? 0) + 1);
111
- }
112
- const out = [];
113
- for (const [d, s] of total) {
114
- if (excluded.has(d) || keep && !keep(d) || mode === "and" && hits.get(d) !== perGroup.length) continue;
115
- const [title, url, section] = meta.docs[d];
116
- out.push({ id: d, title, url, section: meta.sections[section] ?? "", score: s * (hits.get(d) / perGroup.length) });
111
+ return excluded;
112
+ }
113
+ function filteredDocs(meta, excluded, keep) {
114
+ if (!keep) return [];
115
+ const out = [];
116
+ meta.docs.forEach(([title, url, section], d) => keep(d) && !excluded.has(d) && out.push({ id: d, title, url, section: meta.sections[section] ?? "", score: 1 }));
117
+ return out;
118
+ }
119
+ function combineGroups(perGroup, meta, excluded, keep, mode) {
120
+ const total = /* @__PURE__ */ new Map();
121
+ const hits = /* @__PURE__ */ new Map();
122
+ for (const m of perGroup)
123
+ for (const [d, s] of m) {
124
+ total.set(d, (total.get(d) ?? 0) + s);
125
+ hits.set(d, (hits.get(d) ?? 0) + 1);
117
126
  }
118
- return out.sort((a, b) => b.score - a.score);
119
- };
120
- const and = combine("and");
121
- return and.length || p.strict ? and : combine("or");
127
+ const out = [];
128
+ for (const [d, s] of total) {
129
+ if (excluded.has(d) || keep && !keep(d) || mode === "and" && hits.get(d) !== perGroup.length) continue;
130
+ const [title, url, section] = meta.docs[d];
131
+ out.push({ id: d, title, url, section: meta.sections[section] ?? "", score: s * (hits.get(d) / perGroup.length) });
132
+ }
133
+ return out;
122
134
  }
123
135
  const QUERY_RANK = {
124
136
  prefix: 0.6,
@@ -176,23 +188,76 @@ function facetValue(v) {
176
188
  function facetFilter(p, meta) {
177
189
  const { tag, section } = p.filters;
178
190
  const not = p.notFilters ?? { tag: [], section: [] };
179
- if (!tag.length && !section.length && !not.tag.length && !not.section.length) return void 0;
180
- const indexes = (names, want) => new Set(names.flatMap((x, i) => want.includes(facetValue(x)) ? [i] : []));
191
+ const want = Object.entries(p.facets ?? {}).filter(([, v]) => v.length);
192
+ const notWant = Object.entries(p.notFacets ?? {}).filter(([, v]) => v.length);
193
+ if (!tag.length && !section.length && !not.tag.length && !not.section.length && !want.length && !notWant.length) return void 0;
194
+ const indexes = (names, want2) => new Set(names.flatMap((x, i) => want2.includes(facetValue(x)) ? [i] : []));
181
195
  const sections = indexes(meta.sections, section);
182
196
  const tags = indexes(meta.tags ?? [], tag);
183
197
  const notSections = indexes(meta.sections, not.section);
184
198
  const notTags = indexes(meta.tags ?? [], not.tag);
199
+ const place = (name) => (meta.facets ?? []).findIndex((f) => f.name === name);
200
+ const facetSets = (list) => list.map(([name, values]) => {
201
+ const i = place(name);
202
+ return [i, i < 0 ? /* @__PURE__ */ new Set() : indexes(meta.facets[i].values, values)];
203
+ });
204
+ const facets = facetSets(want);
205
+ const notFacets = facetSets(notWant).filter(([i]) => i >= 0);
206
+ const has = (doc, [i, set]) => i >= 0 && (doc[4]?.[i] ?? []).some((v) => set.has(v));
185
207
  return (d) => {
186
208
  const doc = meta.docs[d];
187
209
  const docTags = doc[3] ?? [];
188
210
  if (section.length && !sections.has(doc[2])) return false;
189
211
  if (tag.length && !docTags.some((t) => tags.has(t))) return false;
190
212
  if (notSections.has(doc[2]) || docTags.some((t) => notTags.has(t))) return false;
213
+ for (const f of facets) if (!has(doc, f)) return false;
214
+ for (const f of notFacets) if (has(doc, f)) return false;
191
215
  return true;
192
216
  };
193
217
  }
218
+ function facetNames(metas) {
219
+ return [...new Set(metas.flatMap((m) => (m?.facets ?? []).map((f) => f.name)))];
220
+ }
221
+ function facetCounts(results, metaOf) {
222
+ const out = /* @__PURE__ */ Object.create(null);
223
+ const spelling = /* @__PURE__ */ new Map();
224
+ const add = (facet, value) => {
225
+ const k = `${facet}\0${facetValue(value)}`;
226
+ let label = spelling.get(k);
227
+ if (label === void 0) spelling.set(k, label = value);
228
+ const counts = out[facet] ??= /* @__PURE__ */ Object.create(null);
229
+ counts[label] = (counts[label] ?? 0) + 1;
230
+ };
231
+ for (const r of results) {
232
+ const meta = typeof metaOf === "function" ? metaOf(r) : metaOf;
233
+ const doc = meta?.docs[r.id];
234
+ if (!doc) continue;
235
+ if (meta.sections[doc[2]]) add("section", meta.sections[doc[2]]);
236
+ for (const t of new Set(doc[3] ?? [])) if (meta.tags[t] !== void 0) add("tag", meta.tags[t]);
237
+ (doc[4] ?? []).forEach((ids, i) => {
238
+ const table = meta.facets?.[i];
239
+ if (table) {
240
+ for (const v of new Set(ids)) if (table.values[v] !== void 0) add(table.name, table.values[v]);
241
+ }
242
+ });
243
+ }
244
+ return out;
245
+ }
194
246
  async function scoreGroup(g, meta, data) {
195
- g.corrected = void 0;
247
+ const m = await matchGroup(g, meta, data, true);
248
+ g.corrected = m.corrected.length ? m.corrected : void 0;
249
+ return groupScores(m, idfOf(meta.count, m.docs.size));
250
+ }
251
+ function idfOf(n, df) {
252
+ return Math.log(1 + (n - df + 0.5) / (df + 0.5));
253
+ }
254
+ function groupScores(m, idf) {
255
+ const scores = /* @__PURE__ */ new Map();
256
+ for (const [flat, w] of m.lists)
257
+ for (let i = 0; i < flat.length; i += 2) scores.set(flat[i], Math.max(scores.get(flat[i]) ?? 0, flat[i + 1] * w * idf));
258
+ return scores;
259
+ }
260
+ async function matchGroup(g, meta, data, typo) {
196
261
  const stem = stemFor(meta.lang);
197
262
  const weights = /* @__PURE__ */ new Map();
198
263
  const shards = /* @__PURE__ */ new Map();
@@ -215,34 +280,65 @@ async function scoreGroup(g, meta, data) {
215
280
  if (g.prefix && k.startsWith(term) && n++ < 200) use(k, QUERY_RANK.prefix);
216
281
  if (s && lead && k.startsWith(lead) && stem(k) === s) use(k, QUERY_RANK.stem);
217
282
  }
218
- if (!weights.size && !g.exact && term.length >= 4 && !/[._-]/.test(term)) {
283
+ if (typo && !weights.size && !g.exact && term.length >= 4 && !/[._-]/.test(term)) {
219
284
  for (const k in shard) if (Math.abs(k.length - term.length) <= 1 && oneEdit(term, k)) use(k, QUERY_RANK.typo);
220
285
  }
221
286
  }
222
- if ([...weights.values()].some((w) => w === QUERY_RANK.typo)) g.corrected = [...weights].filter(([, w]) => w === QUERY_RANK.typo).map(([k]) => k);
287
+ const corrected = [...weights].filter(([, w]) => w === QUERY_RANK.typo).map(([k]) => k);
223
288
  const lists = [...weights].map(([k, w]) => [shards.get(k)[k], w]);
224
289
  const docs = /* @__PURE__ */ new Set();
225
290
  for (const [flat] of lists) for (let i = 0; i < flat.length; i += 2) docs.add(flat[i]);
226
- const idf = Math.log(1 + (meta.count - docs.size + 0.5) / (docs.size + 0.5));
227
- const scores = /* @__PURE__ */ new Map();
228
- for (const [flat, w] of lists)
229
- for (let i = 0; i < flat.length; i += 2) scores.set(flat[i], Math.max(scores.get(flat[i]) ?? 0, flat[i + 1] * w * idf));
230
- return scores;
291
+ return { lists, docs, corrected };
231
292
  }
293
+ const dataOf = (data) => typeof data === "function" ? data : () => data;
232
294
  async function loadFragments(results, data) {
233
- const meta = await data.meta();
234
- const blocks = [...new Set(results.map((r) => Math.floor(r.id / meta.block)))];
235
- const loaded = /* @__PURE__ */ new Map();
236
- await Promise.all(blocks.map(async (b) => loaded.set(b, await data.fragment(b))));
237
- for (const r of results) r.fragment ??= loaded.get(Math.floor(r.id / meta.block))?.[r.id % meta.block];
295
+ const pick = dataOf(data);
296
+ const byData = /* @__PURE__ */ new Map();
297
+ for (const r of results) {
298
+ const d = pick(r);
299
+ let rs = byData.get(d);
300
+ if (!rs) byData.set(d, rs = []);
301
+ rs.push(r);
302
+ }
303
+ await Promise.all(
304
+ [...byData].map(async ([d, rs]) => {
305
+ const meta = await d.meta();
306
+ const blocks = [...new Set(rs.map((r) => Math.floor(r.id / meta.block)))];
307
+ const loaded = /* @__PURE__ */ new Map();
308
+ await Promise.all(
309
+ blocks.map(async (b) => {
310
+ try {
311
+ loaded.set(b, await d.fragment(b));
312
+ } catch {
313
+ loaded.set(b, void 0);
314
+ }
315
+ })
316
+ );
317
+ for (const r of rs) r.fragment ??= loaded.get(Math.floor(r.id / meta.block))?.[r.id % meta.block];
318
+ })
319
+ );
320
+ }
321
+ async function hitFor(data) {
322
+ const pick = dataOf(data);
323
+ const tests = /* @__PURE__ */ new Map();
324
+ return async (r) => {
325
+ const d = pick(r);
326
+ let hit = tests.get(d);
327
+ if (!hit) {
328
+ const stem = stemFor((await d.meta()).lang);
329
+ hit = (x, g) => g.terms.some((t) => x === t || g.prefix && x.startsWith(t) || stem !== void 0 && stem(x) === stem(t)) || (g.corrected ?? []).includes(x);
330
+ tests.set(d, hit);
331
+ }
332
+ return hit;
333
+ };
238
334
  }
239
335
  async function refine(p, results, data, n = 10) {
240
336
  const top = results.slice(0, n);
241
337
  await loadFragments(top, data);
242
338
  const words = p.groups;
243
- const stem = stemFor((await data.meta()).lang);
244
- const hit = (x, g) => g.terms.some((t) => x === t || g.prefix && x.startsWith(t) || stem !== void 0 && stem(x) === stem(t)) || (g.corrected ?? []).includes(x);
339
+ const hitOf = await hitFor(data);
245
340
  for (const r of top) {
341
+ const hit = await hitOf(r);
246
342
  const [excerpt, headings] = r.fragment ?? ["", []];
247
343
  const titleTerms = tokenize(r.title);
248
344
  let best = 1;
@@ -266,10 +362,10 @@ async function refine(p, results, data, n = 10) {
266
362
  }
267
363
  async function loadDetails(p, results, data) {
268
364
  await loadFragments(results, data);
269
- const stem = stemFor((await data.meta()).lang);
270
- const hit = (x, g) => g.terms.some((t) => x === t || g.prefix && x.startsWith(t) || stem !== void 0 && stem(x) === stem(t)) || (g.corrected ?? []).includes(x);
365
+ const hitOf = await hitFor(data);
271
366
  for (const r of results) {
272
367
  if (!r.fragment || r.sections) continue;
368
+ const hit = await hitOf(r);
273
369
  r.sections = r.fragment[1].filter(([text]) => {
274
370
  const terms = tokenize(text);
275
371
  return p.groups.length > 0 && p.groups.every((g) => terms.some((x) => hit(x, g)));
@@ -280,20 +376,142 @@ function sameTerms(terms, groups, hit) {
280
376
  return terms.every((x) => groups.some((g) => hit(x, g))) && groups.every((g) => terms.some((x) => hit(x, g)));
281
377
  }
282
378
  async function search(q, data, n = 10) {
283
- const parsed = parseQuery(q);
284
- const stem = stemFor((await data.meta()).lang);
379
+ const meta = await data.meta();
380
+ const parsed = parseQuery(q, { facets: facetNames([meta]) });
381
+ const stem = stemFor(meta.lang);
285
382
  if (stem) parsed.highlight = [.../* @__PURE__ */ new Set([...parsed.highlight, ...parsed.highlight.map(stem).filter((s) => s.length >= 3)])];
286
383
  const ranked = await query(parsed, data);
287
384
  parsed.highlight = [.../* @__PURE__ */ new Set([...parsed.highlight, ...parsed.groups.flatMap((g) => g.corrected ?? [])])];
288
- return { parsed, results: await refine(parsed, ranked, data, n) };
385
+ return { parsed, results: await refine(parsed, ranked, data, n), facets: facetCounts(ranked, meta) };
386
+ }
387
+ async function sourceMetas(sources) {
388
+ return Promise.all(
389
+ sources.map(
390
+ (s) => s.data.meta().then(
391
+ (m) => m && m.format === FORMAT ? m : void 0,
392
+ () => void 0
393
+ )
394
+ )
395
+ );
396
+ }
397
+ async function querySources(q, sources, opts = {}) {
398
+ const metas = await sourceMetas(sources);
399
+ return (await rankSources(typeof q === "string" ? parseQuery(q, { facets: facetNames(metas) }) : q, sources, metas, opts)).results;
400
+ }
401
+ async function rankSources(p, sources, all, opts) {
402
+ const metas = all;
403
+ const failed = /* @__PURE__ */ new Set();
404
+ const errors = [];
405
+ const guard = async (i, f) => {
406
+ if (failed.has(i)) return void 0;
407
+ try {
408
+ return await f();
409
+ } catch (error) {
410
+ failed.add(i);
411
+ errors.push({ source: i, error });
412
+ return void 0;
413
+ }
414
+ };
415
+ const live = sources.flatMap((_, i) => all[i] ? [i] : []);
416
+ const excluded = [];
417
+ await Promise.all(live.map(async (i) => excluded[i] = await guard(i, () => excludedDocs(p, metas[i], sources[i].data)) ?? /* @__PURE__ */ new Set()));
418
+ const matched = [];
419
+ const typoTried = [];
420
+ const match = (g, typo) => Promise.all(live.map((i) => guard(i, () => matchGroup(g, metas[i], sources[i].data, typo))));
421
+ const noneHas = (matches) => matches.every((m, j) => !m?.docs.size || failed.has(live[j]));
422
+ for (const g of p.groups) {
423
+ let matches = await match(g, false);
424
+ typoTried.push(noneHas(matches));
425
+ if (typoTried[typoTried.length - 1]) matches = await match(g, true);
426
+ matched.push(matches);
427
+ }
428
+ for (const [gi, g] of p.groups.entries()) {
429
+ if (typoTried[gi] || !noneHas(matched[gi])) continue;
430
+ g.corrected = void 0;
431
+ matched[gi] = await match(g, true);
432
+ }
433
+ if (live.length && live.every((i) => failed.has(i))) throw errors[0].error;
434
+ const ok = live.filter((i) => !failed.has(i));
435
+ const keeps = [];
436
+ for (const i of ok) keeps[i] = facetFilter(p, metas[i]);
437
+ const tag = (rs, i) => rs.map((r) => ({ ...r, source: i, score: r.score * boostOf(sources[i]) }));
438
+ const done = (results) => ({ results: collapse(results, sources), failed: [...failed].sort((a, b) => a - b), errors });
439
+ if (!p.groups.length) return done(ok.flatMap((i) => tag(filteredDocs(metas[i], excluded[i], keeps[i]), i)).sort(byScore));
440
+ const perGroup = sources.map(() => []);
441
+ const n = ok.reduce((t, i) => t + metas[i].count, 0);
442
+ p.groups.forEach((g, gi) => {
443
+ const matches = matched[gi];
444
+ const kept = live.flatMap((i, j) => failed.has(i) ? [] : [[i, matches[j]]]);
445
+ const corrected = [...new Set(kept.flatMap(([, m]) => m.corrected))];
446
+ g.corrected = corrected.length ? corrected : void 0;
447
+ const df = kept.reduce((t, [, m]) => t + m.docs.size, 0);
448
+ for (const [i, m] of kept) perGroup[i].push(groupScores(m, opts.stats === "own" ? idfOf(metas[i].count, m.docs.size) : idfOf(n, df)));
449
+ });
450
+ const ranked = (mode) => ok.flatMap((i) => tag(combineGroups(perGroup[i], metas[i], excluded[i], keeps[i], mode), i)).sort(byScore);
451
+ const and = ranked("and");
452
+ return done(and.length || p.strict ? and : ranked("or"));
453
+ }
454
+ function boostOf(s) {
455
+ return typeof s.boost === "number" && Number.isFinite(s.boost) && s.boost >= 0 ? s.boost : 1;
456
+ }
457
+ function collapse(results, sources) {
458
+ const firsts = /* @__PURE__ */ new Map();
459
+ const out = [];
460
+ for (const r of results) {
461
+ const group = sources[r.source].collapse;
462
+ if (group === void 0) {
463
+ out.push(r);
464
+ continue;
465
+ }
466
+ const k = `${group}\0${r.url}`;
467
+ const first = firsts.get(k);
468
+ if (first) (first.others ??= []).push({ source: r.source, id: r.id, url: r.url, score: r.score });
469
+ else {
470
+ firsts.set(k, r);
471
+ out.push(r);
472
+ }
473
+ }
474
+ return out;
475
+ }
476
+ async function searchSources(q, sources, n = 10, opts = {}) {
477
+ const metas = await sourceMetas(sources);
478
+ const parsed = parseQuery(q, { facets: facetNames(metas) });
479
+ const missing = sources.flatMap((_, i) => metas[i] ? [] : [i]);
480
+ for (const lang of new Set(metas.flatMap((m) => m ? [m.lang] : []))) {
481
+ const stem = stemFor(lang);
482
+ if (stem) parsed.highlight = [.../* @__PURE__ */ new Set([...parsed.highlight, ...parsed.highlight.map(stem).filter((s) => s.length >= 3)])];
483
+ }
484
+ const { results: ranked, failed, errors } = await rankSources(parsed, sources, metas, opts);
485
+ for (const i of failed) if (!missing.includes(i)) missing.push(i);
486
+ missing.sort((a, b) => a - b);
487
+ parsed.highlight = [.../* @__PURE__ */ new Set([...parsed.highlight, ...parsed.groups.flatMap((g) => g.corrected ?? [])])];
488
+ const facets = facetCounts(ranked, (r) => metas[r.source]);
489
+ return { parsed, results: await refine(parsed, ranked, (r) => sources[r.source].data, n), missing, facets, errors };
289
490
  }
290
491
  function scriptData(base, loadScript, g = globalThis) {
291
- const store = /* @__PURE__ */ new Map();
492
+ const page = g.document?.baseURI ?? g.location?.href;
493
+ const root = absoluteUrl(base, page);
292
494
  const global = g.__DOGSBAY_SEARCH__ ?? { q: [], load() {
293
495
  } };
294
- for (const [k, d] of global.q) store.set(k, d);
496
+ const stores = global.stores ??= /* @__PURE__ */ new Map();
497
+ const store = stores.get(root) ?? /* @__PURE__ */ new Map();
498
+ stores.set(root, store);
499
+ const route = (k, d, src) => {
500
+ let owner;
501
+ if (src) {
502
+ let best = "";
503
+ const abs = absoluteUrl(src, page);
504
+ for (const r of stores.keys()) if (abs.startsWith(r) && r.length > best.length) best = r;
505
+ owner = best ? stores.get(best) : void 0;
506
+ }
507
+ if (!owner && stores.size === 1) owner = store;
508
+ if (owner) owner.set(k, d);
509
+ else global.q.push([k, d, src]);
510
+ };
511
+ const waiting = global.q;
295
512
  global.q = [];
296
- global.load = (k, d) => void store.set(k, d);
513
+ global.load = route;
514
+ for (const [k, d, src] of waiting) route(k, d, src);
297
515
  g.__DOGSBAY_SEARCH__ = global;
298
516
  const get = async (k, src) => {
299
517
  if (!store.has(k)) await loadScript(base + src);
@@ -304,12 +522,22 @@ function scriptData(base, loadScript, g = globalThis) {
304
522
  meta: () => meta ??= get(key.docs, file.docs).then((m) => {
305
523
  if (!m || m.format !== FORMAT) throw new Error(`search index format ${m?.format ?? "missing"}, expected ${FORMAT}: rebuild the site`);
306
524
  return m;
525
+ }).catch((e) => {
526
+ meta = void 0;
527
+ throw e;
307
528
  }),
308
529
  shard: async (k) => (await data.meta()).shards.includes(k) ? get(key.shard(k), file.shard(k)) : void 0,
309
530
  fragment: (b) => get(key.fragment(b), file.fragment(b))
310
531
  };
311
532
  return data;
312
533
  }
534
+ function absoluteUrl(u, page) {
535
+ try {
536
+ return new URL(u, page).href;
537
+ } catch {
538
+ return u;
539
+ }
540
+ }
313
541
  function memoryData(store) {
314
542
  return {
315
543
  meta: async () => store.get(key.docs),
@@ -319,15 +547,20 @@ function memoryData(store) {
319
547
  }
320
548
  export {
321
549
  QUERY_RANK,
550
+ facetCounts,
551
+ facetNames,
322
552
  facetValue,
553
+ idfOf,
323
554
  loadDetails,
324
555
  loadFragments,
325
556
  memoryData,
326
557
  oneEdit,
327
558
  parseQuery,
328
559
  query,
560
+ querySources,
329
561
  refine,
330
562
  scriptData,
331
563
  search,
564
+ searchSources,
332
565
  shardsFor
333
566
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dogsbay/search",
3
- "version": "0.2.0-beta.151",
3
+ "version": "0.2.0-beta.153",
4
4
  "description": "Static search for docs sites: builds in a Worker, queries from file://",
5
5
  "type": "module",
6
6
  "main": "./dist/entry.js",
@@ -30,6 +30,10 @@
30
30
  "types": "./dist/html.d.ts",
31
31
  "import": "./dist/html.js"
32
32
  },
33
+ "./facets": {
34
+ "types": "./dist/facets.d.ts",
35
+ "import": "./dist/facets.js"
36
+ },
33
37
  "./site": {
34
38
  "types": "./dist/site.d.ts",
35
39
  "import": "./dist/site.js"
@@ -42,7 +46,7 @@
42
46
  ],
43
47
  "dependencies": {
44
48
  "stemmer": "^2.0.1",
45
- "@dogsbay/types": "0.2.0-beta.151"
49
+ "@dogsbay/types": "0.2.0-beta.153"
46
50
  },
47
51
  "devDependencies": {
48
52
  "@playwright/test": "1.61.1",
@@ -52,7 +56,7 @@
52
56
  "tsup": "^8.5.1",
53
57
  "typescript": "^5.9.3",
54
58
  "vitest": "^4.1.10",
55
- "@dogsbay/format-openapi": "0.2.0-beta.151"
59
+ "@dogsbay/format-openapi": "0.2.0-beta.153"
56
60
  },
57
61
  "license": "MIT",
58
62
  "repository": {