@foundrykit/search-plugin 0.1.0
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/LICENSE +21 -0
- package/README.md +151 -0
- package/dist/analytics.d.ts +36 -0
- package/dist/analytics.js +71 -0
- package/dist/analytics.js.map +1 -0
- package/dist/cache.d.ts +21 -0
- package/dist/cache.js +42 -0
- package/dist/cache.js.map +1 -0
- package/dist/collections/SearchEvents.d.ts +15 -0
- package/dist/collections/SearchEvents.js +62 -0
- package/dist/collections/SearchEvents.js.map +1 -0
- package/dist/components/SearchDashboard.d.ts +13 -0
- package/dist/components/SearchDashboard.js +170 -0
- package/dist/components/SearchDashboard.js.map +1 -0
- package/dist/components/useSearchHotkey.d.ts +15 -0
- package/dist/components/useSearchHotkey.js +71 -0
- package/dist/components/useSearchHotkey.js.map +1 -0
- package/dist/decodeEntities.d.ts +12 -0
- package/dist/decodeEntities.js +13 -0
- package/dist/decodeEntities.js.map +1 -0
- package/dist/endpoints/handlers.d.ts +24 -0
- package/dist/endpoints/handlers.js +95 -0
- package/dist/endpoints/handlers.js.map +1 -0
- package/dist/exports/client.d.ts +1 -0
- package/dist/exports/client.js +3 -0
- package/dist/exports/client.js.map +1 -0
- package/dist/exports/rsc.d.ts +1 -0
- package/dist/exports/rsc.js +3 -0
- package/dist/exports/rsc.js.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +79 -0
- package/dist/index.js.map +1 -0
- package/dist/options.d.ts +11 -0
- package/dist/options.js +42 -0
- package/dist/options.js.map +1 -0
- package/dist/project.d.ts +37 -0
- package/dist/project.js +82 -0
- package/dist/project.js.map +1 -0
- package/dist/rank.d.ts +38 -0
- package/dist/rank.js +110 -0
- package/dist/rank.js.map +1 -0
- package/dist/resolve.d.ts +25 -0
- package/dist/resolve.js +86 -0
- package/dist/resolve.js.map +1 -0
- package/dist/types.d.ts +125 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/package.json +96 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 UMI Digital
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# @foundrykit/search-plugin
|
|
2
|
+
|
|
3
|
+
Cached, grouped and ranked site search for Payload CMS, layered on top of
|
|
4
|
+
[`@payloadcms/plugin-search`](https://payloadcms.com/docs/plugins/search).
|
|
5
|
+
|
|
6
|
+
That plugin keeps a `search` collection in sync with your content through `afterChange` /
|
|
7
|
+
`afterDelete` hooks. Sync is the part of an index implementation that rots, so this plugin does not
|
|
8
|
+
reimplement it — it owns the **read** side:
|
|
9
|
+
|
|
10
|
+
- **One index read per request**, cached in memory, instead of one query per collection per keystroke
|
|
11
|
+
- **Fuzzy matching** via Fuse.js, so typos, plurals and word order stop mattering
|
|
12
|
+
- **Ranking** by field weight and collection weight, so a title hit beats an incidental description hit
|
|
13
|
+
- **Grouping** with per-group caps, and an opt-in empty-query preset
|
|
14
|
+
- **Editor operability** — reindex on demand, and a "what is searchable" report that gives reasons
|
|
15
|
+
- **Search analytics** — top queries and, more usefully, the ones returning nothing
|
|
16
|
+
|
|
17
|
+
## Why the read side is the interesting half
|
|
18
|
+
|
|
19
|
+
A naive site search queries each source collection live with a `like` substring `where` clause.
|
|
20
|
+
That caps how good relevance can ever get: substring matching has no word boundaries (searching
|
|
21
|
+
`tuni` matches anything containing those four letters anywhere), there is no ranking, and there is
|
|
22
|
+
nothing to measure or rebuild. Every complaint arrives anecdotally and costs a developer a code
|
|
23
|
+
read to diagnose.
|
|
24
|
+
|
|
25
|
+
## Install
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm add @foundrykit/search-plugin
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
Install it **after** `searchPlugin`, since it reads the collection that one creates.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { searchPlugin as payloadSearchPlugin } from '@payloadcms/plugin-search'
|
|
37
|
+
import { searchPlugin } from '@foundrykit/search-plugin'
|
|
38
|
+
|
|
39
|
+
export default buildConfig({
|
|
40
|
+
plugins: [
|
|
41
|
+
payloadSearchPlugin({
|
|
42
|
+
collections: ['pages', 'posts', 'hotels'],
|
|
43
|
+
}),
|
|
44
|
+
|
|
45
|
+
searchPlugin({
|
|
46
|
+
groups: [
|
|
47
|
+
{ slug: 'destinations', label: 'Destinations', limit: 3 },
|
|
48
|
+
{ slug: 'stays', label: 'Places to stay', limit: 4 },
|
|
49
|
+
// Utility pages are worth finding by name, but not worth suggesting unprompted.
|
|
50
|
+
{ slug: 'pages', label: 'Pages', limit: 3, showWhenEmpty: false },
|
|
51
|
+
],
|
|
52
|
+
|
|
53
|
+
collections: [
|
|
54
|
+
{ slug: 'regions', group: 'destinations', path: '/regions', weight: 3 },
|
|
55
|
+
{ slug: 'hotels', group: 'stays', path: '/hotels', icon: 'bed', weight: 2 },
|
|
56
|
+
{
|
|
57
|
+
slug: 'pages',
|
|
58
|
+
group: 'pages',
|
|
59
|
+
// Empty string, not undefined: these are served at the site root.
|
|
60
|
+
path: '',
|
|
61
|
+
excludeSlugs: ['home', 'gift-list'],
|
|
62
|
+
},
|
|
63
|
+
],
|
|
64
|
+
|
|
65
|
+
analytics: { retentionDays: 90 },
|
|
66
|
+
}),
|
|
67
|
+
],
|
|
68
|
+
})
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Endpoints
|
|
72
|
+
|
|
73
|
+
| Method | Path | Purpose |
|
|
74
|
+
| --- | --- | --- |
|
|
75
|
+
| `GET` | `/api/site-search?q=` | Grouped, ranked results. Empty `q` returns the preset. |
|
|
76
|
+
| `POST` | `/api/site-search/reindex` | Rebuild the projection now. Returns counts. |
|
|
77
|
+
| `GET` | `/api/site-search/inspect` | What is indexed, and why anything missing was skipped. |
|
|
78
|
+
| `POST` | `/api/site-search/track` | Attribute a click to a query. Only when analytics are on. |
|
|
79
|
+
|
|
80
|
+
Change the base with `routePrefix`. `reindex` and `inspect` require an authenticated user unless
|
|
81
|
+
you set `requireAdminForOperations: false`.
|
|
82
|
+
|
|
83
|
+
## Options
|
|
84
|
+
|
|
85
|
+
| Option | Default | Notes |
|
|
86
|
+
| --- | --- | --- |
|
|
87
|
+
| `collections` | — | Required. Which collections are searchable, and how their results present. |
|
|
88
|
+
| `groups` | — | Required. Presentation buckets, with caps and empty-state opt-in. |
|
|
89
|
+
| `cacheTTL` | `60000` | Milliseconds to hold the projection. |
|
|
90
|
+
| `fields` | title 1, slug 0.4, description 0.2 | Fields matched, with relative weights. |
|
|
91
|
+
| `fuzzy` | `{ threshold: 0.35, distance: 100, minMatchCharLength: 3 }` | Fuse tuning. |
|
|
92
|
+
| `decodeEntities` | `true` | Decode HTML entities in titles. |
|
|
93
|
+
| `analytics` | `false` | `true`, or `{ retentionDays, collectionSlug }`. |
|
|
94
|
+
| `requireAdminForOperations` | `true` | Guard reindex and inspect. |
|
|
95
|
+
| `routePrefix` | `/site-search` | Base path for endpoints. |
|
|
96
|
+
| `disabled` | `false` | Bypass the plugin entirely. |
|
|
97
|
+
|
|
98
|
+
### A note on `minMatchCharLength`
|
|
99
|
+
|
|
100
|
+
The default of `3` is deliberate. Two-character fragments match too much to be useful, and that is
|
|
101
|
+
the single most common source of "why is this unrelated thing in my results".
|
|
102
|
+
|
|
103
|
+
### A note on the empty-query preset
|
|
104
|
+
|
|
105
|
+
`presetResults` orders by collection weight and then alphabetically. It is **not** popularity- or
|
|
106
|
+
analytics-ranked, and deliberately does not pretend to be — if you want a curated order, set
|
|
107
|
+
weights. Once analytics have accumulated, the top-queries report is the honest input for that
|
|
108
|
+
decision.
|
|
109
|
+
|
|
110
|
+
### `decodeEntities`
|
|
111
|
+
|
|
112
|
+
Content migrated out of a CMS that stored HTML-encoded text (Umbraco, typically) keeps entities in
|
|
113
|
+
its titles. Rich-text renderers decode on output, so a page body reads correctly while every
|
|
114
|
+
plain-text surface — search results, filter labels, map pins — shows a literal `&`. Decoding at
|
|
115
|
+
projection time fixes all of them at once.
|
|
116
|
+
|
|
117
|
+
## Client helpers
|
|
118
|
+
|
|
119
|
+
```tsx
|
|
120
|
+
import { useSearchHotkey, useIsAppleDevice } from '@foundrykit/search-plugin/client'
|
|
121
|
+
|
|
122
|
+
useSearchHotkey(open) // Cmd+K / Ctrl+K
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The hotkey is suppressed inside inputs, textareas, selects and contenteditable. That guard matters:
|
|
126
|
+
`Ctrl+K` is Lexical's "insert link" binding, and Lexical is Payload's own editor.
|
|
127
|
+
|
|
128
|
+
## Analytics and privacy
|
|
129
|
+
|
|
130
|
+
Nothing identifying is stored — no IP, no session, no user relationship. Queries are behavioural
|
|
131
|
+
data, and aggregate counts plus the zero-result list are what actually inform relevance work.
|
|
132
|
+
Events past `retentionDays` are pruned on write, so the log stays bounded without needing a
|
|
133
|
+
scheduled job the host project may not have.
|
|
134
|
+
|
|
135
|
+
## Dashboard
|
|
136
|
+
|
|
137
|
+
```tsx
|
|
138
|
+
import { SearchDashboard } from '@foundrykit/search-plugin/rsc'
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
A server component showing index counts, skipped documents **with reasons**, zero-result queries
|
|
142
|
+
and top queries. Wire it into `admin.components.views` or a custom dashboard.
|
|
143
|
+
|
|
144
|
+
## Development
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
pnpm install
|
|
148
|
+
pnpm test:unit
|
|
149
|
+
pnpm build
|
|
150
|
+
pnpm lint
|
|
151
|
+
```
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
/** Normalise a query for aggregation so "Sri Lanka" and " sri lanka " count as one term. */
|
|
3
|
+
export declare const normalizeQuery: (query: string) => string;
|
|
4
|
+
export type QueryStat = {
|
|
5
|
+
count: number;
|
|
6
|
+
query: string;
|
|
7
|
+
zeroResultCount: number;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Aggregate raw events into the per-query counts the dashboard shows.
|
|
11
|
+
*
|
|
12
|
+
* Kept as a pure function so it is testable without a database, and so the dashboard has no query
|
|
13
|
+
* logic of its own.
|
|
14
|
+
*/
|
|
15
|
+
export declare function aggregateEvents(events: {
|
|
16
|
+
query: string;
|
|
17
|
+
resultCount: number;
|
|
18
|
+
}[]): {
|
|
19
|
+
topQueries: QueryStat[];
|
|
20
|
+
total: number;
|
|
21
|
+
zeroResultQueries: QueryStat[];
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Record one search, and prune anything past the retention window.
|
|
25
|
+
*
|
|
26
|
+
* Pruning on write keeps the log bounded without needing a scheduled job, which a plugin cannot
|
|
27
|
+
* assume the host project has.
|
|
28
|
+
*/
|
|
29
|
+
export declare function recordSearch({ clickedHref, collectionSlug, payload, query, resultCount, retentionDays, }: {
|
|
30
|
+
clickedHref?: string;
|
|
31
|
+
collectionSlug: string;
|
|
32
|
+
payload: Payload;
|
|
33
|
+
query: string;
|
|
34
|
+
resultCount: number;
|
|
35
|
+
retentionDays: number;
|
|
36
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** Normalise a query for aggregation so "Sri Lanka" and " sri lanka " count as one term. */ export const normalizeQuery = (query)=>query.trim().toLowerCase();
|
|
2
|
+
/**
|
|
3
|
+
* Aggregate raw events into the per-query counts the dashboard shows.
|
|
4
|
+
*
|
|
5
|
+
* Kept as a pure function so it is testable without a database, and so the dashboard has no query
|
|
6
|
+
* logic of its own.
|
|
7
|
+
*/ export function aggregateEvents(events) {
|
|
8
|
+
const byQuery = new Map();
|
|
9
|
+
for (const event of events){
|
|
10
|
+
const query = normalizeQuery(event.query);
|
|
11
|
+
if (!query) {
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
const stat = byQuery.get(query) ?? {
|
|
15
|
+
count: 0,
|
|
16
|
+
query,
|
|
17
|
+
zeroResultCount: 0
|
|
18
|
+
};
|
|
19
|
+
stat.count += 1;
|
|
20
|
+
if (event.resultCount === 0) {
|
|
21
|
+
stat.zeroResultCount += 1;
|
|
22
|
+
}
|
|
23
|
+
byQuery.set(query, stat);
|
|
24
|
+
}
|
|
25
|
+
const stats = [
|
|
26
|
+
...byQuery.values()
|
|
27
|
+
];
|
|
28
|
+
const byCount = (a, b)=>b.count - a.count || a.query.localeCompare(b.query);
|
|
29
|
+
return {
|
|
30
|
+
topQueries: [
|
|
31
|
+
...stats
|
|
32
|
+
].sort(byCount),
|
|
33
|
+
total: events.length,
|
|
34
|
+
zeroResultQueries: stats.filter((stat)=>stat.zeroResultCount > 0).sort((a, b)=>b.zeroResultCount - a.zeroResultCount || a.query.localeCompare(b.query))
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Record one search, and prune anything past the retention window.
|
|
39
|
+
*
|
|
40
|
+
* Pruning on write keeps the log bounded without needing a scheduled job, which a plugin cannot
|
|
41
|
+
* assume the host project has.
|
|
42
|
+
*/ export async function recordSearch({ clickedHref, collectionSlug, payload, query, resultCount, retentionDays }) {
|
|
43
|
+
const normalized = normalizeQuery(query);
|
|
44
|
+
if (!normalized) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
await payload.create({
|
|
48
|
+
collection: collectionSlug,
|
|
49
|
+
data: {
|
|
50
|
+
clickedHref,
|
|
51
|
+
query: normalized,
|
|
52
|
+
resultCount
|
|
53
|
+
},
|
|
54
|
+
overrideAccess: true
|
|
55
|
+
});
|
|
56
|
+
if (retentionDays <= 0) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000).toISOString();
|
|
60
|
+
await payload.delete({
|
|
61
|
+
collection: collectionSlug,
|
|
62
|
+
overrideAccess: true,
|
|
63
|
+
where: {
|
|
64
|
+
createdAt: {
|
|
65
|
+
less_than: cutoff
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=analytics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\n/** Normalise a query for aggregation so \"Sri Lanka\" and \" sri lanka \" count as one term. */\nexport const normalizeQuery = (query: string): string => query.trim().toLowerCase()\n\nexport type QueryStat = {\n count: number\n query: string\n zeroResultCount: number\n}\n\n/**\n * Aggregate raw events into the per-query counts the dashboard shows.\n *\n * Kept as a pure function so it is testable without a database, and so the dashboard has no query\n * logic of its own.\n */\nexport function aggregateEvents(\n events: { query: string; resultCount: number }[],\n): { topQueries: QueryStat[]; total: number; zeroResultQueries: QueryStat[] } {\n const byQuery = new Map<string, QueryStat>()\n\n for (const event of events) {\n const query = normalizeQuery(event.query)\n if (!query) {\n continue\n }\n\n const stat = byQuery.get(query) ?? { count: 0, query, zeroResultCount: 0 }\n stat.count += 1\n if (event.resultCount === 0) {\n stat.zeroResultCount += 1\n }\n byQuery.set(query, stat)\n }\n\n const stats = [...byQuery.values()]\n const byCount = (a: QueryStat, b: QueryStat) => b.count - a.count || a.query.localeCompare(b.query)\n\n return {\n topQueries: [...stats].sort(byCount),\n total: events.length,\n zeroResultQueries: stats\n .filter((stat) => stat.zeroResultCount > 0)\n .sort((a, b) => b.zeroResultCount - a.zeroResultCount || a.query.localeCompare(b.query)),\n }\n}\n\n/**\n * Record one search, and prune anything past the retention window.\n *\n * Pruning on write keeps the log bounded without needing a scheduled job, which a plugin cannot\n * assume the host project has.\n */\nexport async function recordSearch({\n clickedHref,\n collectionSlug,\n payload,\n query,\n resultCount,\n retentionDays,\n}: {\n clickedHref?: string\n collectionSlug: string\n payload: Payload\n query: string\n resultCount: number\n retentionDays: number\n}): Promise<void> {\n const normalized = normalizeQuery(query)\n if (!normalized) {\n return\n }\n\n await payload.create({\n collection: collectionSlug as never,\n data: { clickedHref, query: normalized, resultCount } as never,\n overrideAccess: true,\n })\n\n if (retentionDays <= 0) {\n return\n }\n\n const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000).toISOString()\n\n await payload.delete({\n collection: collectionSlug as never,\n overrideAccess: true,\n where: { createdAt: { less_than: cutoff } },\n })\n}\n"],"names":["normalizeQuery","query","trim","toLowerCase","aggregateEvents","events","byQuery","Map","event","stat","get","count","zeroResultCount","resultCount","set","stats","values","byCount","a","b","localeCompare","topQueries","sort","total","length","zeroResultQueries","filter","recordSearch","clickedHref","collectionSlug","payload","retentionDays","normalized","create","collection","data","overrideAccess","cutoff","Date","now","toISOString","delete","where","createdAt","less_than"],"mappings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EP;YAAa3B,OAAO+B;YAAYnB;QAAY;QACpDuB,gBAAgB;IAClB;IAEA,IAAIL,iBAAiB,GAAG;QACtB;IACF;IAEA,MAAMM,SAAS,IAAIC,KAAKA,KAAKC,GAAG,KAAKR,gBAAgB,KAAK,KAAK,KAAK,MAAMS,WAAW;IAErF,MAAMV,QAAQW,MAAM,CAAC;QACnBP,YAAYL;QACZO,gBAAgB;QAChBM,OAAO;YAAEC,WAAW;gBAAEC,WAAWP;YAAO;QAAE;IAC5C;AACF"}
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { IndexedDoc } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Holds the projected index in memory for a TTL.
|
|
4
|
+
*
|
|
5
|
+
* The read path is otherwise one query per configured collection on every keystroke-driven
|
|
6
|
+
* request. A short TTL removes that without the staleness of a full-page cache: the projection is
|
|
7
|
+
* cheap to rebuild, and `invalidate` gives content changes an immediate path back to fresh data
|
|
8
|
+
* rather than waiting the TTL out.
|
|
9
|
+
*/
|
|
10
|
+
export declare class SearchIndexCache {
|
|
11
|
+
private snapshot;
|
|
12
|
+
private ttl;
|
|
13
|
+
constructor(ttlMs?: number);
|
|
14
|
+
/** Timestamp of the held snapshot, for the inspector. */
|
|
15
|
+
builtAt(): null | number;
|
|
16
|
+
configure(ttlMs: number): void;
|
|
17
|
+
get(): IndexedDoc[] | undefined;
|
|
18
|
+
invalidate(): void;
|
|
19
|
+
set(docs: IndexedDoc[]): void;
|
|
20
|
+
}
|
|
21
|
+
export declare const searchIndexCache: SearchIndexCache;
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Holds the projected index in memory for a TTL.
|
|
3
|
+
*
|
|
4
|
+
* The read path is otherwise one query per configured collection on every keystroke-driven
|
|
5
|
+
* request. A short TTL removes that without the staleness of a full-page cache: the projection is
|
|
6
|
+
* cheap to rebuild, and `invalidate` gives content changes an immediate path back to fresh data
|
|
7
|
+
* rather than waiting the TTL out.
|
|
8
|
+
*/ export class SearchIndexCache {
|
|
9
|
+
snapshot = null;
|
|
10
|
+
ttl;
|
|
11
|
+
constructor(ttlMs = 60_000){
|
|
12
|
+
this.ttl = ttlMs;
|
|
13
|
+
}
|
|
14
|
+
/** Timestamp of the held snapshot, for the inspector. */ builtAt() {
|
|
15
|
+
return this.snapshot?.builtAt ?? null;
|
|
16
|
+
}
|
|
17
|
+
configure(ttlMs) {
|
|
18
|
+
this.ttl = ttlMs;
|
|
19
|
+
}
|
|
20
|
+
get() {
|
|
21
|
+
if (!this.snapshot) {
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
if (Date.now() - this.snapshot.builtAt > this.ttl) {
|
|
25
|
+
this.snapshot = null;
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
return this.snapshot.docs;
|
|
29
|
+
}
|
|
30
|
+
invalidate() {
|
|
31
|
+
this.snapshot = null;
|
|
32
|
+
}
|
|
33
|
+
set(docs) {
|
|
34
|
+
this.snapshot = {
|
|
35
|
+
builtAt: Date.now(),
|
|
36
|
+
docs
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
export const searchIndexCache = new SearchIndexCache();
|
|
41
|
+
|
|
42
|
+
//# sourceMappingURL=cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/cache.ts"],"sourcesContent":["import type { IndexedDoc } from './types.js'\n\ntype Snapshot = {\n builtAt: number\n docs: IndexedDoc[]\n}\n\n/**\n * Holds the projected index in memory for a TTL.\n *\n * The read path is otherwise one query per configured collection on every keystroke-driven\n * request. A short TTL removes that without the staleness of a full-page cache: the projection is\n * cheap to rebuild, and `invalidate` gives content changes an immediate path back to fresh data\n * rather than waiting the TTL out.\n */\nexport class SearchIndexCache {\n private snapshot: null | Snapshot = null\n\n private ttl: number\n\n constructor(ttlMs = 60_000) {\n this.ttl = ttlMs\n }\n\n /** Timestamp of the held snapshot, for the inspector. */\n builtAt(): null | number {\n return this.snapshot?.builtAt ?? null\n }\n\n configure(ttlMs: number): void {\n this.ttl = ttlMs\n }\n\n get(): IndexedDoc[] | undefined {\n if (!this.snapshot) {\n return undefined\n }\n if (Date.now() - this.snapshot.builtAt > this.ttl) {\n this.snapshot = null\n return undefined\n }\n return this.snapshot.docs\n }\n\n invalidate(): void {\n this.snapshot = null\n }\n\n set(docs: IndexedDoc[]): void {\n this.snapshot = { builtAt: Date.now(), docs }\n }\n}\n\nexport const searchIndexCache = new SearchIndexCache()\n"],"names":["SearchIndexCache","snapshot","ttl","ttlMs","builtAt","configure","get","undefined","Date","now","docs","invalidate","set","searchIndexCache"],"mappings":"AAOA;;;;;;;CAOC,GACD,OAAO,MAAMA;IACHC,WAA4B,KAAI;IAEhCC,IAAW;IAEnB,YAAYC,QAAQ,MAAM,CAAE;QAC1B,IAAI,CAACD,GAAG,GAAGC;IACb;IAEA,uDAAuD,GACvDC,UAAyB;QACvB,OAAO,IAAI,CAACH,QAAQ,EAAEG,WAAW;IACnC;IAEAC,UAAUF,KAAa,EAAQ;QAC7B,IAAI,CAACD,GAAG,GAAGC;IACb;IAEAG,MAAgC;QAC9B,IAAI,CAAC,IAAI,CAACL,QAAQ,EAAE;YAClB,OAAOM;QACT;QACA,IAAIC,KAAKC,GAAG,KAAK,IAAI,CAACR,QAAQ,CAACG,OAAO,GAAG,IAAI,CAACF,GAAG,EAAE;YACjD,IAAI,CAACD,QAAQ,GAAG;YAChB,OAAOM;QACT;QACA,OAAO,IAAI,CAACN,QAAQ,CAACS,IAAI;IAC3B;IAEAC,aAAmB;QACjB,IAAI,CAACV,QAAQ,GAAG;IAClB;IAEAW,IAAIF,IAAkB,EAAQ;QAC5B,IAAI,CAACT,QAAQ,GAAG;YAAEG,SAASI,KAAKC,GAAG;YAAIC;QAAK;IAC9C;AACF;AAEA,OAAO,MAAMG,mBAAmB,IAAIb,mBAAkB"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { CollectionConfig } from 'payload';
|
|
2
|
+
/**
|
|
3
|
+
* Stored search events.
|
|
4
|
+
*
|
|
5
|
+
* Deliberately narrow. Queries are behavioural data, so nothing here identifies a user: no IP, no
|
|
6
|
+
* session, no user relationship. Aggregate counts and the zero-result list are what make the
|
|
7
|
+
* preset and relevance work evidence-based, and they carry far less baggage than a per-user log.
|
|
8
|
+
*
|
|
9
|
+
* Every search complaint on a project tends to arrive anecdotally — "pages like careers don't
|
|
10
|
+
* appear", "searching X shows things that don't match". A zero-result log surfaces those before a
|
|
11
|
+
* client has to notice.
|
|
12
|
+
*/
|
|
13
|
+
export declare const createSearchEventsCollection: ({ slug, }?: {
|
|
14
|
+
slug?: string;
|
|
15
|
+
}) => CollectionConfig;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stored search events.
|
|
3
|
+
*
|
|
4
|
+
* Deliberately narrow. Queries are behavioural data, so nothing here identifies a user: no IP, no
|
|
5
|
+
* session, no user relationship. Aggregate counts and the zero-result list are what make the
|
|
6
|
+
* preset and relevance work evidence-based, and they carry far less baggage than a per-user log.
|
|
7
|
+
*
|
|
8
|
+
* Every search complaint on a project tends to arrive anecdotally — "pages like careers don't
|
|
9
|
+
* appear", "searching X shows things that don't match". A zero-result log surfaces those before a
|
|
10
|
+
* client has to notice.
|
|
11
|
+
*/ export const createSearchEventsCollection = ({ slug = 'search-events' } = {})=>({
|
|
12
|
+
slug,
|
|
13
|
+
access: {
|
|
14
|
+
// Written by the tracking endpoint via overrideAccess, never by a public API caller.
|
|
15
|
+
create: ()=>false,
|
|
16
|
+
delete: ({ req })=>Boolean(req.user),
|
|
17
|
+
read: ({ req })=>Boolean(req.user),
|
|
18
|
+
update: ()=>false
|
|
19
|
+
},
|
|
20
|
+
admin: {
|
|
21
|
+
defaultColumns: [
|
|
22
|
+
'query',
|
|
23
|
+
'resultCount',
|
|
24
|
+
'createdAt'
|
|
25
|
+
],
|
|
26
|
+
description: 'What visitors search for, and what returns nothing. Aggregated only — no per-user data is stored.',
|
|
27
|
+
group: 'Settings',
|
|
28
|
+
useAsTitle: 'query'
|
|
29
|
+
},
|
|
30
|
+
fields: [
|
|
31
|
+
{
|
|
32
|
+
name: 'query',
|
|
33
|
+
type: 'text',
|
|
34
|
+
admin: {
|
|
35
|
+
readOnly: true
|
|
36
|
+
},
|
|
37
|
+
index: true,
|
|
38
|
+
required: true
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
name: 'resultCount',
|
|
42
|
+
type: 'number',
|
|
43
|
+
admin: {
|
|
44
|
+
description: 'Zero means the query returned nothing — the most useful signal here.',
|
|
45
|
+
readOnly: true
|
|
46
|
+
},
|
|
47
|
+
index: true,
|
|
48
|
+
required: true
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
name: 'clickedHref',
|
|
52
|
+
type: 'text',
|
|
53
|
+
admin: {
|
|
54
|
+
description: 'Set when the visitor opened a result, so click-through can be measured.',
|
|
55
|
+
readOnly: true
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
],
|
|
59
|
+
timestamps: true
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
//# sourceMappingURL=SearchEvents.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/collections/SearchEvents.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\n/**\n * Stored search events.\n *\n * Deliberately narrow. Queries are behavioural data, so nothing here identifies a user: no IP, no\n * session, no user relationship. Aggregate counts and the zero-result list are what make the\n * preset and relevance work evidence-based, and they carry far less baggage than a per-user log.\n *\n * Every search complaint on a project tends to arrive anecdotally — \"pages like careers don't\n * appear\", \"searching X shows things that don't match\". A zero-result log surfaces those before a\n * client has to notice.\n */\nexport const createSearchEventsCollection = ({\n slug = 'search-events',\n}: {\n slug?: string\n} = {}): CollectionConfig => ({\n slug,\n access: {\n // Written by the tracking endpoint via overrideAccess, never by a public API caller.\n create: () => false,\n delete: ({ req }) => Boolean(req.user),\n read: ({ req }) => Boolean(req.user),\n update: () => false,\n },\n admin: {\n defaultColumns: ['query', 'resultCount', 'createdAt'],\n description:\n 'What visitors search for, and what returns nothing. Aggregated only — no per-user data is stored.',\n group: 'Settings',\n useAsTitle: 'query',\n },\n fields: [\n {\n name: 'query',\n type: 'text',\n admin: { readOnly: true },\n index: true,\n required: true,\n },\n {\n name: 'resultCount',\n type: 'number',\n admin: {\n description: 'Zero means the query returned nothing — the most useful signal here.',\n readOnly: true,\n },\n index: true,\n required: true,\n },\n {\n name: 'clickedHref',\n type: 'text',\n admin: {\n description: 'Set when the visitor opened a result, so click-through can be measured.',\n readOnly: true,\n },\n },\n ],\n timestamps: true,\n})\n"],"names":["createSearchEventsCollection","slug","access","create","delete","req","Boolean","user","read","update","admin","defaultColumns","description","group","useAsTitle","fields","name","type","readOnly","index","required","timestamps"],"mappings":"AAEA;;;;;;;;;;CAUC,GACD,OAAO,MAAMA,+BAA+B,CAAC,EAC3CC,OAAO,eAAe,EAGvB,GAAG,CAAC,CAAC,GAAwB,CAAA;QAC5BA;QACAC,QAAQ;YACN,qFAAqF;YACrFC,QAAQ,IAAM;YACdC,QAAQ,CAAC,EAAEC,GAAG,EAAE,GAAKC,QAAQD,IAAIE,IAAI;YACrCC,MAAM,CAAC,EAAEH,GAAG,EAAE,GAAKC,QAAQD,IAAIE,IAAI;YACnCE,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,gBAAgB;gBAAC;gBAAS;gBAAe;aAAY;YACrDC,aACE;YACFC,OAAO;YACPC,YAAY;QACd;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;gBACNP,OAAO;oBAAEQ,UAAU;gBAAK;gBACxBC,OAAO;gBACPC,UAAU;YACZ;YACA;gBACEJ,MAAM;gBACNC,MAAM;gBACNP,OAAO;oBACLE,aAAa;oBACbM,UAAU;gBACZ;gBACAC,OAAO;gBACPC,UAAU;YACZ;YACA;gBACEJ,MAAM;gBACNC,MAAM;gBACNP,OAAO;oBACLE,aAAa;oBACbM,UAAU;gBACZ;YACF;SACD;QACDG,YAAY;IACd,CAAA,EAAE"}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
import React from 'react';
|
|
3
|
+
import type { SearchPluginConfig } from '../types.js';
|
|
4
|
+
/**
|
|
5
|
+
* Admin dashboard: what people search for, what returns nothing, and what is actually indexed.
|
|
6
|
+
*
|
|
7
|
+
* A server component so it can read the index and the event log directly. It renders counts only —
|
|
8
|
+
* the aggregation lives in `aggregateEvents` so it stays testable without a database.
|
|
9
|
+
*/
|
|
10
|
+
export declare function SearchDashboard({ config, payload, }: {
|
|
11
|
+
config: SearchPluginConfig;
|
|
12
|
+
payload: Payload;
|
|
13
|
+
}): Promise<React.JSX.Element>;
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import React from 'react';
|
|
3
|
+
import { aggregateEvents } from '../analytics.js';
|
|
4
|
+
import { searchIndexCache } from '../cache.js';
|
|
5
|
+
import { resolveAnalytics } from '../options.js';
|
|
6
|
+
import { createSearchService } from '../resolve.js';
|
|
7
|
+
/**
|
|
8
|
+
* Admin dashboard: what people search for, what returns nothing, and what is actually indexed.
|
|
9
|
+
*
|
|
10
|
+
* A server component so it can read the index and the event log directly. It renders counts only —
|
|
11
|
+
* the aggregation lives in `aggregateEvents` so it stays testable without a database.
|
|
12
|
+
*/ export async function SearchDashboard({ config, payload }) {
|
|
13
|
+
const analytics = resolveAnalytics(config.analytics);
|
|
14
|
+
const report = await createSearchService({
|
|
15
|
+
cache: searchIndexCache,
|
|
16
|
+
config,
|
|
17
|
+
payload
|
|
18
|
+
}).inspect();
|
|
19
|
+
let topQueries = [];
|
|
20
|
+
let zeroResultQueries = [];
|
|
21
|
+
let totalSearches = 0;
|
|
22
|
+
if (analytics.enabled) {
|
|
23
|
+
const events = await payload.find({
|
|
24
|
+
collection: analytics.collectionSlug,
|
|
25
|
+
depth: 0,
|
|
26
|
+
limit: 0,
|
|
27
|
+
pagination: false
|
|
28
|
+
});
|
|
29
|
+
const aggregated = aggregateEvents(events.docs);
|
|
30
|
+
topQueries = aggregated.topQueries.slice(0, 20);
|
|
31
|
+
zeroResultQueries = aggregated.zeroResultQueries.slice(0, 20);
|
|
32
|
+
totalSearches = aggregated.total;
|
|
33
|
+
}
|
|
34
|
+
return /*#__PURE__*/ _jsxs("div", {
|
|
35
|
+
className: "search-dashboard",
|
|
36
|
+
children: [
|
|
37
|
+
/*#__PURE__*/ _jsx("h2", {
|
|
38
|
+
children: "Search"
|
|
39
|
+
}),
|
|
40
|
+
/*#__PURE__*/ _jsxs("section", {
|
|
41
|
+
children: [
|
|
42
|
+
/*#__PURE__*/ _jsx("h3", {
|
|
43
|
+
children: "Index"
|
|
44
|
+
}),
|
|
45
|
+
/*#__PURE__*/ _jsxs("p", {
|
|
46
|
+
children: [
|
|
47
|
+
report.total,
|
|
48
|
+
" documents indexed",
|
|
49
|
+
report.builtAt ? ` — built ${report.builtAt}` : ''
|
|
50
|
+
]
|
|
51
|
+
}),
|
|
52
|
+
/*#__PURE__*/ _jsxs("table", {
|
|
53
|
+
children: [
|
|
54
|
+
/*#__PURE__*/ _jsx("thead", {
|
|
55
|
+
children: /*#__PURE__*/ _jsxs("tr", {
|
|
56
|
+
children: [
|
|
57
|
+
/*#__PURE__*/ _jsx("th", {
|
|
58
|
+
children: "Collection"
|
|
59
|
+
}),
|
|
60
|
+
/*#__PURE__*/ _jsx("th", {
|
|
61
|
+
children: "Indexed"
|
|
62
|
+
}),
|
|
63
|
+
/*#__PURE__*/ _jsx("th", {
|
|
64
|
+
children: "Skipped"
|
|
65
|
+
})
|
|
66
|
+
]
|
|
67
|
+
})
|
|
68
|
+
}),
|
|
69
|
+
/*#__PURE__*/ _jsx("tbody", {
|
|
70
|
+
children: report.collections.map((row)=>/*#__PURE__*/ _jsxs("tr", {
|
|
71
|
+
children: [
|
|
72
|
+
/*#__PURE__*/ _jsx("td", {
|
|
73
|
+
children: row.slug
|
|
74
|
+
}),
|
|
75
|
+
/*#__PURE__*/ _jsx("td", {
|
|
76
|
+
children: row.indexed
|
|
77
|
+
}),
|
|
78
|
+
/*#__PURE__*/ _jsx("td", {
|
|
79
|
+
children: row.excluded
|
|
80
|
+
})
|
|
81
|
+
]
|
|
82
|
+
}, row.slug))
|
|
83
|
+
})
|
|
84
|
+
]
|
|
85
|
+
})
|
|
86
|
+
]
|
|
87
|
+
}),
|
|
88
|
+
report.skipped.length > 0 && /*#__PURE__*/ _jsxs("section", {
|
|
89
|
+
children: [
|
|
90
|
+
/*#__PURE__*/ _jsx("h3", {
|
|
91
|
+
children: "Skipped documents"
|
|
92
|
+
}),
|
|
93
|
+
/*#__PURE__*/ _jsx("ul", {
|
|
94
|
+
children: report.skipped.slice(0, 50).map((row)=>/*#__PURE__*/ _jsxs("li", {
|
|
95
|
+
children: [
|
|
96
|
+
row.slug,
|
|
97
|
+
" #",
|
|
98
|
+
row.id,
|
|
99
|
+
" — ",
|
|
100
|
+
row.reason
|
|
101
|
+
]
|
|
102
|
+
}, `${row.slug}-${row.id}`))
|
|
103
|
+
})
|
|
104
|
+
]
|
|
105
|
+
}),
|
|
106
|
+
!analytics.enabled && /*#__PURE__*/ _jsx("section", {
|
|
107
|
+
children: /*#__PURE__*/ _jsxs("p", {
|
|
108
|
+
children: [
|
|
109
|
+
"Search analytics are disabled. Enable the ",
|
|
110
|
+
/*#__PURE__*/ _jsx("code", {
|
|
111
|
+
children: "analytics"
|
|
112
|
+
}),
|
|
113
|
+
" option to record what visitors search for and which queries return nothing."
|
|
114
|
+
]
|
|
115
|
+
})
|
|
116
|
+
}),
|
|
117
|
+
analytics.enabled && /*#__PURE__*/ _jsxs(_Fragment, {
|
|
118
|
+
children: [
|
|
119
|
+
/*#__PURE__*/ _jsxs("section", {
|
|
120
|
+
children: [
|
|
121
|
+
/*#__PURE__*/ _jsx("h3", {
|
|
122
|
+
children: "Zero-result queries"
|
|
123
|
+
}),
|
|
124
|
+
/*#__PURE__*/ _jsx("p", {
|
|
125
|
+
children: "Searches that found nothing — the shortest path to a content or relevance gap."
|
|
126
|
+
}),
|
|
127
|
+
zeroResultQueries.length === 0 ? /*#__PURE__*/ _jsx("p", {
|
|
128
|
+
children: "None recorded."
|
|
129
|
+
}) : /*#__PURE__*/ _jsx("ol", {
|
|
130
|
+
children: zeroResultQueries.map((stat)=>/*#__PURE__*/ _jsxs("li", {
|
|
131
|
+
children: [
|
|
132
|
+
stat.query,
|
|
133
|
+
" — ",
|
|
134
|
+
stat.zeroResultCount
|
|
135
|
+
]
|
|
136
|
+
}, stat.query))
|
|
137
|
+
})
|
|
138
|
+
]
|
|
139
|
+
}),
|
|
140
|
+
/*#__PURE__*/ _jsxs("section", {
|
|
141
|
+
children: [
|
|
142
|
+
/*#__PURE__*/ _jsx("h3", {
|
|
143
|
+
children: "Top queries"
|
|
144
|
+
}),
|
|
145
|
+
/*#__PURE__*/ _jsxs("p", {
|
|
146
|
+
children: [
|
|
147
|
+
totalSearches,
|
|
148
|
+
" searches recorded."
|
|
149
|
+
]
|
|
150
|
+
}),
|
|
151
|
+
topQueries.length === 0 ? /*#__PURE__*/ _jsx("p", {
|
|
152
|
+
children: "None recorded."
|
|
153
|
+
}) : /*#__PURE__*/ _jsx("ol", {
|
|
154
|
+
children: topQueries.map((stat)=>/*#__PURE__*/ _jsxs("li", {
|
|
155
|
+
children: [
|
|
156
|
+
stat.query,
|
|
157
|
+
" — ",
|
|
158
|
+
stat.count
|
|
159
|
+
]
|
|
160
|
+
}, stat.query))
|
|
161
|
+
})
|
|
162
|
+
]
|
|
163
|
+
})
|
|
164
|
+
]
|
|
165
|
+
})
|
|
166
|
+
]
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
//# sourceMappingURL=SearchDashboard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/components/SearchDashboard.tsx"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport React from 'react'\n\nimport type { SearchPluginConfig } from '../types.js'\n\nimport { aggregateEvents } from '../analytics.js'\nimport { searchIndexCache } from '../cache.js'\nimport { resolveAnalytics } from '../options.js'\nimport { createSearchService } from '../resolve.js'\n\n/**\n * Admin dashboard: what people search for, what returns nothing, and what is actually indexed.\n *\n * A server component so it can read the index and the event log directly. It renders counts only —\n * the aggregation lives in `aggregateEvents` so it stays testable without a database.\n */\nexport async function SearchDashboard({\n config,\n payload,\n}: {\n config: SearchPluginConfig\n payload: Payload\n}) {\n const analytics = resolveAnalytics(config.analytics)\n const report = await createSearchService({\n cache: searchIndexCache,\n config,\n payload,\n }).inspect()\n\n let topQueries: ReturnType<typeof aggregateEvents>['topQueries'] = []\n let zeroResultQueries: ReturnType<typeof aggregateEvents>['zeroResultQueries'] = []\n let totalSearches = 0\n\n if (analytics.enabled) {\n const events = await payload.find({\n collection: analytics.collectionSlug as never,\n depth: 0,\n limit: 0,\n pagination: false,\n })\n\n const aggregated = aggregateEvents(\n events.docs as unknown as { query: string; resultCount: number }[],\n )\n topQueries = aggregated.topQueries.slice(0, 20)\n zeroResultQueries = aggregated.zeroResultQueries.slice(0, 20)\n totalSearches = aggregated.total\n }\n\n return (\n <div className=\"search-dashboard\">\n <h2>Search</h2>\n\n <section>\n <h3>Index</h3>\n <p>\n {report.total} documents indexed\n {report.builtAt ? ` — built ${report.builtAt}` : ''}\n </p>\n <table>\n <thead>\n <tr>\n <th>Collection</th>\n <th>Indexed</th>\n <th>Skipped</th>\n </tr>\n </thead>\n <tbody>\n {report.collections.map((row) => (\n <tr key={row.slug}>\n <td>{row.slug}</td>\n <td>{row.indexed}</td>\n <td>{row.excluded}</td>\n </tr>\n ))}\n </tbody>\n </table>\n </section>\n\n {report.skipped.length > 0 && (\n <section>\n <h3>Skipped documents</h3>\n {/* Reasons, not just a count: an inventory tells you nothing when the document you care\n about is the missing one. */}\n <ul>\n {report.skipped.slice(0, 50).map((row) => (\n <li key={`${row.slug}-${row.id}`}>\n {row.slug} #{row.id} — {row.reason}\n </li>\n ))}\n </ul>\n </section>\n )}\n\n {!analytics.enabled && (\n <section>\n <p>\n Search analytics are disabled. Enable the <code>analytics</code> option to record what\n visitors search for and which queries return nothing.\n </p>\n </section>\n )}\n\n {analytics.enabled && (\n <>\n <section>\n <h3>Zero-result queries</h3>\n <p>Searches that found nothing — the shortest path to a content or relevance gap.</p>\n {zeroResultQueries.length === 0 ? (\n <p>None recorded.</p>\n ) : (\n <ol>\n {zeroResultQueries.map((stat) => (\n <li key={stat.query}>\n {stat.query} — {stat.zeroResultCount}\n </li>\n ))}\n </ol>\n )}\n </section>\n\n <section>\n <h3>Top queries</h3>\n <p>{totalSearches} searches recorded.</p>\n {topQueries.length === 0 ? (\n <p>None recorded.</p>\n ) : (\n <ol>\n {topQueries.map((stat) => (\n <li key={stat.query}>\n {stat.query} — {stat.count}\n </li>\n ))}\n </ol>\n )}\n </section>\n </>\n )}\n </div>\n )\n}\n"],"names":["React","aggregateEvents","searchIndexCache","resolveAnalytics","createSearchService","SearchDashboard","config","payload","analytics","report","cache","inspect","topQueries","zeroResultQueries","totalSearches","enabled","events","find","collection","collectionSlug","depth","limit","pagination","aggregated","docs","slice","total","div","className","h2","section","h3","p","builtAt","table","thead","tr","th","tbody","collections","map","row","td","slug","indexed","excluded","skipped","length","ul","li","id","reason","code","ol","stat","query","zeroResultCount","count"],"mappings":";AAEA,OAAOA,WAAW,QAAO;AAIzB,SAASC,eAAe,QAAQ,kBAAiB;AACjD,SAASC,gBAAgB,QAAQ,cAAa;AAC9C,SAASC,gBAAgB,QAAQ,gBAAe;AAChD,SAASC,mBAAmB,QAAQ,gBAAe;AAEnD;;;;;CAKC,GACD,OAAO,eAAeC,gBAAgB,EACpCC,MAAM,EACNC,OAAO,EAIR;IACC,MAAMC,YAAYL,iBAAiBG,OAAOE,SAAS;IAC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