@foundrykit/search-plugin 0.1.1 → 0.2.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/README.md +25 -5
- package/dist/analytics.d.ts +6 -17
- package/dist/analytics.js +10 -35
- package/dist/analytics.js.map +1 -1
- package/dist/collections/SearchEvents.d.ts +4 -4
- package/dist/collections/SearchEvents.js +64 -17
- package/dist/collections/SearchEvents.js.map +1 -1
- package/dist/endpoints/handlers.d.ts +1 -1
- package/dist/endpoints/handlers.js +25 -33
- package/dist/endpoints/handlers.js.map +1 -1
- package/dist/exports/client.d.ts +2 -0
- package/dist/exports/client.js +1 -0
- package/dist/exports/client.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/options.d.ts +3 -3
- package/dist/options.js +7 -4
- package/dist/options.js.map +1 -1
- package/dist/track.d.ts +39 -0
- package/dist/track.js +151 -0
- package/dist/track.js.map +1 -0
- package/dist/trackClient.d.ts +3 -0
- package/dist/trackClient.js +24 -0
- package/dist/trackClient.js.map +1 -0
- package/dist/types.d.ts +9 -1
- package/dist/types.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -75,7 +75,7 @@ export default buildConfig({
|
|
|
75
75
|
| `GET` | `/api/site-search?q=` | Grouped, ranked results. Empty `q` returns the preset. |
|
|
76
76
|
| `POST` | `/api/site-search/reindex` | Rebuild the projection now. Returns counts. |
|
|
77
77
|
| `GET` | `/api/site-search/inspect` | What is indexed, and why anything missing was skipped. |
|
|
78
|
-
| `POST` | `/api/site-search/track` |
|
|
78
|
+
| `POST` | `/api/site-search/track` | Record a settled search and its clicks. Only when analytics are on. |
|
|
79
79
|
|
|
80
80
|
Change the base with `routePrefix`. `reindex` and `inspect` require an authenticated user unless
|
|
81
81
|
you set `requireAdminForOperations: false`.
|
|
@@ -127,10 +127,30 @@ The hotkey is suppressed inside inputs, textareas, selects and contenteditable.
|
|
|
127
127
|
|
|
128
128
|
## Analytics and privacy
|
|
129
129
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
130
|
+
With `analytics` on, the `search-events` collection records **one row per settled search**: the
|
|
131
|
+
query, result count, the results shown, any clicks, the page it happened on, a coarse device type
|
|
132
|
+
(mobile, tablet or desktop), the referrer host, and UTM parameters. No IP address and no user
|
|
133
|
+
relationship is stored.
|
|
134
|
+
|
|
135
|
+
- **Recording.** The browser reports searches to `POST /api/site-search/track`. The `GET` search
|
|
136
|
+
endpoint no longer records anything.
|
|
137
|
+
- **`visitorCookie`** (opt-in). Name a cookie and the plugin stores its value on the event, so you
|
|
138
|
+
can tell repeat searchers apart. The plugin only *reads* it; your site sets it, and should do so
|
|
139
|
+
only with consent.
|
|
140
|
+
- **`isEnabled(req)`**. Return `false` to skip recording for a request, e.g. when consent is absent.
|
|
141
|
+
- **Retention.** Events older than `retentionDays` (default **400**) are pruned on write, so the log
|
|
142
|
+
stays bounded without a scheduled job.
|
|
143
|
+
- **Schema change.** `clickedHref` is gone and several fields are new. Hosts must generate and run
|
|
144
|
+
a migration (`payload migrate:create`).
|
|
145
|
+
|
|
146
|
+
```tsx
|
|
147
|
+
import { trackSearchEvent } from '@foundrykit/search-plugin/client'
|
|
148
|
+
|
|
149
|
+
trackSearchEvent({ searchId, query, resultCount, results, pagePath, source: 'dialog' })
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
`trackSearchEvent(payload, endpoint = '/api/site-search/track')` uses `sendBeacon`, falls back to a
|
|
153
|
+
`keepalive` fetch, and never throws.
|
|
134
154
|
|
|
135
155
|
## Dashboard
|
|
136
156
|
|
package/dist/analytics.d.ts
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/**
|
|
2
|
+
* A search box's text as a stored term: whitespace-collapsed and lower-cased so "Maldives " and
|
|
3
|
+
* "maldives" report as one term. Anything shaped like an email address or a phone number is
|
|
4
|
+
* masked — people do paste contact details into search boxes, and those must not reach analytics.
|
|
5
|
+
*/
|
|
6
|
+
export declare function cleanSearchTerm(raw: string): string;
|
|
4
7
|
export type QueryStat = {
|
|
5
8
|
count: number;
|
|
6
9
|
query: string;
|
|
@@ -20,17 +23,3 @@ export declare function aggregateEvents(events: {
|
|
|
20
23
|
total: number;
|
|
21
24
|
zeroResultQueries: QueryStat[];
|
|
22
25
|
};
|
|
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>;
|
package/dist/analytics.js
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
|
-
|
|
1
|
+
const EMAIL = /[^\s@]+@[^\s@]+\.[^\s@]+/g;
|
|
2
|
+
const NUMBER_RUN = /\+?\d[\d\s().-]*\d/g;
|
|
3
|
+
/**
|
|
4
|
+
* A search box's text as a stored term: whitespace-collapsed and lower-cased so "Maldives " and
|
|
5
|
+
* "maldives" report as one term. Anything shaped like an email address or a phone number is
|
|
6
|
+
* masked — people do paste contact details into search boxes, and those must not reach analytics.
|
|
7
|
+
*/ export function cleanSearchTerm(raw) {
|
|
8
|
+
return raw.replace(EMAIL, '[email]').replace(NUMBER_RUN, (run)=>run.replace(/\D/g, '').length >= 7 ? '[number]' : run).replace(/\s+/g, ' ').trim().toLowerCase().slice(0, 100);
|
|
9
|
+
}
|
|
2
10
|
/**
|
|
3
11
|
* Aggregate raw events into the per-query counts the dashboard shows.
|
|
4
12
|
*
|
|
@@ -7,7 +15,7 @@
|
|
|
7
15
|
*/ export function aggregateEvents(events) {
|
|
8
16
|
const byQuery = new Map();
|
|
9
17
|
for (const event of events){
|
|
10
|
-
const query =
|
|
18
|
+
const query = cleanSearchTerm(event.query);
|
|
11
19
|
if (!query) {
|
|
12
20
|
continue;
|
|
13
21
|
}
|
|
@@ -34,38 +42,5 @@
|
|
|
34
42
|
zeroResultQueries: stats.filter((stat)=>stat.zeroResultCount > 0).sort((a, b)=>b.zeroResultCount - a.zeroResultCount || a.query.localeCompare(b.query))
|
|
35
43
|
};
|
|
36
44
|
}
|
|
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
45
|
|
|
71
46
|
//# sourceMappingURL=analytics.js.map
|
package/dist/analytics.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/analytics.ts"],"sourcesContent":["
|
|
1
|
+
{"version":3,"sources":["../src/analytics.ts"],"sourcesContent":["const EMAIL = /[^\\s@]+@[^\\s@]+\\.[^\\s@]+/g\nconst NUMBER_RUN = /\\+?\\d[\\d\\s().-]*\\d/g\n\n/**\n * A search box's text as a stored term: whitespace-collapsed and lower-cased so \"Maldives \" and\n * \"maldives\" report as one term. Anything shaped like an email address or a phone number is\n * masked — people do paste contact details into search boxes, and those must not reach analytics.\n */\nexport function cleanSearchTerm(raw: string): string {\n return raw\n .replace(EMAIL, '[email]')\n .replace(NUMBER_RUN, (run) => (run.replace(/\\D/g, '').length >= 7 ? '[number]' : run))\n .replace(/\\s+/g, ' ')\n .trim()\n .toLowerCase()\n .slice(0, 100)\n}\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 = cleanSearchTerm(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"],"names":["EMAIL","NUMBER_RUN","cleanSearchTerm","raw","replace","run","length","trim","toLowerCase","slice","aggregateEvents","events","byQuery","Map","event","query","stat","get","count","zeroResultCount","resultCount","set","stats","values","byCount","a","b","localeCompare","topQueries","sort","total","zeroResultQueries","filter"],"mappings":"AAAA,MAAMA,QAAQ;AACd,MAAMC,aAAa;AAEnB;;;;CAIC,GACD,OAAO,SAASC,gBAAgBC,GAAW;IACzC,OAAOA,IACJC,OAAO,CAACJ,OAAO,WACfI,OAAO,CAACH,YAAY,CAACI,MAASA,IAAID,OAAO,CAAC,OAAO,IAAIE,MAAM,IAAI,IAAI,aAAaD,KAChFD,OAAO,CAAC,QAAQ,KAChBG,IAAI,GACJC,WAAW,GACXC,KAAK,CAAC,GAAG;AACd;AAQA;;;;;CAKC,GACD,OAAO,SAASC,gBACdC,MAAgD;IAEhD,MAAMC,UAAU,IAAIC;IAEpB,KAAK,MAAMC,SAASH,OAAQ;QAC1B,MAAMI,QAAQb,gBAAgBY,MAAMC,KAAK;QACzC,IAAI,CAACA,OAAO;YACV;QACF;QAEA,MAAMC,OAAOJ,QAAQK,GAAG,CAACF,UAAU;YAAEG,OAAO;YAAGH;YAAOI,iBAAiB;QAAE;QACzEH,KAAKE,KAAK,IAAI;QACd,IAAIJ,MAAMM,WAAW,KAAK,GAAG;YAC3BJ,KAAKG,eAAe,IAAI;QAC1B;QACAP,QAAQS,GAAG,CAACN,OAAOC;IACrB;IAEA,MAAMM,QAAQ;WAAIV,QAAQW,MAAM;KAAG;IACnC,MAAMC,UAAU,CAACC,GAAcC,IAAiBA,EAAER,KAAK,GAAGO,EAAEP,KAAK,IAAIO,EAAEV,KAAK,CAACY,aAAa,CAACD,EAAEX,KAAK;IAElG,OAAO;QACLa,YAAY;eAAIN;SAAM,CAACO,IAAI,CAACL;QAC5BM,OAAOnB,OAAOL,MAAM;QACpByB,mBAAmBT,MAChBU,MAAM,CAAC,CAAChB,OAASA,KAAKG,eAAe,GAAG,GACxCU,IAAI,CAAC,CAACJ,GAAGC,IAAMA,EAAEP,eAAe,GAAGM,EAAEN,eAAe,IAAIM,EAAEV,KAAK,CAACY,aAAa,CAACD,EAAEX,KAAK;IAC1F;AACF"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import type { CollectionConfig } from 'payload';
|
|
2
2
|
/**
|
|
3
|
-
* Stored search events.
|
|
3
|
+
* Stored search events: one row per settled search.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* Queries are behavioural data, so the stored term is masked (emails and phone numbers) before it
|
|
6
|
+
* is written. A visitor ID is stored only when the host opts in with `visitorCookie`; without it
|
|
7
|
+
* nothing here identifies a user. No IP and no user relationship are stored either way.
|
|
8
8
|
*
|
|
9
9
|
* Every search complaint on a project tends to arrive anecdotally — "pages like careers don't
|
|
10
10
|
* appear", "searching X shows things that don't match". A zero-result log surfaces those before a
|
|
@@ -1,9 +1,12 @@
|
|
|
1
|
+
const readOnly = {
|
|
2
|
+
readOnly: true
|
|
3
|
+
};
|
|
1
4
|
/**
|
|
2
|
-
* Stored search events.
|
|
5
|
+
* Stored search events: one row per settled search.
|
|
3
6
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
+
* Queries are behavioural data, so the stored term is masked (emails and phone numbers) before it
|
|
8
|
+
* is written. A visitor ID is stored only when the host opts in with `visitorCookie`; without it
|
|
9
|
+
* nothing here identifies a user. No IP and no user relationship are stored either way.
|
|
7
10
|
*
|
|
8
11
|
* Every search complaint on a project tends to arrive anecdotally — "pages like careers don't
|
|
9
12
|
* appear", "searching X shows things that don't match". A zero-result log surfaces those before a
|
|
@@ -23,37 +26,81 @@
|
|
|
23
26
|
'resultCount',
|
|
24
27
|
'createdAt'
|
|
25
28
|
],
|
|
26
|
-
description: 'What visitors search for, and what returns nothing.
|
|
29
|
+
description: 'What visitors search for, what they click, and what returns nothing. Queries are masked for emails and phone numbers; a visitor ID is stored only if the site opts in.',
|
|
27
30
|
group: 'Settings',
|
|
28
31
|
useAsTitle: 'query'
|
|
29
32
|
},
|
|
30
33
|
fields: [
|
|
34
|
+
{
|
|
35
|
+
name: 'searchId',
|
|
36
|
+
type: 'text',
|
|
37
|
+
admin: readOnly,
|
|
38
|
+
index: true,
|
|
39
|
+
required: true,
|
|
40
|
+
unique: true
|
|
41
|
+
},
|
|
31
42
|
{
|
|
32
43
|
name: 'query',
|
|
33
44
|
type: 'text',
|
|
34
|
-
admin:
|
|
35
|
-
readOnly: true
|
|
36
|
-
},
|
|
45
|
+
admin: readOnly,
|
|
37
46
|
index: true,
|
|
38
47
|
required: true
|
|
39
48
|
},
|
|
49
|
+
{
|
|
50
|
+
name: 'source',
|
|
51
|
+
type: 'text',
|
|
52
|
+
admin: readOnly,
|
|
53
|
+
index: true
|
|
54
|
+
},
|
|
40
55
|
{
|
|
41
56
|
name: 'resultCount',
|
|
42
57
|
type: 'number',
|
|
58
|
+
index: true,
|
|
43
59
|
admin: {
|
|
44
60
|
description: 'Zero means the query returned nothing — the most useful signal here.',
|
|
45
|
-
readOnly
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
|
|
61
|
+
...readOnly
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
name: 'results',
|
|
66
|
+
type: 'json',
|
|
67
|
+
admin: readOnly
|
|
49
68
|
},
|
|
50
69
|
{
|
|
51
|
-
name: '
|
|
70
|
+
name: 'clicks',
|
|
71
|
+
type: 'json',
|
|
72
|
+
admin: readOnly
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
name: 'pagePath',
|
|
52
76
|
type: 'text',
|
|
53
|
-
admin:
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
77
|
+
admin: readOnly
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
name: 'referrer',
|
|
81
|
+
type: 'text',
|
|
82
|
+
admin: readOnly
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
name: 'utm',
|
|
86
|
+
type: 'json',
|
|
87
|
+
admin: readOnly
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
name: 'device',
|
|
91
|
+
type: 'select',
|
|
92
|
+
admin: readOnly,
|
|
93
|
+
options: [
|
|
94
|
+
'mobile',
|
|
95
|
+
'tablet',
|
|
96
|
+
'desktop'
|
|
97
|
+
]
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
name: 'visitorId',
|
|
101
|
+
type: 'text',
|
|
102
|
+
admin: readOnly,
|
|
103
|
+
index: true
|
|
57
104
|
}
|
|
58
105
|
],
|
|
59
106
|
timestamps: true
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/collections/SearchEvents.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\n/**\n * Stored search events.\n *\n *
|
|
1
|
+
{"version":3,"sources":["../../src/collections/SearchEvents.ts"],"sourcesContent":["import type { CollectionConfig } from 'payload'\n\nconst readOnly = { readOnly: true }\n\n/**\n * Stored search events: one row per settled search.\n *\n * Queries are behavioural data, so the stored term is masked (emails and phone numbers) before it\n * is written. A visitor ID is stored only when the host opts in with `visitorCookie`; without it\n * nothing here identifies a user. No IP and no user relationship are stored either way.\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, what they click, and what returns nothing. Queries are masked for emails and phone numbers; a visitor ID is stored only if the site opts in.',\n group: 'Settings',\n useAsTitle: 'query',\n },\n fields: [\n { name: 'searchId', type: 'text', admin: readOnly, index: true, required: true, unique: true },\n { name: 'query', type: 'text', admin: readOnly, index: true, required: true },\n { name: 'source', type: 'text', admin: readOnly, index: true },\n {\n name: 'resultCount',\n type: 'number',\n index: true,\n admin: {\n description: 'Zero means the query returned nothing — the most useful signal here.',\n ...readOnly,\n },\n },\n { name: 'results', type: 'json', admin: readOnly },\n { name: 'clicks', type: 'json', admin: readOnly },\n { name: 'pagePath', type: 'text', admin: readOnly },\n { name: 'referrer', type: 'text', admin: readOnly },\n { name: 'utm', type: 'json', admin: readOnly },\n {\n name: 'device',\n type: 'select',\n admin: readOnly,\n options: ['mobile', 'tablet', 'desktop'],\n },\n { name: 'visitorId', type: 'text', admin: readOnly, index: true },\n ],\n timestamps: true,\n})\n"],"names":["readOnly","createSearchEventsCollection","slug","access","create","delete","req","Boolean","user","read","update","admin","defaultColumns","description","group","useAsTitle","fields","name","type","index","required","unique","options","timestamps"],"mappings":"AAEA,MAAMA,WAAW;IAAEA,UAAU;AAAK;AAElC;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,+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;gBAAEC,MAAM;gBAAYC,MAAM;gBAAQP,OAAOX;gBAAUmB,OAAO;gBAAMC,UAAU;gBAAMC,QAAQ;YAAK;YAC7F;gBAAEJ,MAAM;gBAASC,MAAM;gBAAQP,OAAOX;gBAAUmB,OAAO;gBAAMC,UAAU;YAAK;YAC5E;gBAAEH,MAAM;gBAAUC,MAAM;gBAAQP,OAAOX;gBAAUmB,OAAO;YAAK;YAC7D;gBACEF,MAAM;gBACNC,MAAM;gBACNC,OAAO;gBACPR,OAAO;oBACLE,aAAa;oBACb,GAAGb,QAAQ;gBACb;YACF;YACA;gBAAEiB,MAAM;gBAAWC,MAAM;gBAAQP,OAAOX;YAAS;YACjD;gBAAEiB,MAAM;gBAAUC,MAAM;gBAAQP,OAAOX;YAAS;YAChD;gBAAEiB,MAAM;gBAAYC,MAAM;gBAAQP,OAAOX;YAAS;YAClD;gBAAEiB,MAAM;gBAAYC,MAAM;gBAAQP,OAAOX;YAAS;YAClD;gBAAEiB,MAAM;gBAAOC,MAAM;gBAAQP,OAAOX;YAAS;YAC7C;gBACEiB,MAAM;gBACNC,MAAM;gBACNP,OAAOX;gBACPsB,SAAS;oBAAC;oBAAU;oBAAU;iBAAU;YAC1C;YACA;gBAAEL,MAAM;gBAAaC,MAAM;gBAAQP,OAAOX;gBAAUmB,OAAO;YAAK;SACjE;QACDI,YAAY;IACd,CAAA,EAAE"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { PayloadHandler } from 'payload';
|
|
2
2
|
import type { SearchIndexCache } from '../cache.js';
|
|
3
3
|
import type { SearchPluginConfig } from '../types.js';
|
|
4
|
-
/** GET — grouped, ranked results for `?q=`. Records the
|
|
4
|
+
/** GET — grouped, ranked results for `?q=`. Records nothing: it runs per keystroke, so the track endpoint owns recording. */
|
|
5
5
|
export declare const createSearchHandler: ({ cache, config, }: {
|
|
6
6
|
cache: SearchIndexCache;
|
|
7
7
|
config: SearchPluginConfig;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { recordSearch } from '../analytics.js';
|
|
2
1
|
import { resolveAnalytics } from '../options.js';
|
|
3
2
|
import { createSearchService } from '../resolve.js';
|
|
3
|
+
import { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from '../track.js';
|
|
4
4
|
const json = (body, status = 200)=>new Response(JSON.stringify(body), {
|
|
5
5
|
headers: {
|
|
6
6
|
'Content-Type': 'application/json'
|
|
@@ -15,29 +15,9 @@ const service = (req, cache, config)=>createSearchService({
|
|
|
15
15
|
config,
|
|
16
16
|
payload: req.payload
|
|
17
17
|
});
|
|
18
|
-
/** GET — grouped, ranked results for `?q=`. Records the
|
|
18
|
+
/** GET — grouped, ranked results for `?q=`. Records nothing: it runs per keystroke, so the track endpoint owns recording. */ export const createSearchHandler = ({ cache, config })=>async (req)=>{
|
|
19
19
|
const query = new URL(req.url ?? '', 'http://localhost').searchParams.get('q') ?? '';
|
|
20
20
|
const results = await service(req, cache, config).search(query);
|
|
21
|
-
const analytics = resolveAnalytics(config.analytics);
|
|
22
|
-
if (analytics.enabled && query.trim()) {
|
|
23
|
-
const resultCount = Object.values(results).reduce((sum, group)=>sum + group.length, 0);
|
|
24
|
-
// Never let a failed write break the search response — analytics are diagnostic, not
|
|
25
|
-
// load-bearing.
|
|
26
|
-
try {
|
|
27
|
-
await recordSearch({
|
|
28
|
-
collectionSlug: analytics.collectionSlug,
|
|
29
|
-
payload: req.payload,
|
|
30
|
-
query,
|
|
31
|
-
resultCount,
|
|
32
|
-
retentionDays: analytics.retentionDays
|
|
33
|
-
});
|
|
34
|
-
} catch (error) {
|
|
35
|
-
req.payload.logger.error({
|
|
36
|
-
err: error,
|
|
37
|
-
msg: 'search-plugin: failed to record search'
|
|
38
|
-
});
|
|
39
|
-
}
|
|
40
|
-
}
|
|
41
21
|
return json(results);
|
|
42
22
|
};
|
|
43
23
|
/** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */ export const createReindexHandler = ({ cache, config, requireAdmin })=>async (req)=>{
|
|
@@ -60,31 +40,43 @@ const service = (req, cache, config)=>createSearchService({
|
|
|
60
40
|
};
|
|
61
41
|
/** POST — attribute a click to a query, so click-through is measurable. */ export const createTrackHandler = ({ config })=>async (req)=>{
|
|
62
42
|
const analytics = resolveAnalytics(config.analytics);
|
|
63
|
-
if (!analytics.enabled) {
|
|
43
|
+
if (!analytics.enabled || !await analytics.isEnabled(req)) {
|
|
64
44
|
return json({
|
|
65
45
|
tracked: false
|
|
66
46
|
});
|
|
67
47
|
}
|
|
68
|
-
const
|
|
69
|
-
if (
|
|
48
|
+
const userAgent = req.headers.get('user-agent') ?? '';
|
|
49
|
+
if (req.user || isBot(userAgent)) {
|
|
70
50
|
return json({
|
|
71
|
-
|
|
51
|
+
tracked: false
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
const event = parseTrackPayload(await req.json?.().catch(()=>null));
|
|
55
|
+
if (!event) {
|
|
56
|
+
return json({
|
|
57
|
+
error: 'Invalid payload'
|
|
72
58
|
}, 400);
|
|
73
59
|
}
|
|
60
|
+
const cookieName = analytics.visitorCookie;
|
|
61
|
+
const visitorId = cookieName ? req.headers.get('cookie')?.split(';').map((c)=>c.trim().split('=')).find(([name])=>name === cookieName)?.[1]?.slice(0, 100) : undefined;
|
|
62
|
+
// Same-site referrers say nothing about acquisition; keep external hosts only.
|
|
63
|
+
const host = (req.headers.get('host') ?? '').split(':')[0];
|
|
64
|
+
if (event.referrer === host) {
|
|
65
|
+
event.referrer = undefined;
|
|
66
|
+
}
|
|
74
67
|
try {
|
|
75
|
-
await
|
|
76
|
-
clickedHref: body.href,
|
|
68
|
+
await recordSearchEvent({
|
|
77
69
|
collectionSlug: analytics.collectionSlug,
|
|
70
|
+
device: deviceOf(userAgent),
|
|
71
|
+
event,
|
|
78
72
|
payload: req.payload,
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
resultCount: 1,
|
|
82
|
-
retentionDays: analytics.retentionDays
|
|
73
|
+
retentionDays: analytics.retentionDays,
|
|
74
|
+
visitorId
|
|
83
75
|
});
|
|
84
76
|
} catch (error) {
|
|
85
77
|
req.payload.logger.error({
|
|
86
78
|
err: error,
|
|
87
|
-
msg: 'search-plugin: failed to record
|
|
79
|
+
msg: 'search-plugin: failed to record search event'
|
|
88
80
|
});
|
|
89
81
|
}
|
|
90
82
|
return json({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/endpoints/handlers.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\n\nimport type { SearchIndexCache } from '../cache.js'\nimport type { SearchPluginConfig } from '../types.js'\n\nimport {
|
|
1
|
+
{"version":3,"sources":["../../src/endpoints/handlers.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\n\nimport type { SearchIndexCache } from '../cache.js'\nimport type { SearchPluginConfig } from '../types.js'\n\nimport { resolveAnalytics } from '../options.js'\nimport { createSearchService } from '../resolve.js'\nimport { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from '../track.js'\n\nconst json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n headers: { 'Content-Type': 'application/json' },\n status,\n })\n\nconst forbidden = () => json({ error: 'Not permitted' }, 403)\n\nconst service = (req: PayloadRequest, cache: SearchIndexCache, config: SearchPluginConfig) =>\n createSearchService({ cache, config, payload: req.payload })\n\n/** GET — grouped, ranked results for `?q=`. Records nothing: it runs per keystroke, so the track endpoint owns recording. */\nexport const createSearchHandler =\n ({\n cache,\n config,\n }: {\n cache: SearchIndexCache\n config: SearchPluginConfig\n }): PayloadHandler =>\n async (req) => {\n const query = new URL(req.url ?? '', 'http://localhost').searchParams.get('q') ?? ''\n const results = await service(req, cache, config).search(query)\n\n return json(results)\n }\n\n/** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */\nexport const createReindexHandler =\n ({\n cache,\n config,\n requireAdmin,\n }: {\n cache: SearchIndexCache\n config: SearchPluginConfig\n requireAdmin: boolean\n }): PayloadHandler =>\n async (req) => {\n if (requireAdmin && !req.user) {\n return forbidden()\n }\n\n const stats = await service(req, cache, config).reindex()\n\n // Reported rather than silently succeeding: the point is for a non-developer to be able to\n // tell whether it worked.\n return json({\n message: `Reindexed ${stats.indexed} documents, ${stats.skipped} skipped.`,\n ...stats,\n })\n }\n\n/** GET — what is searchable, and why anything missing was left out. */\nexport const createInspectHandler =\n ({\n cache,\n config,\n requireAdmin,\n }: {\n cache: SearchIndexCache\n config: SearchPluginConfig\n requireAdmin: boolean\n }): PayloadHandler =>\n async (req) => {\n if (requireAdmin && !req.user) {\n return forbidden()\n }\n\n return json(await service(req, cache, config).inspect())\n }\n\n/** POST — attribute a click to a query, so click-through is measurable. */\nexport const createTrackHandler =\n ({ config }: { config: SearchPluginConfig }): PayloadHandler =>\n async (req) => {\n const analytics = resolveAnalytics(config.analytics)\n if (!analytics.enabled || !(await analytics.isEnabled(req))) {\n return json({ tracked: false })\n }\n\n const userAgent = req.headers.get('user-agent') ?? ''\n if (req.user || isBot(userAgent)) {\n return json({ tracked: false })\n }\n\n const event = parseTrackPayload(await req.json?.().catch(() => null))\n if (!event) {\n return json({ error: 'Invalid payload' }, 400)\n }\n\n const cookieName = analytics.visitorCookie\n const visitorId = cookieName\n ? req.headers\n .get('cookie')\n ?.split(';')\n .map((c) => c.trim().split('='))\n .find(([name]) => name === cookieName)?.[1]\n ?.slice(0, 100)\n : undefined\n\n // Same-site referrers say nothing about acquisition; keep external hosts only.\n const host = (req.headers.get('host') ?? '').split(':')[0]\n if (event.referrer === host) {\n event.referrer = undefined\n }\n\n try {\n await recordSearchEvent({\n collectionSlug: analytics.collectionSlug,\n device: deviceOf(userAgent),\n event,\n payload: req.payload,\n retentionDays: analytics.retentionDays,\n visitorId,\n })\n } catch (error) {\n req.payload.logger.error({ err: error, msg: 'search-plugin: failed to record search event' })\n }\n\n return json({ tracked: true })\n }\n"],"names":["resolveAnalytics","createSearchService","deviceOf","isBot","parseTrackPayload","recordSearchEvent","json","body","status","Response","JSON","stringify","headers","forbidden","error","service","req","cache","config","payload","createSearchHandler","query","URL","url","searchParams","get","results","search","createReindexHandler","requireAdmin","user","stats","reindex","message","indexed","skipped","createInspectHandler","inspect","createTrackHandler","analytics","enabled","isEnabled","tracked","userAgent","event","catch","cookieName","visitorCookie","visitorId","split","map","c","trim","find","name","slice","undefined","host","referrer","collectionSlug","device","retentionDays","logger","err","msg"],"mappings":"AAKA,SAASA,gBAAgB,QAAQ,gBAA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B,UAAUoB,cAAc;gBACxCC,QAAQ1D,SAASyC;gBACjBC;gBACAzB,SAASH,IAAIG,OAAO;gBACpB0C,eAAetB,UAAUsB,aAAa;gBACtCb;YACF;QACF,EAAE,OAAOlC,OAAO;YACdE,IAAIG,OAAO,CAAC2C,MAAM,CAAChD,KAAK,CAAC;gBAAEiD,KAAKjD;gBAAOkD,KAAK;YAA+C;QAC7F;QAEA,OAAO1D,KAAK;YAAEoC,SAAS;QAAK;IAC9B,EAAC"}
|
package/dist/exports/client.d.ts
CHANGED
package/dist/exports/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export { isEditableTarget, useIsAppleDevice, useSearchHotkey } from '../components/useSearchHotkey.js'\n"],"names":["isEditableTarget","useIsAppleDevice","useSearchHotkey"],"mappings":"AAAA,SAASA,gBAAgB,EAAEC,gBAAgB,EAAEC,eAAe,QAAQ,mCAAkC"}
|
|
1
|
+
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export { isEditableTarget, useIsAppleDevice, useSearchHotkey } from '../components/useSearchHotkey.js'\nexport { trackSearchEvent } from '../trackClient.js'\nexport type { ShownResult, TrackPayload } from '../track.js'\n"],"names":["isEditableTarget","useIsAppleDevice","useSearchHotkey","trackSearchEvent"],"mappings":"AAAA,SAASA,gBAAgB,EAAEC,gBAAgB,EAAEC,eAAe,QAAQ,mCAAkC;AACtG,SAASC,gBAAgB,QAAQ,oBAAmB"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import type { Config } from 'payload';
|
|
2
2
|
import type { SearchPluginConfig } from './types.js';
|
|
3
|
-
export { aggregateEvents,
|
|
3
|
+
export { aggregateEvents, cleanSearchTerm } from './analytics.js';
|
|
4
4
|
export { SearchIndexCache, searchIndexCache } from './cache.js';
|
|
5
5
|
export { decodeEntities } from './decodeEntities.js';
|
|
6
6
|
export { hrefFor, projectDocs } from './project.js';
|
|
7
7
|
export { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs } from './rank.js';
|
|
8
8
|
export { createSearchService } from './resolve.js';
|
|
9
|
+
export { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.js';
|
|
10
|
+
export type { ShownResult, TrackPayload } from './track.js';
|
|
9
11
|
export type * from './types.js';
|
|
10
12
|
/**
|
|
11
13
|
* Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.
|
package/dist/index.js
CHANGED
|
@@ -2,12 +2,13 @@ import { searchIndexCache } from './cache.js';
|
|
|
2
2
|
import { createSearchEventsCollection } from './collections/SearchEvents.js';
|
|
3
3
|
import { createInspectHandler, createReindexHandler, createSearchHandler, createTrackHandler } from './endpoints/handlers.js';
|
|
4
4
|
import { assertConfig, resolveAnalytics } from './options.js';
|
|
5
|
-
export { aggregateEvents,
|
|
5
|
+
export { aggregateEvents, cleanSearchTerm } from './analytics.js';
|
|
6
6
|
export { SearchIndexCache, searchIndexCache } from './cache.js';
|
|
7
7
|
export { decodeEntities } from './decodeEntities.js';
|
|
8
8
|
export { hrefFor, projectDocs } from './project.js';
|
|
9
9
|
export { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs } from './rank.js';
|
|
10
10
|
export { createSearchService } from './resolve.js';
|
|
11
|
+
export { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.js';
|
|
11
12
|
/**
|
|
12
13
|
* Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.
|
|
13
14
|
*
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport type { SearchPluginConfig } from './types.js'\n\nimport { searchIndexCache } from './cache.js'\nimport { createSearchEventsCollection } from './collections/SearchEvents.js'\nimport {\n createInspectHandler,\n createReindexHandler,\n createSearchHandler,\n createTrackHandler,\n} from './endpoints/handlers.js'\nimport { assertConfig, resolveAnalytics } from './options.js'\n\nexport { aggregateEvents,
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport type { SearchPluginConfig } from './types.js'\n\nimport { searchIndexCache } from './cache.js'\nimport { createSearchEventsCollection } from './collections/SearchEvents.js'\nimport {\n createInspectHandler,\n createReindexHandler,\n createSearchHandler,\n createTrackHandler,\n} from './endpoints/handlers.js'\nimport { assertConfig, resolveAnalytics } from './options.js'\n\nexport { aggregateEvents, cleanSearchTerm } from './analytics.js'\nexport { SearchIndexCache, searchIndexCache } from './cache.js'\nexport { decodeEntities } from './decodeEntities.js'\nexport { hrefFor, projectDocs } from './project.js'\nexport { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs } from './rank.js'\nexport { createSearchService } from './resolve.js'\nexport { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.js'\nexport type { ShownResult, TrackPayload } from './track.js'\nexport type * from './types.js'\n\n/**\n * Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.\n *\n * Layered on top of plugin-search rather than replacing it: that plugin already keeps a `search`\n * collection in sync through afterChange/afterDelete hooks, and sync is the part of an index\n * implementation that rots. This owns the read side — projection, caching, fuzzy ranking,\n * grouping — plus the operational surface an editor needs.\n *\n * Install it AFTER searchPlugin in the plugins array, since it reads the collection that one\n * creates.\n */\nexport const searchPlugin =\n (pluginOptions: SearchPluginConfig) =>\n (config: Config): Config => {\n if (pluginOptions.disabled) {\n return config\n }\n\n assertConfig(pluginOptions)\n\n const analytics = resolveAnalytics(pluginOptions.analytics)\n const prefix = pluginOptions.routePrefix ?? '/site-search'\n const requireAdmin = pluginOptions.requireAdminForOperations ?? true\n\n searchIndexCache.configure(pluginOptions.cacheTTL ?? 60_000)\n\n if (analytics.enabled) {\n config.collections = [\n ...(config.collections || []),\n createSearchEventsCollection({ slug: analytics.collectionSlug }),\n ]\n }\n\n config.endpoints = [\n ...(config.endpoints || []),\n {\n handler: createSearchHandler({ cache: searchIndexCache, config: pluginOptions }),\n method: 'get',\n path: prefix,\n },\n {\n handler: createReindexHandler({\n cache: searchIndexCache,\n config: pluginOptions,\n requireAdmin,\n }),\n method: 'post',\n path: `${prefix}/reindex`,\n },\n {\n handler: createInspectHandler({\n cache: searchIndexCache,\n config: pluginOptions,\n requireAdmin,\n }),\n method: 'get',\n path: `${prefix}/inspect`,\n },\n ...(analytics.enabled\n ? [\n {\n handler: createTrackHandler({ config: pluginOptions }),\n method: 'post' as const,\n path: `${prefix}/track`,\n },\n ]\n : []),\n ]\n\n return config\n }\n"],"names":["searchIndexCache","createSearchEventsCollection","createInspectHandler","createReindexHandler","createSearchHandler","createTrackHandler","assertConfig","resolveAnalytics","aggregateEvents","cleanSearchTerm","SearchIndexCache","decodeEntities","hrefFor","projectDocs","DEFAULT_FIELDS","DEFAULT_FUZZY","groupResults","presetResults","rankDocs","createSearchService","deviceOf","isBot","parseTrackPayload","recordSearchEvent","searchPlugin","pluginOptions","config","disabled","analytics","prefix","routePrefix","requireAdmin","requireAdminForOperations","configure","cacheTTL","enabled","collections","slug","collectionSlug","endpoints","handler","cache","method","path"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,aAAY;AAC7C,SAASC,4BAA4B,QAAQ,gCAA+B;AAC5E,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,mBAAmB,EACnBC,kBAAkB,QACb,0BAAyB;AAChC,SAASC,YAAY,EAAEC,gBAAgB,QAAQ,eAAc;AAE7D,SAASC,eAAe,EAAEC,eAAe,QAAQ,iBAAgB;AACjE,SAASC,gBAAgB,EAAEV,gBAAgB,QAAQ,aAAY;AAC/D,SAASW,cAAc,QAAQ,sBAAqB;AACpD,SAASC,OAAO,EAAEC,WAAW,QAAQ,eAAc;AACnD,SAASC,cAAc,EAAEC,aAAa,EAAEC,YAAY,EAAEC,aAAa,EAAEC,QAAQ,QAAQ,YAAW;AAChG,SAASC,mBAAmB,QAAQ,eAAc;AAClD,SAASC,QAA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
2
|
-
export declare const DEFAULT_ANALYTICS:
|
|
1
|
+
import type { ResolvedAnalytics, SearchPluginConfig } from './types.js';
|
|
2
|
+
export declare const DEFAULT_ANALYTICS: ResolvedAnalytics;
|
|
3
3
|
/** Normalise the `analytics` option, which accepts a boolean shorthand. */
|
|
4
|
-
export declare const resolveAnalytics: (analytics: SearchPluginConfig["analytics"]) =>
|
|
4
|
+
export declare const resolveAnalytics: (analytics: SearchPluginConfig["analytics"]) => ResolvedAnalytics;
|
|
5
5
|
/**
|
|
6
6
|
* Fail loudly on a misconfiguration rather than silently returning nothing.
|
|
7
7
|
*
|
package/dist/options.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
export const DEFAULT_ANALYTICS = {
|
|
2
2
|
collectionSlug: 'search-events',
|
|
3
3
|
enabled: false,
|
|
4
|
-
|
|
5
|
-
//
|
|
6
|
-
|
|
4
|
+
isEnabled: ()=>true,
|
|
5
|
+
// Long enough to compare a full year, short enough that the log stays bounded and the
|
|
6
|
+
// retention question is answered up front rather than by accumulation.
|
|
7
|
+
retentionDays: 400
|
|
7
8
|
};
|
|
8
9
|
/** Normalise the `analytics` option, which accepts a boolean shorthand. */ export const resolveAnalytics = (analytics)=>{
|
|
9
10
|
if (analytics === undefined) {
|
|
@@ -18,7 +19,9 @@ export const DEFAULT_ANALYTICS = {
|
|
|
18
19
|
return {
|
|
19
20
|
collectionSlug: analytics.collectionSlug ?? DEFAULT_ANALYTICS.collectionSlug,
|
|
20
21
|
enabled: analytics.enabled ?? true,
|
|
21
|
-
|
|
22
|
+
isEnabled: analytics.isEnabled ?? DEFAULT_ANALYTICS.isEnabled,
|
|
23
|
+
retentionDays: analytics.retentionDays ?? DEFAULT_ANALYTICS.retentionDays,
|
|
24
|
+
visitorCookie: analytics.visitorCookie
|
|
22
25
|
};
|
|
23
26
|
};
|
|
24
27
|
/**
|
package/dist/options.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/options.ts"],"sourcesContent":["import type {
|
|
1
|
+
{"version":3,"sources":["../src/options.ts"],"sourcesContent":["import type { ResolvedAnalytics, SearchPluginConfig } from './types.js'\n\nexport const DEFAULT_ANALYTICS: ResolvedAnalytics = {\n collectionSlug: 'search-events',\n enabled: false,\n isEnabled: () => true,\n // Long enough to compare a full year, short enough that the log stays bounded and the\n // retention question is answered up front rather than by accumulation.\n retentionDays: 400,\n}\n\n/** Normalise the `analytics` option, which accepts a boolean shorthand. */\nexport const resolveAnalytics = (\n analytics: SearchPluginConfig['analytics'],\n): ResolvedAnalytics => {\n if (analytics === undefined) {\n return DEFAULT_ANALYTICS\n }\n if (typeof analytics === 'boolean') {\n return { ...DEFAULT_ANALYTICS, enabled: analytics }\n }\n return {\n collectionSlug: analytics.collectionSlug ?? DEFAULT_ANALYTICS.collectionSlug,\n enabled: analytics.enabled ?? true,\n isEnabled: analytics.isEnabled ?? DEFAULT_ANALYTICS.isEnabled,\n retentionDays: analytics.retentionDays ?? DEFAULT_ANALYTICS.retentionDays,\n visitorCookie: analytics.visitorCookie,\n }\n}\n\n/**\n * Fail loudly on a misconfiguration rather than silently returning nothing.\n *\n * A collection pointing at a group that does not exist is the most likely mistake, and its symptom\n * — results vanishing — is indistinguishable from an empty index.\n */\nexport function assertConfig(config: SearchPluginConfig): void {\n const groups = new Set(config.groups.map((group) => group.slug))\n\n for (const entry of config.collections) {\n if (!groups.has(entry.group)) {\n throw new Error(\n `search-plugin: collection \"${String(entry.slug)}\" is assigned to group \"${entry.group}\", which is not configured.`,\n )\n }\n }\n\n const duplicateGroup = config.groups.find(\n (group, index) => config.groups.findIndex((other) => other.slug === group.slug) !== index,\n )\n if (duplicateGroup) {\n throw new Error(`search-plugin: duplicate group \"${duplicateGroup.slug}\".`)\n }\n}\n"],"names":["DEFAULT_ANALYTICS","collectionSlug","enabled","isEnabled","retentionDays","resolveAnalytics","analytics","undefined","visitorCookie","assertConfig","config","groups","Set","map","group","slug","entry","collections","has","Error","String","duplicateGroup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}
|
package/dist/track.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { Payload } from 'payload';
|
|
2
|
+
export type ShownResult = {
|
|
3
|
+
group: string;
|
|
4
|
+
href: string;
|
|
5
|
+
title: string;
|
|
6
|
+
};
|
|
7
|
+
export type TrackPayload = {
|
|
8
|
+
click?: {
|
|
9
|
+
position: number;
|
|
10
|
+
} & ShownResult;
|
|
11
|
+
pagePath: string;
|
|
12
|
+
query: string;
|
|
13
|
+
referrer?: string;
|
|
14
|
+
results: ({
|
|
15
|
+
position: number;
|
|
16
|
+
} & ShownResult)[];
|
|
17
|
+
resultCount: number;
|
|
18
|
+
searchId: string;
|
|
19
|
+
source: string;
|
|
20
|
+
utm?: Record<string, string>;
|
|
21
|
+
};
|
|
22
|
+
type Device = 'desktop' | 'mobile' | 'tablet';
|
|
23
|
+
/** Validate and bound an untrusted beacon body. Null means reject. */
|
|
24
|
+
export declare function parseTrackPayload(body: unknown): null | TrackPayload;
|
|
25
|
+
export declare function deviceOf(userAgent: string): Device;
|
|
26
|
+
export declare function isBot(userAgent: string): boolean;
|
|
27
|
+
/**
|
|
28
|
+
* Upsert one row per searchId: the search creates it, later beacons for the same search append
|
|
29
|
+
* their click. Prunes past retention on write (no scheduled job to assume).
|
|
30
|
+
*/
|
|
31
|
+
export declare function recordSearchEvent({ collectionSlug, device, event, payload, retentionDays, visitorId, }: {
|
|
32
|
+
collectionSlug: string;
|
|
33
|
+
device: Device;
|
|
34
|
+
event: TrackPayload;
|
|
35
|
+
payload: Payload;
|
|
36
|
+
retentionDays: number;
|
|
37
|
+
visitorId?: string;
|
|
38
|
+
}): Promise<void>;
|
|
39
|
+
export {};
|
package/dist/track.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { cleanSearchTerm } from './analytics.js';
|
|
2
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
3
|
+
const str = (v, max)=>typeof v === 'string' ? v.slice(0, max) : '';
|
|
4
|
+
const isObj = (v)=>typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
5
|
+
const shown = (v, position)=>{
|
|
6
|
+
if (!isObj(v)) {
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
return {
|
|
10
|
+
group: str(v.group, 200),
|
|
11
|
+
href: str(v.href, 2000).split(/[?#]/)[0].slice(0, 200),
|
|
12
|
+
position: typeof v.position === 'number' && Number.isFinite(v.position) ? v.position : position,
|
|
13
|
+
title: str(v.title, 200)
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
/** Validate and bound an untrusted beacon body. Null means reject. */ export function parseTrackPayload(body) {
|
|
17
|
+
if (!isObj(body)) {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
const searchId = str(body.searchId, 64);
|
|
21
|
+
if (!UUID.test(searchId)) {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
const query = cleanSearchTerm(str(body.query, 1000));
|
|
25
|
+
if (!query) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
if (typeof body.resultCount !== 'number' || !Number.isFinite(body.resultCount) || body.resultCount < 0) {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
const results = (Array.isArray(body.results) ? body.results.slice(0, 20) : []).map((r, i)=>shown(r, i)).filter((r)=>r !== null);
|
|
32
|
+
const utm = {};
|
|
33
|
+
if (isObj(body.utm)) {
|
|
34
|
+
for (const [k, v] of Object.entries(body.utm)){
|
|
35
|
+
if (k.startsWith('utm_') && typeof v === 'string') {
|
|
36
|
+
utm[k.slice(0, 50)] = v.slice(0, 100);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
let referrer = '';
|
|
41
|
+
try {
|
|
42
|
+
referrer = new URL(str(body.referrer, 2000)).hostname;
|
|
43
|
+
} catch {
|
|
44
|
+
// unparseable: dropped
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
click: shown(body.click, 0) ?? undefined,
|
|
48
|
+
pagePath: str(body.pagePath, 2000).split(/[?#]/)[0].slice(0, 300),
|
|
49
|
+
query,
|
|
50
|
+
referrer: referrer || undefined,
|
|
51
|
+
resultCount: body.resultCount,
|
|
52
|
+
results,
|
|
53
|
+
searchId,
|
|
54
|
+
source: str(body.source, 32),
|
|
55
|
+
utm: Object.keys(utm).length ? utm : undefined
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export function deviceOf(userAgent) {
|
|
59
|
+
if (/ipad|tablet/i.test(userAgent) || /android/i.test(userAgent) && !/mobile/i.test(userAgent)) {
|
|
60
|
+
return 'tablet';
|
|
61
|
+
}
|
|
62
|
+
return /mobi|iphone|ipod|android/i.test(userAgent) ? 'mobile' : 'desktop';
|
|
63
|
+
}
|
|
64
|
+
export function isBot(userAgent) {
|
|
65
|
+
return /bot|crawl|spider|slurp|headless|lighthouse|preview|curl|wget/i.test(userAgent);
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Upsert one row per searchId: the search creates it, later beacons for the same search append
|
|
69
|
+
* their click. Prunes past retention on write (no scheduled job to assume).
|
|
70
|
+
*/ export async function recordSearchEvent({ collectionSlug, device, event, payload, retentionDays, visitorId }) {
|
|
71
|
+
const collection = collectionSlug;
|
|
72
|
+
const click = event.click && {
|
|
73
|
+
...event.click,
|
|
74
|
+
at: new Date().toISOString()
|
|
75
|
+
};
|
|
76
|
+
const findRow = async ()=>(await payload.find({
|
|
77
|
+
collection,
|
|
78
|
+
depth: 0,
|
|
79
|
+
limit: 1,
|
|
80
|
+
overrideAccess: true,
|
|
81
|
+
where: {
|
|
82
|
+
searchId: {
|
|
83
|
+
equals: event.searchId
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
})).docs[0];
|
|
87
|
+
const appendClick = async (row)=>{
|
|
88
|
+
const prior = Array.isArray(row?.clicks) ? row.clicks : [];
|
|
89
|
+
if (!row || !click || prior.length >= 20) {
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
await payload.update({
|
|
93
|
+
id: row.id,
|
|
94
|
+
collection,
|
|
95
|
+
data: {
|
|
96
|
+
clicks: [
|
|
97
|
+
...prior,
|
|
98
|
+
click
|
|
99
|
+
]
|
|
100
|
+
},
|
|
101
|
+
overrideAccess: true
|
|
102
|
+
});
|
|
103
|
+
};
|
|
104
|
+
const existing = await findRow();
|
|
105
|
+
if (existing) {
|
|
106
|
+
await appendClick(existing);
|
|
107
|
+
} else {
|
|
108
|
+
try {
|
|
109
|
+
await payload.create({
|
|
110
|
+
collection,
|
|
111
|
+
data: {
|
|
112
|
+
clicks: click ? [
|
|
113
|
+
click
|
|
114
|
+
] : [],
|
|
115
|
+
device,
|
|
116
|
+
pagePath: event.pagePath,
|
|
117
|
+
query: event.query,
|
|
118
|
+
referrer: event.referrer,
|
|
119
|
+
resultCount: event.resultCount,
|
|
120
|
+
results: event.results,
|
|
121
|
+
searchId: event.searchId,
|
|
122
|
+
source: event.source,
|
|
123
|
+
utm: event.utm,
|
|
124
|
+
visitorId
|
|
125
|
+
},
|
|
126
|
+
overrideAccess: true
|
|
127
|
+
});
|
|
128
|
+
} catch (error) {
|
|
129
|
+
// Payload wraps pg 23505 in a ValidationError with no code, so don't sniff the error: if the
|
|
130
|
+
// row now exists we lost a race, otherwise the failure is real.
|
|
131
|
+
const raced = await findRow();
|
|
132
|
+
if (!raced) {
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
await appendClick(raced);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (retentionDays > 0) {
|
|
139
|
+
await payload.delete({
|
|
140
|
+
collection,
|
|
141
|
+
overrideAccess: true,
|
|
142
|
+
where: {
|
|
143
|
+
createdAt: {
|
|
144
|
+
less_than: new Date(Date.now() - retentionDays * 86_400_000).toISOString()
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
//# sourceMappingURL=track.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/track.ts"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport { cleanSearchTerm } from './analytics.js'\n\nexport type ShownResult = { group: string; href: string; title: string }\nexport type TrackPayload = {\n click?: { position: number } & ShownResult\n pagePath: string\n query: string\n referrer?: string\n results: ({ position: number } & ShownResult)[]\n resultCount: number\n searchId: string\n source: string\n utm?: Record<string, string>\n}\ntype Device = 'desktop' | 'mobile' | 'tablet'\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\nconst str = (v: unknown, max: number): string => (typeof v === 'string' ? v.slice(0, max) : '')\nconst isObj = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v)\n\nconst shown = (v: unknown, position: number): ({ position: number } & ShownResult) | null => {\n if (!isObj(v)) {\n return null\n }\n return {\n group: str(v.group, 200),\n href: str(v.href, 2000).split(/[?#]/)[0].slice(0, 200),\n position: typeof v.position === 'number' && Number.isFinite(v.position) ? v.position : position,\n title: str(v.title, 200),\n }\n}\n\n/** Validate and bound an untrusted beacon body. Null means reject. */\nexport function parseTrackPayload(body: unknown): null | TrackPayload {\n if (!isObj(body)) {\n return null\n }\n const searchId = str(body.searchId, 64)\n if (!UUID.test(searchId)) {\n return null\n }\n const query = cleanSearchTerm(str(body.query, 1000))\n if (!query) {\n return null\n }\n if (typeof body.resultCount !== 'number' || !Number.isFinite(body.resultCount) || body.resultCount < 0) {\n return null\n }\n\n const results = (Array.isArray(body.results) ? body.results.slice(0, 20) : [])\n .map((r, i) => shown(r, i))\n .filter((r): r is NonNullable<typeof r> => r !== null)\n\n const utm: Record<string, string> = {}\n if (isObj(body.utm)) {\n for (const [k, v] of Object.entries(body.utm)) {\n if (k.startsWith('utm_') && typeof v === 'string') {\n utm[k.slice(0, 50)] = v.slice(0, 100)\n }\n }\n }\n\n let referrer = ''\n try {\n referrer = new URL(str(body.referrer, 2000)).hostname\n } catch {\n // unparseable: dropped\n }\n\n return {\n click: shown(body.click, 0) ?? undefined,\n pagePath: str(body.pagePath, 2000).split(/[?#]/)[0].slice(0, 300),\n query,\n referrer: referrer || undefined,\n resultCount: body.resultCount,\n results,\n searchId,\n source: str(body.source, 32),\n utm: Object.keys(utm).length ? utm : undefined,\n }\n}\n\nexport function deviceOf(userAgent: string): Device {\n if (/ipad|tablet/i.test(userAgent) || (/android/i.test(userAgent) && !/mobile/i.test(userAgent))) {\n return 'tablet'\n }\n return /mobi|iphone|ipod|android/i.test(userAgent) ? 'mobile' : 'desktop'\n}\n\nexport function isBot(userAgent: string): boolean {\n return /bot|crawl|spider|slurp|headless|lighthouse|preview|curl|wget/i.test(userAgent)\n}\n\n/**\n * Upsert one row per searchId: the search creates it, later beacons for the same search append\n * their click. Prunes past retention on write (no scheduled job to assume).\n */\nexport async function recordSearchEvent({\n collectionSlug,\n device,\n event,\n payload,\n retentionDays,\n visitorId,\n}: {\n collectionSlug: string\n device: Device\n event: TrackPayload\n payload: Payload\n retentionDays: number\n visitorId?: string\n}): Promise<void> {\n const collection = collectionSlug as never\n const click = event.click && { ...event.click, at: new Date().toISOString() }\n\n const findRow = async () =>\n (\n await payload.find({\n collection,\n depth: 0,\n limit: 1,\n overrideAccess: true,\n where: { searchId: { equals: event.searchId } },\n })\n ).docs[0] as undefined | { clicks?: unknown; id: number | string }\n\n const appendClick = async (row: undefined | { clicks?: unknown; id: number | string }) => {\n const prior = Array.isArray(row?.clicks) ? row.clicks : []\n if (!row || !click || prior.length >= 20) {\n return\n }\n await payload.update({\n id: row.id,\n collection,\n data: { clicks: [...prior, click] } as never,\n overrideAccess: true,\n })\n }\n\n const existing = await findRow()\n if (existing) {\n await appendClick(existing)\n } else {\n try {\n await payload.create({\n collection,\n data: {\n clicks: click ? [click] : [],\n device,\n pagePath: event.pagePath,\n query: event.query,\n referrer: event.referrer,\n resultCount: event.resultCount,\n results: event.results,\n searchId: event.searchId,\n source: event.source,\n utm: event.utm,\n visitorId,\n } as never,\n overrideAccess: true,\n })\n } catch (error) {\n // Payload wraps pg 23505 in a ValidationError with no code, so don't sniff the error: if the\n // row now exists we lost a race, otherwise the failure is real.\n const raced = await findRow()\n if (!raced) {\n throw error\n }\n await appendClick(raced)\n }\n }\n\n if (retentionDays > 0) {\n await payload.delete({\n collection,\n overrideAccess: true,\n where: {\n createdAt: { less_than: new Date(Date.now() - retentionDays * 86_400_000).toISOString() },\n },\n })\n }\n}\n"],"names":["cleanSearchTerm","UUID","str","v","max","slice","isObj","Array","isArray","shown","position","group","href","split","Number","isFinite","title","parseTrackPayload","body","searchId","test","query","resultCount","results","map","r","i","filter","utm","k","Object","entries","startsWith","referrer","URL","hostname","click","undefined","pagePath","source","keys","length","deviceOf","userAgent","isBot","recordSearchEvent","collectionSlug","device","event","payload","retentionDays","visitorId","collection","at","Date","toISOString","findRow","find","depth","limit","overrideAccess","where","equals","docs","appendClick","row","prior","clicks","update","id","data","existing","create","error","raced","delete","createdAt","less_than","now"],"mappings":"AAEA,SAASA,eAAe,QAAQ,iBAAgB;AAgBhD,MAAMC,OAAO;AACb,MAAMC,MAAM,CAACC,GAAYC,MAAyB,OAAOD,MAAM,WAAWA,EAAEE,KAAK,CAAC,GAAGD,OAAO;AAC5F,MAAME,QAAQ,CAACH,IACb,OAAOA,MAAM,YAAYA,MAAM,QAAQ,CAACI,MAAMC,OAAO,CAACL;AAExD,MAAMM,QAAQ,CAACN,GAAYO;IACzB,IAAI,CAACJ,MAAMH,IAAI;QACb,OAAO;IACT;IACA,OAAO;QACLQ,OAAOT,IAAIC,EAAEQ,KAAK,EAAE;QACpBC,MAAMV,IAAIC,EAAES,IAAI,EAAE,MAAMC,KAAK,CAAC,OAAO,CAAC,EAAE,CAACR,KAAK,CAAC,GAAG;QAClDK,UAAU,OAAOP,EAAEO,QAAQ,KAAK,YAAYI,OAA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AAI,CAACF,OAAO,CAAC7B,SAAS8B,MAAMzB,MAAM,IAAI,IAAI;YACxC;QACF;QACA,MAAMQ,QAAQmB,MAAM,CAAC;YACnBC,IAAIJ,IAAII,EAAE;YACVjB;YACAkB,MAAM;gBAAEH,QAAQ;uBAAID;oBAAO9B;iBAAM;YAAC;YAClCwB,gBAAgB;QAClB;IACF;IAEA,MAAMW,WAAW,MAAMf;IACvB,IAAIe,UAAU;QACZ,MAAMP,YAAYO;IACpB,OAAO;QACL,IAAI;YACF,MAAMtB,QAAQuB,MAAM,CAAC;gBACnBpB;gBACAkB,MAAM;oBACJH,QAAQ/B,QAAQ;wBAACA;qBAAM,GAAG,EAAE;oBAC5BW;oBACAT,UAAUU,MAAMV,QAAQ;oBACxBjB,OAAO2B,MAAM3B,KAAK;oBAClBY,UAAUe,MAAMf,QAAQ;oBACxBX,aAAa0B,MAAM1B,WAAW;oBAC9BC,SAASyB,MAAMzB,OAAO;oBACtBJ,UAAU6B,MAAM7B,QAAQ;oBACxBoB,QAAQS,MAAMT,MAAM;oBACpBX,KAAKoB,MAAMpB,GAAG;oBACduB;gBACF;gBACAS,gBAAgB;YAClB;QACF,EAAE,OAAOa,OAAO;YACd,6FAA6F;YAC7F,gEAAgE;YAChE,MAAMC,QAAQ,MAAMlB;YACpB,IAAI,CAACkB,OAAO;gBACV,MAAMD;YACR;YACA,MAAMT,YAAYU;QACpB;IACF;IAEA,IAAIxB,gBAAgB,GAAG;QACrB,MAAMD,QAAQ0B,MAAM,CAAC;YACnBvB;YACAQ,gBAAgB;YAChBC,OAAO;gBACLe,WAAW;oBAAEC,WAAW,IAAIvB,KAAKA,KAAKwB,GAAG,KAAK5B,gBAAgB,YAAYK,WAAW;gBAAG;YAC1F;QACF;IACF;AACF"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Fire-and-forget search event; survives page unload and never throws. */ export function trackSearchEvent(payload, endpoint = '/api/site-search/track') {
|
|
2
|
+
try {
|
|
3
|
+
const body = JSON.stringify(payload);
|
|
4
|
+
if (navigator.sendBeacon?.(endpoint, new Blob([
|
|
5
|
+
body
|
|
6
|
+
], {
|
|
7
|
+
type: 'application/json'
|
|
8
|
+
}))) {
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
void fetch(endpoint, {
|
|
12
|
+
body,
|
|
13
|
+
headers: {
|
|
14
|
+
'Content-Type': 'application/json'
|
|
15
|
+
},
|
|
16
|
+
keepalive: true,
|
|
17
|
+
method: 'POST'
|
|
18
|
+
}).catch(()=>{});
|
|
19
|
+
} catch {
|
|
20
|
+
// analytics must never break the page
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
//# sourceMappingURL=trackClient.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/trackClient.ts"],"sourcesContent":["import type { TrackPayload } from './track.js'\n\n/** Fire-and-forget search event; survives page unload and never throws. */\nexport function trackSearchEvent(payload: TrackPayload, endpoint = '/api/site-search/track'): void {\n try {\n const body = JSON.stringify(payload)\n if (navigator.sendBeacon?.(endpoint, new Blob([body], { type: 'application/json' }))) {\n return\n }\n void fetch(endpoint, {\n body,\n headers: { 'Content-Type': 'application/json' },\n keepalive: true,\n method: 'POST',\n }).catch(() => {})\n } catch {\n // analytics must never break the page\n }\n}\n"],"names":["trackSearchEvent","payload","endpoint","body","JSON","stringify","navigator","sendBeacon","Blob","type","fetch","headers","keepalive","method","catch"],"mappings":"AAEA,yEAAyE,GACzE,OAAO,SAASA,iBAAiBC,OAAqB,EAAEC,WAAW,wBAAwB;IACzF,IAAI;QACF,MAAMC,OAAOC,KAAKC,SAAS,CAACJ;QAC5B,IAAIK,UAAUC,UAAU,GAAGL,UAAU,IAAIM,KAAK;YAACL;SAAK,EAAE;YAAEM,MAAM;QAAmB,KAAK;YACpF;QACF;QACA,KAAKC,MAAMR,UAAU;YACnBC;YACAQ,SAAS;gBAAE,gBAAgB;YAAmB;YAC9CC,WAAW;YACXC,QAAQ;QACV,GAAGC,KAAK,CAAC,KAAO;IAClB,EAAE,OAAM;IACN,sCAAsC;IACxC;AACF"}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { CollectionSlug } from 'payload';
|
|
1
|
+
import type { CollectionSlug, PayloadRequest } from 'payload';
|
|
2
2
|
/**
|
|
3
3
|
* A collection that should appear in site search, and how its results present.
|
|
4
4
|
*
|
|
@@ -58,12 +58,20 @@ export type AnalyticsOptions = {
|
|
|
58
58
|
/** Collection slug for stored events. */
|
|
59
59
|
collectionSlug?: string;
|
|
60
60
|
enabled?: boolean;
|
|
61
|
+
/** Per-request gate, e.g. a consent check. Return false to record nothing. Default: always true. */
|
|
62
|
+
isEnabled?: (req: PayloadRequest) => boolean | Promise<boolean>;
|
|
61
63
|
/**
|
|
62
64
|
* Days to keep events. Events older than this are pruned on write rather than accumulating an
|
|
63
65
|
* unbounded log.
|
|
64
66
|
*/
|
|
65
67
|
retentionDays?: number;
|
|
68
|
+
/** Name of the cookie holding a visitor ID. Unset means visitor IDs are never read. */
|
|
69
|
+
visitorCookie?: string;
|
|
66
70
|
};
|
|
71
|
+
/** `AnalyticsOptions` after defaults: `isEnabled` is always callable, `visitorCookie` stays optional. */
|
|
72
|
+
export type ResolvedAnalytics = {
|
|
73
|
+
isEnabled: NonNullable<AnalyticsOptions['isEnabled']>;
|
|
74
|
+
} & Omit<Required<AnalyticsOptions>, 'isEnabled' | 'visitorCookie'> & Pick<AnalyticsOptions, 'visitorCookie'>;
|
|
67
75
|
export type SearchPluginConfig = {
|
|
68
76
|
analytics?: AnalyticsOptions | boolean;
|
|
69
77
|
/** Milliseconds to hold the projected index in memory. */
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { CollectionSlug } from 'payload'\n\n/**\n * A collection that should appear in site search, and how its results present.\n *\n * Everything a host project would otherwise hardcode lives here: which group a collection lands\n * in, how its URLs are built, how strongly it ranks, and which documents are held back.\n */\nexport type SearchableCollection = {\n /** Documents whose slug appears here are never returned. */\n excludeSlugs?: string[]\n /** Group key this collection's results are filed under. Must match a configured group. */\n group: string\n /** Opaque icon token passed through to the consumer's own icon map. */\n icon?: string\n /**\n * URL prefix for a result, without a trailing slash. Use an empty string for collections served\n * at the site root — it is deliberately distinct from \"unset\".\n */\n path: string\n slug: CollectionSlug\n /**\n * Ranking multiplier relative to other collections. 1 is neutral; raise it to float a\n * collection's matches above equally-good matches elsewhere.\n */\n weight?: number\n}\n\n/** A presentation group that results are bucketed into. */\nexport type SearchGroup = {\n /** Human label. The plugin never renders it, but ships it so consumers stay consistent. */\n label: string\n /** Maximum results returned for this group. Omit for no cap. */\n limit?: number\n /** Sort position in the returned group list. Lower comes first. */\n order?: number\n /** Whether this group appears in the empty-query preset list. */\n showWhenEmpty?: boolean\n slug: string\n}\n\n/**\n * A field on the indexed document to match against, with a relative weight.\n *\n * Weights are what stop the \"search for tuni, get unrelated results\" class of complaint: a title\n * hit and an incidental description hit stop being treated identically.\n */\nexport type SearchField = {\n name: string\n weight?: number\n}\n\nexport type FuzzyOptions = {\n /** Character distance a match may drift from the expected location. */\n distance?: number\n /** Shortest run of characters that counts as a match. Guards against 1-2 letter noise. */\n minMatchCharLength?: number\n /** 0 demands a perfect match, 1 matches anything. */\n threshold?: number\n}\n\nexport type AnalyticsOptions = {\n /** Collection slug for stored events. */\n collectionSlug?: string\n enabled?: boolean\n /**\n * Days to keep events. Events older than this are pruned on write rather than accumulating an\n * unbounded log.\n */\n retentionDays?: number\n}\n\nexport type SearchPluginConfig = {\n analytics?: AnalyticsOptions | boolean\n /** Milliseconds to hold the projected index in memory. */\n cacheTTL?: number\n collections: SearchableCollection[]\n /**\n * Decode HTML entities in titles before returning them. Content migrated out of a CMS that\n * stored encoded markup will otherwise surface \"&\" as literal text wherever a result is\n * rendered as plain text.\n */\n decodeEntities?: boolean\n disabled?: boolean\n /** Fields matched against, with relative weights. */\n fields?: SearchField[]\n fuzzy?: FuzzyOptions\n groups: SearchGroup[]\n /** Restrict the reindex and inspect endpoints to admin users. */\n requireAdminForOperations?: boolean\n /** Base path for the plugin's endpoints. */\n routePrefix?: string\n}\n\n/** One document as held in the in-memory projection. */\nexport type IndexedDoc = {\n collection: string\n description?: string\n group: string\n icon?: string\n id: string\n path: string\n slug: string\n title: string\n weight: number\n}\n\nexport type SearchResult = {\n collection: string\n group: string\n href: string\n icon?: string\n id: string\n /** Fuse score, carried through so consumers can debug ranking. Lower is a better match. */\n score?: number\n title: string\n}\n\nexport type GroupedResults = Record<string, SearchResult[]>\n\n/** What the inspector reports, so \"is this searchable\" stops needing a code read. */\nexport type IndexReport = {\n builtAt: null | string\n collections: {\n excluded: number\n indexed: number\n slug: string\n }[]\n skipped: {\n id: string\n reason: string\n slug: string\n }[]\n total: number\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { CollectionSlug, PayloadRequest } from 'payload'\n\n/**\n * A collection that should appear in site search, and how its results present.\n *\n * Everything a host project would otherwise hardcode lives here: which group a collection lands\n * in, how its URLs are built, how strongly it ranks, and which documents are held back.\n */\nexport type SearchableCollection = {\n /** Documents whose slug appears here are never returned. */\n excludeSlugs?: string[]\n /** Group key this collection's results are filed under. Must match a configured group. */\n group: string\n /** Opaque icon token passed through to the consumer's own icon map. */\n icon?: string\n /**\n * URL prefix for a result, without a trailing slash. Use an empty string for collections served\n * at the site root — it is deliberately distinct from \"unset\".\n */\n path: string\n slug: CollectionSlug\n /**\n * Ranking multiplier relative to other collections. 1 is neutral; raise it to float a\n * collection's matches above equally-good matches elsewhere.\n */\n weight?: number\n}\n\n/** A presentation group that results are bucketed into. */\nexport type SearchGroup = {\n /** Human label. The plugin never renders it, but ships it so consumers stay consistent. */\n label: string\n /** Maximum results returned for this group. Omit for no cap. */\n limit?: number\n /** Sort position in the returned group list. Lower comes first. */\n order?: number\n /** Whether this group appears in the empty-query preset list. */\n showWhenEmpty?: boolean\n slug: string\n}\n\n/**\n * A field on the indexed document to match against, with a relative weight.\n *\n * Weights are what stop the \"search for tuni, get unrelated results\" class of complaint: a title\n * hit and an incidental description hit stop being treated identically.\n */\nexport type SearchField = {\n name: string\n weight?: number\n}\n\nexport type FuzzyOptions = {\n /** Character distance a match may drift from the expected location. */\n distance?: number\n /** Shortest run of characters that counts as a match. Guards against 1-2 letter noise. */\n minMatchCharLength?: number\n /** 0 demands a perfect match, 1 matches anything. */\n threshold?: number\n}\n\nexport type AnalyticsOptions = {\n /** Collection slug for stored events. */\n collectionSlug?: string\n enabled?: boolean\n /** Per-request gate, e.g. a consent check. Return false to record nothing. Default: always true. */\n isEnabled?: (req: PayloadRequest) => boolean | Promise<boolean>\n /**\n * Days to keep events. Events older than this are pruned on write rather than accumulating an\n * unbounded log.\n */\n retentionDays?: number\n /** Name of the cookie holding a visitor ID. Unset means visitor IDs are never read. */\n visitorCookie?: string\n}\n\n/** `AnalyticsOptions` after defaults: `isEnabled` is always callable, `visitorCookie` stays optional. */\nexport type ResolvedAnalytics = {\n isEnabled: NonNullable<AnalyticsOptions['isEnabled']>\n} & Omit<Required<AnalyticsOptions>, 'isEnabled' | 'visitorCookie'> &\n Pick<AnalyticsOptions, 'visitorCookie'>\n\nexport type SearchPluginConfig = {\n analytics?: AnalyticsOptions | boolean\n /** Milliseconds to hold the projected index in memory. */\n cacheTTL?: number\n collections: SearchableCollection[]\n /**\n * Decode HTML entities in titles before returning them. Content migrated out of a CMS that\n * stored encoded markup will otherwise surface \"&\" as literal text wherever a result is\n * rendered as plain text.\n */\n decodeEntities?: boolean\n disabled?: boolean\n /** Fields matched against, with relative weights. */\n fields?: SearchField[]\n fuzzy?: FuzzyOptions\n groups: SearchGroup[]\n /** Restrict the reindex and inspect endpoints to admin users. */\n requireAdminForOperations?: boolean\n /** Base path for the plugin's endpoints. */\n routePrefix?: string\n}\n\n/** One document as held in the in-memory projection. */\nexport type IndexedDoc = {\n collection: string\n description?: string\n group: string\n icon?: string\n id: string\n path: string\n slug: string\n title: string\n weight: number\n}\n\nexport type SearchResult = {\n collection: string\n group: string\n href: string\n icon?: string\n id: string\n /** Fuse score, carried through so consumers can debug ranking. Lower is a better match. */\n score?: number\n title: string\n}\n\nexport type GroupedResults = Record<string, SearchResult[]>\n\n/** What the inspector reports, so \"is this searchable\" stops needing a code read. */\nexport type IndexReport = {\n builtAt: null | string\n collections: {\n excluded: number\n indexed: number\n slug: string\n }[]\n skipped: {\n id: string\n reason: string\n slug: string\n }[]\n total: number\n}\n"],"names":[],"mappings":"AAkIA,mFAAmF,GACnF,WAaC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foundrykit/search-plugin",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "A plugin for Payload CMS that provides a cached, grouped and ranked site search over the plugin-search index, with fuzzy matching, editor-controlled relevance and search analytics.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|