@foundrykit/search-plugin 0.3.0 → 0.4.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 CHANGED
@@ -79,6 +79,7 @@ export default buildConfig({
79
79
  | Method | Path | Purpose |
80
80
  | ------ | -------------------------- | ------------------------------------------------------------------- |
81
81
  | `GET` | `/api/site-search?q=` | Grouped, ranked results. Empty `q` returns the preset. |
82
+ | `GET` | `/api/site-search/results` | Flat, ranked, paginated: `?q=&collection=&page=&limit=`. |
82
83
  | `POST` | `/api/site-search/reindex` | Rebuild the projection now. Returns counts. |
83
84
  | `GET` | `/api/site-search/inspect` | What is indexed, and why anything missing was skipped. |
84
85
  | `POST` | `/api/site-search/track` | Record a settled search and its clicks. Only when analytics are on. |
@@ -99,9 +100,73 @@ you set `requireAdminForOperations: false`.
99
100
  | `analytics` | `false` | `true`, or `{ retentionDays, collectionSlug }`. |
100
101
  | `rateLimit` | `{ limit: 30, window: 60 }` | Per-IP limit on the public track endpoint. `false` disables it. |
101
102
  | `requireAdminForOperations` | `true` | Guard reindex and inspect. |
103
+ | `indexCollection` | `search` | plugin-search's collection slug, if you renamed it. |
102
104
  | `routePrefix` | `/site-search` | Base path for endpoints. |
103
105
  | `disabled` | `false` | Bypass the plugin entirely. |
104
106
 
107
+ ### Per-collection options
108
+
109
+ | Option | Notes |
110
+ | -------------- | ------------------------------------------------------------------------------------------- |
111
+ | `slug` | Required. The source collection. |
112
+ | `group` | Required. A configured group's slug. |
113
+ | `path` | Required. URL prefix; `''` for the site root. |
114
+ | `weight` | Ranking multiplier. Default `1`. |
115
+ | `icon` | Opaque token passed through to your icon map. |
116
+ | `excludeSlugs` | Slugs never returned. |
117
+ | `excludeField` | A checkbox on the source collection (e.g. `excludeFromSearch`) that hides a document. |
118
+ | `href` | `(row) => string` for URLs `path` + slug can't express. Gets the raw index row (see below). |
119
+
120
+ `excludeField` is read once per projection build, so it costs nothing per request. Toggling it saves
121
+ the document, plugin-search re-syncs the row, and the plugin drops its cache, so the change shows
122
+ straight away.
123
+
124
+ For nested URLs (`/destinations/asia/indonesia/bali`), add the URL to the index row with
125
+ plugin-search's `beforeSync` and a field in `searchOverrides`, then read it back:
126
+
127
+ ```ts
128
+ { slug: 'regions', group: 'destinations', path: '/regions', href: row => row.url as string }
129
+ ```
130
+
131
+ ### Results
132
+
133
+ Each result carries `id`, `docId` (the source document's ID), `collection`, `group`, `title`,
134
+ `description`, `href`, `icon`, `score` and `highlights`: the matched `[start, end)` ranges in
135
+ `title`, for bolding the match.
136
+
137
+ ### Flat results and filtered archives
138
+
139
+ `GET /api/site-search/results` (or `service.query()`) returns every match ranked and paginated,
140
+ ignoring group caps: `{ docs, totalDocs, page, totalPages, limit }`. A listing with its own filters
141
+ can use it for fuzzy, ranked matching instead of `title: { contains: q }`:
142
+
143
+ ```ts
144
+ const service = createSearchService({
145
+ cache: searchIndexCache,
146
+ config,
147
+ payload,
148
+ });
149
+ const { docs } = await service.query({
150
+ q,
151
+ collections: ['hotels'],
152
+ limit: 100,
153
+ });
154
+ const ids = docs.map(d => d.docId);
155
+ const hotels = await payload.find({
156
+ collection: 'hotels',
157
+ where: { and: [{ id: { in: ids } }, ...filters] },
158
+ pagination: false,
159
+ });
160
+ // Restore relevance order: hotels.docs.sort((a, b) => ids.indexOf(String(a.id)) - ids.indexOf(String(b.id)))
161
+ ```
162
+
163
+ ### Caching
164
+
165
+ The projection is cached in memory for `cacheTTL` and dropped whenever plugin-search writes the
166
+ index, so a published change shows up straight away (on the instance that handled the write; others
167
+ wait out the TTL). The cache is one per process: give every `createSearchService` call the same
168
+ config as the plugin, or they will overwrite each other's projection.
169
+
105
170
  ### A note on `minMatchCharLength`
106
171
 
107
172
  The default of `3` is deliberate. Two-character fragments match too much to be useful, and that is
@@ -6,6 +6,14 @@ export declare const createSearchHandler: ({ cache, config, }: {
6
6
  cache: SearchIndexCache;
7
7
  config: SearchPluginConfig;
8
8
  }) => PayloadHandler;
9
+ /**
10
+ * GET — flat, ranked, paginated results for `?q=&collection=&page=&limit=`. `collection` may
11
+ * repeat. For a full results page, where the grouped endpoint's caps get in the way.
12
+ */
13
+ export declare const createResultsHandler: ({ cache, config, }: {
14
+ cache: SearchIndexCache;
15
+ config: SearchPluginConfig;
16
+ }) => PayloadHandler;
9
17
  /** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */
10
18
  export declare const createReindexHandler: ({ cache, config, requireAdmin, }: {
11
19
  cache: SearchIndexCache;
@@ -20,6 +20,18 @@ const service = (req, cache, config)=>createSearchService({
20
20
  const results = await service(req, cache, config).search(query);
21
21
  return json(results);
22
22
  };
23
+ /**
24
+ * GET — flat, ranked, paginated results for `?q=&collection=&page=&limit=`. `collection` may
25
+ * repeat. For a full results page, where the grouped endpoint's caps get in the way.
26
+ */ export const createResultsHandler = ({ cache, config })=>async (req)=>{
27
+ const params = new URL(req.url ?? '', 'http://localhost').searchParams;
28
+ return json(await service(req, cache, config).query({
29
+ collections: params.getAll('collection'),
30
+ limit: Number(params.get('limit')) || undefined,
31
+ page: Number(params.get('page')) || undefined,
32
+ q: params.get('q') ?? ''
33
+ }));
34
+ };
23
35
  /** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */ export const createReindexHandler = ({ cache, config, requireAdmin })=>async (req)=>{
24
36
  if (requireAdmin && !req.user) {
25
37
  return forbidden();
@@ -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 { resolveAnalytics } from '../options.js';\nimport { createSearchService } from '../resolve.js';\nimport {\n deviceOf,\n isBot,\n parseTrackPayload,\n recordSearchEvent,\n} from '../track.js';\nimport type { SearchPluginConfig } from '../types.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 = (\n req: PayloadRequest,\n cache: SearchIndexCache,\n 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 =\n 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 req,\n retentionDays: analytics.retentionDays,\n visitorId,\n });\n } catch (error) {\n req.payload.logger.error({\n err: error,\n msg: 'search-plugin: failed to record search event',\n });\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":"AAGA,SAASA,gBAAgB,QAAQ,gBAAgB;AACjD,SAASC,mBAAmB,QAAQ,gBAAgB;AACpD,SACEC,QAAQ,EACRC,KAAK,EACLC,iBAAiB,EACjBC,iBAAiB,QACZ,cAAc;AAGrB,MAAMC,OAAO,CAACC,MAAeC,SAAS,GAAG,GACvC,IAAIC,SAASC,KAAKC,SAAS,CAACJ,OAAO;QACjCK,SAAS;YAAE,gBAAgB;QAAmB;QAC9CJ;IACF;AAEF,MAAMK,YAAY,IAAMP,KAAK;QAAEQ,OAAO;IAAgB,GAAG;AAEzD,MAAMC,UAAU,CACdC,KACAC,OACAC,SACGjB,oBAAoB;QAAEgB;QAAOC;QAAQC,SAASH,IAAIG,OAAO;IAAC;AAE/D,2HAA2H,GAC3H,OAAO,MAAMC,sBAC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iB;QACnD,IAAIT,IAAIc,IAAI,IAAI3B,MAAMwC,YAAY;YAChC,OAAOrC,KAAK;gBAAEoC,SAAS;YAAM;QAC/B;QAEA,MAAME,QAAQxC,kBAAkB,MAAMY,IAAIV,IAAI,KAAKuC,MAAM,IAAM;QAC/D,IAAI,CAACD,OAAO;YACV,OAAOtC,KAAK;gBAAEQ,OAAO;YAAkB,GAAG;QAC5C;QAEA,MAAMgC,aAAaP,UAAUQ,aAAa;QAC1C,MAAMC,YAAYF,aACd9B,IAAIJ,OAAO,CACRa,GAAG,CAAC,WACHwB,MAAM,KACPC,IAAIC,CAAAA,IAAKA,EAAEC,IAAI,GAAGH,KAAK,CAAC,MACxBI,KAAK,CAAC,CAACC,KAAK,GAAKA,SAASR,aAAa,CAAC,EAAE,EACzCS,MAAM,GAAG,OACbC;QAEJ,+EAA+E;QAC/E,MAAMC,OAAO,AAACzC,CAAAA,IAAIJ,OAAO,CAACa,GAAG,CAAC,WAAW,EAAC,EAAGwB,KAAK,CAAC,IAAI,CAAC,EAAE;QAC1D,IAAIL,MAAMc,QAAQ,KAAKD,MAAM;YAC3Bb,MAAMc,QAAQ,GAAGF;QACnB;QAEA,IAAI;YACF,MAAMnD,kBAAkB;gBACtBsD,gBAAgBpB,UAAUoB,cAAc;gBACxCC,QAAQ1D,SAASyC;gBACjBC;gBACAzB,SAASH,IAAIG,OAAO;gBACpBH;gBACA6C,eAAetB,UAAUsB,aAAa;gBACtCb;YACF;QACF,EAAE,OAAOlC,OAAO;YACdE,IAAIG,OAAO,CAAC2C,MAAM,CAAChD,KAAK,CAAC;gBACvBiD,KAAKjD;gBACLkD,KAAK;YACP;QACF;QAEA,OAAO1D,KAAK;YAAEoC,SAAS;QAAK;IAC9B,EAAE"}
1
+ {"version":3,"sources":["../../src/endpoints/handlers.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload';\n\nimport type { SearchIndexCache } from '../cache.js';\nimport { resolveAnalytics } from '../options.js';\nimport { createSearchService } from '../resolve.js';\nimport {\n deviceOf,\n isBot,\n parseTrackPayload,\n recordSearchEvent,\n} from '../track.js';\nimport type { SearchPluginConfig } from '../types.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 = (\n req: PayloadRequest,\n cache: SearchIndexCache,\n 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 =\n 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/**\n * GET — flat, ranked, paginated results for `?q=&collection=&page=&limit=`. `collection` may\n * repeat. For a full results page, where the grouped endpoint's caps get in the way.\n */\nexport const createResultsHandler =\n ({\n cache,\n config,\n }: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n }): PayloadHandler =>\n async req => {\n const params = new URL(req.url ?? '', 'http://localhost').searchParams;\n return json(\n await service(req, cache, config).query({\n collections: params.getAll('collection'),\n limit: Number(params.get('limit')) || undefined,\n page: Number(params.get('page')) || undefined,\n q: params.get('q') ?? '',\n })\n );\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 req,\n retentionDays: analytics.retentionDays,\n visitorId,\n });\n } catch (error) {\n req.payload.logger.error({\n err: error,\n msg: 'search-plugin: failed to record search event',\n });\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","createResultsHandler","params","collections","getAll","limit","Number","undefined","page","q","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","host","referrer","collectionSlug","device","retentionDays","logger","err","msg"],"mappings":"AAGA,SAASA,gBAAgB,QAAQ,gBAAgB;AACjD,SAASC,mBAAmB,QAAQ,gBAAgB;AACpD,SACEC,QAAQ,EACRC,KAAK,EACLC,iBAAiB,EACjBC,iBAAiB,QACZ,cAAc;AAGrB,MAAMC,OAAO,CAACC,MAAeC,SAAS,GAAG,GACvC,IAAIC,SAASC,KAAKC,SAAS,CAACJ,OAAO;QACjCK,SAAS;YAAE,gBAAgB;QAAmB;QAC9CJ;IACF;AAEF,MAAMK,YAAY,IAAMP,KAAK;QAAEQ,OAAO;IAAgB,GAAG;AAEzD,MAAMC,UAAU,CACdC,KACAC,OACAC,SACGjB,oBAAoB;QAAEgB;QAAOC;QAAQC,SAASH,IAAIG,OAAO;IAAC;AAE/D,2HAA2H,GAC3H,OAAO,MAAMC,sBACX,CAAC,EACCH,KAAK,EACLC,MAAM,EAIP,GACD,OAAMF;QACJ,MAAMK,QACJ,IAAIC,IAAIN,IAAIO,GAAG,IAAI,IAAI,oBAAoBC,YAAY,CAACC,GAAG,CAAC,QAAQ;QACtE,MAAMC,UAAU,MAAMX,QAAQC,KAAKC,OAAOC,QAAQS,MAAM,CAACN;QAEzD,OAAOf,KAAKoB;IACd,EAAE;AAEJ;;;CAGC,GACD,OAAO,MAAME,uBACX,CAAC,EACCX,KAAK,EACLC,MAAM,EAIP,GACD,OAAMF;QACJ,MAAMa,SAAS,IAAIP,IAAIN,IAAIO,GAAG,IAAI,IAAI,oBAAoBC,YAAY;QACtE,OAAOlB,KACL,MAAMS,QAAQC,KAAKC,OAAOC,QAAQG,KAAK,CAAC;YACtCS,aAAaD,OAAOE,MAAM,CAAC;YAC3BC,OAAOC,OAAOJ,OAAOJ,GAAG,CAAC,aAAaS;YACtCC,MAAMF,OAAOJ,OAAOJ,GAAG,CAAC,YAAYS;YACpCE,GAAGP,OA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D,OAAO;YACV,OAAO/C,KAAK;gBAAEQ,OAAO;YAAkB,GAAG;QAC5C;QAEA,MAAMyC,aAAaP,UAAUQ,aAAa;QAC1C,MAAMC,YAAYF,aACdvC,IAAIJ,OAAO,CACRa,GAAG,CAAC,WACHiC,MAAM,KACPC,IAAIC,CAAAA,IAAKA,EAAEC,IAAI,GAAGH,KAAK,CAAC,MACxBI,KAAK,CAAC,CAACC,KAAK,GAAKA,SAASR,aAAa,CAAC,EAAE,EACzCS,MAAM,GAAG,OACb9B;QAEJ,+EAA+E;QAC/E,MAAM+B,OAAO,AAACjD,CAAAA,IAAIJ,OAAO,CAACa,GAAG,CAAC,WAAW,EAAC,EAAGiC,KAAK,CAAC,IAAI,CAAC,EAAE;QAC1D,IAAIL,MAAMa,QAAQ,KAAKD,MAAM;YAC3BZ,MAAMa,QAAQ,GAAGhC;QACnB;QAEA,IAAI;YACF,MAAM7B,kBAAkB;gBACtB8D,gBAAgBnB,UAAUmB,cAAc;gBACxCC,QAAQlE,SAASkD;gBACjBC;gBACAlC,SAASH,IAAIG,OAAO;gBACpBH;gBACAqD,eAAerB,UAAUqB,aAAa;gBACtCZ;YACF;QACF,EAAE,OAAO3C,OAAO;YACdE,IAAIG,OAAO,CAACmD,MAAM,CAACxD,KAAK,CAAC;gBACvByD,KAAKzD;gBACL0D,KAAK;YACP;QACF;QAEA,OAAOlE,KAAK;YAAE6C,SAAS;QAAK;IAC9B,EAAE"}
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ 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
- export { createSearchService } from './resolve.js';
8
+ export { createSearchService, DEFAULT_INDEX_COLLECTION, } from './resolve.js';
9
9
  export type { ShownResult, TrackPayload } from './track.js';
10
10
  export { deviceOf, isBot, parseTrackPayload, recordSearchEvent, } from './track.js';
11
11
  export type * from './types.js';
package/dist/index.js CHANGED
@@ -2,14 +2,15 @@ import { withRateLimit } from '@foundrykit/rate-limit';
2
2
  import { recordActivePlugin } from './activePlugins.js';
3
3
  import { searchIndexCache } from './cache.js';
4
4
  import { createSearchEventsCollection } from './collections/SearchEvents.js';
5
- import { createInspectHandler, createReindexHandler, createSearchHandler, createTrackHandler } from './endpoints/handlers.js';
5
+ import { createInspectHandler, createReindexHandler, createResultsHandler, createSearchHandler, createTrackHandler } from './endpoints/handlers.js';
6
6
  import { assertConfig, DEFAULT_TRACK_RATE_LIMIT, resolveAnalytics } from './options.js';
7
+ import { DEFAULT_INDEX_COLLECTION } from './resolve.js';
7
8
  export { aggregateEvents, cleanSearchTerm } from './analytics.js';
8
9
  export { SearchIndexCache, searchIndexCache } from './cache.js';
9
10
  export { decodeEntities } from './decodeEntities.js';
10
11
  export { hrefFor, projectDocs } from './project.js';
11
12
  export { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs } from './rank.js';
12
- export { createSearchService } from './resolve.js';
13
+ export { createSearchService, DEFAULT_INDEX_COLLECTION } from './resolve.js';
13
14
  export { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.js';
14
15
  /**
15
16
  * Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.
@@ -30,6 +31,24 @@ export { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.j
30
31
  const prefix = pluginOptions.routePrefix ?? '/site-search';
31
32
  const requireAdmin = pluginOptions.requireAdminForOperations ?? true;
32
33
  searchIndexCache.configure(pluginOptions.cacheTTL ?? 60_000);
34
+ // Drop the projection whenever plugin-search writes the index, so a published edit shows up
35
+ // now rather than after the TTL. Per process: other instances still wait out the TTL.
36
+ const indexSlug = pluginOptions.indexCollection ?? DEFAULT_INDEX_COLLECTION;
37
+ const invalidate = ()=>searchIndexCache.invalidate();
38
+ config.collections = (config.collections || []).map((collection)=>collection.slug === indexSlug ? {
39
+ ...collection,
40
+ hooks: {
41
+ ...collection.hooks,
42
+ afterChange: [
43
+ ...collection.hooks?.afterChange ?? [],
44
+ invalidate
45
+ ],
46
+ afterDelete: [
47
+ ...collection.hooks?.afterDelete ?? [],
48
+ invalidate
49
+ ]
50
+ }
51
+ } : collection);
33
52
  if (analytics.enabled) {
34
53
  config.collections = [
35
54
  ...config.collections || [],
@@ -48,6 +67,14 @@ export { deviceOf, isBot, parseTrackPayload, recordSearchEvent } from './track.j
48
67
  method: 'get',
49
68
  path: prefix
50
69
  },
70
+ {
71
+ handler: createResultsHandler({
72
+ cache: searchIndexCache,
73
+ config: pluginOptions
74
+ }),
75
+ method: 'get',
76
+ path: `${prefix}/results`
77
+ },
51
78
  {
52
79
  handler: createReindexHandler({
53
80
  cache: searchIndexCache,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { withRateLimit } from '@foundrykit/rate-limit';\nimport type { Config } from 'payload';\nimport { recordActivePlugin } from './activePlugins.js';\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 {\n assertConfig,\n DEFAULT_TRACK_RATE_LIMIT,\n resolveAnalytics,\n} from './options.js';\nimport type { SearchPluginConfig } from './types.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 {\n DEFAULT_FIELDS,\n DEFAULT_FUZZY,\n groupResults,\n presetResults,\n rankDocs,\n} from './rank.js';\nexport { createSearchService } from './resolve.js';\nexport type { ShownResult, TrackPayload } from './track.js';\nexport {\n deviceOf,\n isBot,\n parseTrackPayload,\n recordSearchEvent,\n} 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({\n cache: searchIndexCache,\n config: pluginOptions,\n }),\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 // Public and writes a row per call, so it is always limited unless the host opts out.\n handler:\n pluginOptions.rateLimit === false\n ? createTrackHandler({ config: pluginOptions })\n : withRateLimit(\n createTrackHandler({ config: pluginOptions }),\n {\n key: (_req, ip) => `search-track:${ip}`,\n ...DEFAULT_TRACK_RATE_LIMIT,\n ...pluginOptions.rateLimit,\n }\n ),\n method: 'post' as const,\n path: `${prefix}/track`,\n },\n ]\n : []),\n ];\n\n return recordActivePlugin(config, '@foundrykit/search-plugin');\n };\n"],"names":["withRateLimit","recordActivePlugin","searchIndexCache","createSearchEventsCollection","createInspectHandler","createReindexHandler","createSearchHandler","createTrackHandler","assertConfig","DEFAULT_TRACK_RATE_LIMIT","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","rateLimit","key","_req","ip"],"mappings":"AAAA,SAASA,aAAa,QAAQ,yBAAyB;AAEvD,SAASC,kBAAkB,QAAQ,qBAAqB;AACxD,SAASC,gBAAgB,QAAQ,aAAa;AAC9C,SAASC,4BAA4B,QAAQ,gCAAgC;AAC7E,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,mBAAmB,EACnBC,kBAAkB,QACb,0BAA0B;AACjC,SACEC,YAAY,EACZC,wBAAwB,EACxBC,gBAAgB,QACX,eAAe;AAGtB,SAASC,eAAe,EAAEC,eAAe,QAAQ,iBAAiB;AAClE,SAASC,gBAAgB,EAAEX,gBAAgB,QAAQ,aAAa;AAChE,SAASY,cAAc,QAAQ,sBAAsB;AACrD,SAASC,OAAO,EAAEC,WAAW,QAAQ,eAAe;AACpD,SACEC,cAAc,EACdC,aAAa,EACbC,YAAY,EACZC,aAAa,EACbC,QAAQ,QACH,YAAY;AACnB,SAASC,mBAAmB,QAAQ,eAAe;AAEnD,SACEC,QAAQ,EACRC,KAAK,EACLC,iBAAiB,EACjBC,iBAAiB,QACZ,aAAa;AAGpB;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,eACX,CAACC,gBACD,CAACC;QACC,IAAID,cAAcE,QAAQ,EAAE;YAC1B,OAAOD;QACT;QAEArB,aAAaoB;QAEb,MAAMG,YAAYrB,iBAAiBkB,cAAcG,SAAS;QAC1D,MAAMC,SAASJ,cAAcK,WAAW,IAAI;QAC5C,MAAMC,eAAeN,cAAcO,yBAAyB,IAAI;QAEhEjC,iBAAiBkC,SAAS,CAACR,cAAcS,QAAQ,IAAI;QAErD,IAAIN,UAAUO,OAAO,EAAE;YACrBT,OAAOU,WAAW,GAAG;mBACfV,OAAOU,WAAW,IAAI,EAAE;gBAC5BpC,6BAA6B;oBAAEqC,MAAMT,UAAUU,cAAc;gBAAC;aAC/D;QACH;QAEAZ,OAAOa,SAAS,GAAG;eACbb,OAAOa,SAAS,IAAI,EAAE;YAC1B;gBACEC,SAASrC,oBAAoB;oBAC3BsC,OAAO1C;oBACP2B,QAAQD;gBACV;gBACAiB,QAAQ;gBACRC,MAAMd;YACR;YACA;gBACEW,SAAStC,qBAAqB;oBAC5BuC,OAAO1C;oBACP2B,QAAQD;oBACRM;gBACF;gBACAW,QAAQ;gBACRC,MAAM,GAAGd,OAAO,QAAQ,CAAC;YAC3B;YACA;gBACEW,SAASvC,qBAAqB;oBAC5BwC,OAAO1C;oBACP2B,QAAQD;oBACRM;gBACF;gBACAW,QAAQ;gBACRC,MAAM,GAAGd,OAAO,QAAQ,CAAC;YAC3B;eACID,UAAUO,OAAO,GACjB;gBACE;oBACE,sFAAsF;oBACtFK,SACEf,cAAcmB,SAAS,KAAK,QACxBxC,mBAAmB;wBAAEsB,QAAQD;oBAAc,KAC3C5B,cACEO,mBAAmB;wBAAEsB,QAAQD;oBAAc,IAC3C;wBACEoB,KAAK,CAACC,MAAMC,KAAO,CAAC,aAAa,EAAEA,IAAI;wBACvC,GAAGzC,wBAAwB;wBAC3B,GAAGmB,cAAcmB,SAAS;oBAC5B;oBAERF,QAAQ;oBACRC,MAAM,GAAGd,OAAO,MAAM,CAAC;gBACzB;aACD,GACD,EAAE;SACP;QAED,OAAO/B,mBAAmB4B,QAAQ;IACpC,EAAE"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { withRateLimit } from '@foundrykit/rate-limit';\nimport type { Config } from 'payload';\nimport { recordActivePlugin } from './activePlugins.js';\nimport { searchIndexCache } from './cache.js';\nimport { createSearchEventsCollection } from './collections/SearchEvents.js';\nimport {\n createInspectHandler,\n createReindexHandler,\n createResultsHandler,\n createSearchHandler,\n createTrackHandler,\n} from './endpoints/handlers.js';\nimport {\n assertConfig,\n DEFAULT_TRACK_RATE_LIMIT,\n resolveAnalytics,\n} from './options.js';\nimport { DEFAULT_INDEX_COLLECTION } from './resolve.js';\nimport type { SearchPluginConfig } from './types.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 {\n DEFAULT_FIELDS,\n DEFAULT_FUZZY,\n groupResults,\n presetResults,\n rankDocs,\n} from './rank.js';\nexport {\n createSearchService,\n DEFAULT_INDEX_COLLECTION,\n} from './resolve.js';\nexport type { ShownResult, TrackPayload } from './track.js';\nexport {\n deviceOf,\n isBot,\n parseTrackPayload,\n recordSearchEvent,\n} 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 // Drop the projection whenever plugin-search writes the index, so a published edit shows up\n // now rather than after the TTL. Per process: other instances still wait out the TTL.\n const indexSlug = pluginOptions.indexCollection ?? DEFAULT_INDEX_COLLECTION;\n const invalidate = () => searchIndexCache.invalidate();\n config.collections = (config.collections || []).map(collection =>\n collection.slug === indexSlug\n ? {\n ...collection,\n hooks: {\n ...collection.hooks,\n afterChange: [\n ...(collection.hooks?.afterChange ?? []),\n invalidate,\n ],\n afterDelete: [\n ...(collection.hooks?.afterDelete ?? []),\n invalidate,\n ],\n },\n }\n : collection\n );\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({\n cache: searchIndexCache,\n config: pluginOptions,\n }),\n method: 'get',\n path: prefix,\n },\n {\n handler: createResultsHandler({\n cache: searchIndexCache,\n config: pluginOptions,\n }),\n method: 'get',\n path: `${prefix}/results`,\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 // Public and writes a row per call, so it is always limited unless the host opts out.\n handler:\n pluginOptions.rateLimit === false\n ? createTrackHandler({ config: pluginOptions })\n : withRateLimit(\n createTrackHandler({ config: pluginOptions }),\n {\n key: (_req, ip) => `search-track:${ip}`,\n ...DEFAULT_TRACK_RATE_LIMIT,\n ...pluginOptions.rateLimit,\n }\n ),\n method: 'post' as const,\n path: `${prefix}/track`,\n },\n ]\n : []),\n ];\n\n return recordActivePlugin(config, '@foundrykit/search-plugin');\n };\n"],"names":["withRateLimit","recordActivePlugin","searchIndexCache","createSearchEventsCollection","createInspectHandler","createReindexHandler","createResultsHandler","createSearchHandler","createTrackHandler","assertConfig","DEFAULT_TRACK_RATE_LIMIT","resolveAnalytics","DEFAULT_INDEX_COLLECTION","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","indexSlug","indexCollection","invalidate","collections","map","collection","slug","hooks","afterChange","afterDelete","enabled","collectionSlug","endpoints","handler","cache","method","path","rateLimit","key","_req","ip"],"mappings":"AAAA,SAASA,aAAa,QAAQ,yBAAyB;AAEvD,SAASC,kBAAkB,QAAQ,qBAAqB;AACxD,SAASC,gBAAgB,QAAQ,aAAa;AAC9C,SAASC,4BAA4B,QAAQ,gCAAgC;AAC7E,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,oBAAoB,EACpBC,mBAAmB,EACnBC,kBAAkB,QACb,0BAA0B;AACjC,SACEC,YAAY,EACZC,wBAAwB,EACxBC,gBAAgB,QACX,eAAe;AACtB,SAASC,wBAAwB,QAAQ,eAAe;AAGxD,SAASC,eAAe,EAAEC,eAAe,QAAQ,iBAAiB;AAClE,SAASC,gBAAgB,EAAEb,gBAAgB,QAAQ,aAAa;AAChE,SAASc,cAAc,QAAQ,sBAAsB;AACrD,SAASC,OAAO,EAAEC,WAAW,QAAQ,eAAe;AACpD,SACEC,cAAc,EACdC,aAAa,EACbC,YAAY,EACZC,aAAa,EACbC,QAAQ,QACH,YAAY;AACnB,SACEC,mBAAmB,EACnBZ,wBAAwB,QACnB,eAAe;AAEtB,SACEa,QAAQ,EACRC,KAAK,EACLC,iBAAiB,EACjBC,iBAAiB,QACZ,aAAa;AAGpB;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,eACX,CAACC,gBACD,CAACC;QACC,IAAID,cAAcE,QAAQ,EAAE;YAC1B,OAAOD;QACT;QAEAtB,aAAaqB;QAEb,MAAMG,YAAYtB,iBAAiBmB,cAAcG,SAAS;QAC1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qB;oBAC5BkD,OAAOpD;oBACP6B,QAAQD;oBACRM;gBACF;gBACAmB,QAAQ;gBACRC,MAAM,GAAGtB,OAAO,QAAQ,CAAC;YAC3B;eACID,UAAUiB,OAAO,GACjB;gBACE;oBACE,sFAAsF;oBACtFG,SACEvB,cAAc2B,SAAS,KAAK,QACxBjD,mBAAmB;wBAAEuB,QAAQD;oBAAc,KAC3C9B,cACEQ,mBAAmB;wBAAEuB,QAAQD;oBAAc,IAC3C;wBACE4B,KAAK,CAACC,MAAMC,KAAO,CAAC,aAAa,EAAEA,IAAI;wBACvC,GAAGlD,wBAAwB;wBAC3B,GAAGoB,cAAc2B,SAAS;oBAC5B;oBAERF,QAAQ;oBACRC,MAAM,GAAGtB,OAAO,MAAM,CAAC;gBACzB;aACD,GACD,EAAE;SACP;QAED,OAAOjC,mBAAmB8B,QAAQ;IACpC,EAAE"}
package/dist/project.d.ts CHANGED
@@ -1,18 +1,4 @@
1
- import type { IndexedDoc, SearchableCollection } from './types.js';
2
- /** A row as it comes back from the plugin-search `search` collection. */
3
- export type SearchDoc = {
4
- doc?: {
5
- relationTo?: string;
6
- value?: number | string;
7
- } | null;
8
- id?: number | string;
9
- meta?: {
10
- description?: null | string;
11
- title?: null | string;
12
- } | null;
13
- slug?: null | string;
14
- title?: null | string;
15
- };
1
+ import type { IndexedDoc, SearchableCollection, SearchDoc } from './types.js';
16
2
  export type ProjectionResult = {
17
3
  docs: IndexedDoc[];
18
4
  skipped: {
@@ -28,9 +14,11 @@ export type ProjectionResult = {
28
14
  * drop is recorded with a reason — an inventory count tells you nothing when the document you care
29
15
  * about is the one that is missing.
30
16
  */
31
- export declare function projectDocs({ collections, decode, rows, }: {
17
+ export declare function projectDocs({ collections, decode, hidden, rows, }: {
32
18
  collections: SearchableCollection[];
33
19
  decode?: boolean;
20
+ /** `${collection}:${docId}` keys hidden by a collection's `excludeField`. */
21
+ hidden?: Set<string>;
34
22
  rows: SearchDoc[];
35
23
  }): ProjectionResult;
36
24
  /** Build the href for a projected document. */
package/dist/project.js CHANGED
@@ -5,7 +5,7 @@ import { decodeEntities } from './decodeEntities.js';
5
5
  * Rows are dropped rather than half-rendered when they cannot produce a working result, and every
6
6
  * drop is recorded with a reason — an inventory count tells you nothing when the document you care
7
7
  * about is the one that is missing.
8
- */ export function projectDocs({ collections, decode = true, rows }) {
8
+ */ export function projectDocs({ collections, decode = true, hidden, rows }) {
9
9
  const byslug = new Map(collections.map((entry)=>[
10
10
  entry.slug,
11
11
  entry
@@ -58,11 +58,21 @@ import { decodeEntities } from './decodeEntities.js';
58
58
  });
59
59
  continue;
60
60
  }
61
+ if (hidden?.has(`${collection}:${id}`)) {
62
+ skipped.push({
63
+ id,
64
+ slug: collection,
65
+ reason: `hidden by "${config.excludeField}"`
66
+ });
67
+ continue;
68
+ }
61
69
  docs.push({
62
70
  id: `${collection}-${id}`,
63
71
  collection,
64
72
  description: decode ? decodeEntities(row.meta?.description) : row.meta?.description ?? undefined,
73
+ docId: id,
65
74
  group: config.group,
75
+ href: config.href?.(row) || undefined,
66
76
  icon: config.icon,
67
77
  // An empty prefix is meaningful: it marks a collection served at the site root. Compared
68
78
  // against undefined rather than truthiness so those documents are not silently dropped.
@@ -77,6 +87,6 @@ import { decodeEntities } from './decodeEntities.js';
77
87
  skipped
78
88
  };
79
89
  }
80
- /** Build the href for a projected document. */ export const hrefFor = (doc)=>`${doc.path}/${doc.slug}`;
90
+ /** Build the href for a projected document. */ export const hrefFor = (doc)=>doc.href ?? `${doc.path}/${doc.slug}`;
81
91
 
82
92
  //# sourceMappingURL=project.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/project.ts"],"sourcesContent":["import { decodeEntities } from './decodeEntities.js';\nimport type { IndexedDoc, SearchableCollection } from './types.js';\n\n/** A row as it comes back from the plugin-search `search` collection. */\nexport type SearchDoc = {\n doc?: { relationTo?: string; value?: number | string } | null;\n id?: number | string;\n meta?: { description?: null | string; title?: null | string } | null;\n slug?: null | string;\n title?: null | string;\n};\n\nexport type ProjectionResult = {\n docs: IndexedDoc[];\n skipped: { id: string; reason: string; slug: string }[];\n};\n\n/**\n * Turn plugin-search rows into the flat projection the read path searches.\n *\n * Rows are dropped rather than half-rendered when they cannot produce a working result, and every\n * drop is recorded with a reason — an inventory count tells you nothing when the document you care\n * about is the one that is missing.\n */\nexport function projectDocs({\n collections,\n decode = true,\n rows,\n}: {\n collections: SearchableCollection[];\n decode?: boolean;\n rows: SearchDoc[];\n}): ProjectionResult {\n const byslug = new Map(collections.map(entry => [entry.slug, entry]));\n const docs: IndexedDoc[] = [];\n const skipped: ProjectionResult['skipped'] = [];\n\n for (const row of rows) {\n const collection = row.doc?.relationTo;\n const id = String(row.doc?.value ?? row.id ?? '');\n\n if (!collection) {\n skipped.push({\n id,\n slug: '',\n reason: 'no source collection on the index row',\n });\n continue;\n }\n\n const config = byslug.get(collection);\n if (!config) {\n skipped.push({\n id,\n slug: collection,\n reason: `collection \"${collection}\" is not configured`,\n });\n continue;\n }\n\n const slug = row.slug;\n const title = row.title || row.meta?.title;\n\n if (!slug) {\n skipped.push({\n id,\n slug: collection,\n reason: 'no slug, so no URL can be built',\n });\n continue;\n }\n\n if (!title) {\n skipped.push({ id, slug: collection, reason: 'no title to display' });\n continue;\n }\n\n if (config.excludeSlugs?.includes(slug)) {\n skipped.push({ id, slug: collection, reason: 'excluded by config' });\n continue;\n }\n\n docs.push({\n id: `${collection}-${id}`,\n collection,\n description: decode\n ? decodeEntities(row.meta?.description)\n : (row.meta?.description ?? undefined),\n group: config.group,\n icon: config.icon,\n // An empty prefix is meaningful: it marks a collection served at the site root. Compared\n // against undefined rather than truthiness so those documents are not silently dropped.\n slug,\n path: config.path,\n title: decode ? decodeEntities(title) : title,\n weight: config.weight ?? 1,\n });\n }\n\n return { docs, skipped };\n}\n\n/** Build the href for a projected document. */\nexport const hrefFor = (doc: IndexedDoc): string => `${doc.path}/${doc.slug}`;\n"],"names":["decodeEntities","projectDocs","collections","decode","rows","byslug","Map","map","entry","slug","docs","skipped","row","collection","doc","relationTo","id","String","value","push","reason","config","get","title","meta","excludeSlugs","includes","description","undefined","group","icon","path","weight","hrefFor"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAsB;AAiBrD;;;;;;CAMC,GACD,OAAO,SAASC,YAAY,EAC1BC,WAAW,EACXC,SAAS,IAAI,EACbC,IAAI,EAKL;IACC,MAAMC,SAAS,IAAIC,IAAIJ,YAAYK,GAAG,CAACC,CAAAA,QAAS;YAACA,MAAMC,IAAI;YAAED;SAAM;IACnE,MAAME,OAAqB,EAAE;IAC7B,MAAMC,UAAuC,EAAE;IAE/C,KAAK,MAAMC,OAAOR,KAAM;QACtB,MAAMS,aAAaD,IAAIE,GAAG,EAAEC;QAC5B,MAAMC,KAAKC,OAAOL,IAAIE,GAAG,EAAEI,SAASN,IAAII,EAAE,IAAI;QAE9C,IAAI,CAACH,YAAY;YACfF,QAAQQ,IAAI,CAAC;gBACXH;gBACAP,MAAM;gBACNW,QAAQ;YACV;YACA;QACF;QAEA,MAAMC,SAAShB,OAAOiB,GAAG,CAACT;QAC1B,IAAI,CAACQ,QAAQ;YACXV,QAAQQ,IAAI,CAAC;gBACXH;gBACAP,MAAMI;gBACNO,QAAQ,CAAC,YAAY,EAAEP,WAAW,mBAAmB,CAAC;YACxD;YACA;QACF;QAEA,MAAMJ,OAAOG,IAAIH,IAAI;QACrB,MAAMc,QAAQX,IAAIW,KAAK,IAAIX,IAAIY,IAAI,EAAED;QAErC,IAAI,CAACd,MAAM;YACTE,QAAQQ,IAAI,CAAC;gBACXH;gBACAP,MAAMI;gBACNO,QAAQ;YACV;YACA;QACF;QAEA,IAAI,CAACG,OAAO;YACVZ,QAAQQ,IAAI,CAAC;gBAAEH;gBAAIP,MAAMI;gBAAYO,QAAQ;YAAsB;YACnE;QACF;QAEA,IAAIC,OAAOI,YAAY,EAAEC,SAASjB,OAAO;YACvCE,QAAQQ,IAAI,CAAC;gBAAEH;gBAAIP,MAAMI;gBAAYO,QAAQ;YAAqB;YAClE;QACF;QAEAV,KAAKS,IAAI,CAAC;YACRH,IAAI,GAAGH,WAAW,CAAC,EAAEG,IAAI;YACzBH;YACAc,aAAaxB,SACTH,eAAeY,IAAIY,IAAI,EAAEG,eACxBf,IAAIY,IAAI,EAAEG,eAAeC;YAC9BC,OAAOR,OAAOQ,KAAK;YACnBC,MAAMT,OAAOS,IAAI;YACjB,yFAAyF;YACzF,wFAAwF;YACxFrB;YACAsB,MAAMV,OAAOU,IAAI;YACjBR,OAAOpB,SAASH,eAAeuB,SAASA;YACxCS,QAAQX,OAAOW,MAAM,IAAI;QAC3B;IACF;IAEA,OAAO;QAAEtB;QAAMC;IAAQ;AACzB;AAEA,6CAA6C,GAC7C,OAAO,MAAMsB,UAAU,CAACnB,MAA4B,GAAGA,IAAIiB,IAAI,CAAC,CAAC,EAAEjB,IAAIL,IAAI,EAAE,CAAC"}
1
+ {"version":3,"sources":["../src/project.ts"],"sourcesContent":["import { decodeEntities } from './decodeEntities.js';\nimport type { IndexedDoc, SearchableCollection, SearchDoc } from './types.js';\n\nexport type ProjectionResult = {\n docs: IndexedDoc[];\n skipped: { id: string; reason: string; slug: string }[];\n};\n\n/**\n * Turn plugin-search rows into the flat projection the read path searches.\n *\n * Rows are dropped rather than half-rendered when they cannot produce a working result, and every\n * drop is recorded with a reason — an inventory count tells you nothing when the document you care\n * about is the one that is missing.\n */\nexport function projectDocs({\n collections,\n decode = true,\n hidden,\n rows,\n}: {\n collections: SearchableCollection[];\n decode?: boolean;\n /** `${collection}:${docId}` keys hidden by a collection's `excludeField`. */\n hidden?: Set<string>;\n rows: SearchDoc[];\n}): ProjectionResult {\n const byslug = new Map(collections.map(entry => [entry.slug, entry]));\n const docs: IndexedDoc[] = [];\n const skipped: ProjectionResult['skipped'] = [];\n\n for (const row of rows) {\n const collection = row.doc?.relationTo;\n const id = String(row.doc?.value ?? row.id ?? '');\n\n if (!collection) {\n skipped.push({\n id,\n slug: '',\n reason: 'no source collection on the index row',\n });\n continue;\n }\n\n const config = byslug.get(collection);\n if (!config) {\n skipped.push({\n id,\n slug: collection,\n reason: `collection \"${collection}\" is not configured`,\n });\n continue;\n }\n\n const slug = row.slug;\n const title = row.title || row.meta?.title;\n\n if (!slug) {\n skipped.push({\n id,\n slug: collection,\n reason: 'no slug, so no URL can be built',\n });\n continue;\n }\n\n if (!title) {\n skipped.push({ id, slug: collection, reason: 'no title to display' });\n continue;\n }\n\n if (config.excludeSlugs?.includes(slug)) {\n skipped.push({ id, slug: collection, reason: 'excluded by config' });\n continue;\n }\n\n if (hidden?.has(`${collection}:${id}`)) {\n skipped.push({\n id,\n slug: collection,\n reason: `hidden by \"${config.excludeField}\"`,\n });\n continue;\n }\n\n docs.push({\n id: `${collection}-${id}`,\n collection,\n description: decode\n ? decodeEntities(row.meta?.description)\n : (row.meta?.description ?? undefined),\n docId: id,\n group: config.group,\n href: config.href?.(row) || undefined,\n icon: config.icon,\n // An empty prefix is meaningful: it marks a collection served at the site root. Compared\n // against undefined rather than truthiness so those documents are not silently dropped.\n slug,\n path: config.path,\n title: decode ? decodeEntities(title) : title,\n weight: config.weight ?? 1,\n });\n }\n\n return { docs, skipped };\n}\n\n/** Build the href for a projected document. */\nexport const hrefFor = (doc: IndexedDoc): string =>\n doc.href ?? `${doc.path}/${doc.slug}`;\n"],"names":["decodeEntities","projectDocs","collections","decode","hidden","rows","byslug","Map","map","entry","slug","docs","skipped","row","collection","doc","relationTo","id","String","value","push","reason","config","get","title","meta","excludeSlugs","includes","has","excludeField","description","undefined","docId","group","href","icon","path","weight","hrefFor"],"mappings":"AAAA,SAASA,cAAc,QAAQ,sBAAsB;AAQrD;;;;;;CAMC,GACD,OAAO,SAASC,YAAY,EAC1BC,WAAW,EACXC,SAAS,IAAI,EACbC,MAAM,EACNC,IAAI,EAOL;IACC,MAAMC,SAAS,IAAIC,IAAIL,YAAYM,GAAG,CAACC,CAAAA,QAAS;YAACA,MAAMC,IAAI;YAAED;SAAM;IACnE,MAAME,OAAqB,E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eACxBjB,IAAIY,IAAI,EAAEK,eAAeC;YAC9BC,OAAOf;YACPgB,OAAOX,OAAOW,KAAK;YACnBC,MAAMZ,OAAOY,IAAI,GAAGrB,QAAQkB;YAC5BI,MAAMb,OAAOa,IAAI;YACjB,yFAAyF;YACzF,wFAAwF;YACxFzB;YACA0B,MAAMd,OAAOc,IAAI;YACjBZ,OAAOrB,SAASH,eAAewB,SAASA;YACxCa,QAAQf,OAAOe,MAAM,IAAI;QAC3B;IACF;IAEA,OAAO;QAAE1B;QAAMC;IAAQ;AACzB;AAEA,6CAA6C,GAC7C,OAAO,MAAM0B,UAAU,CAACvB,MACtBA,IAAImB,IAAI,IAAI,GAAGnB,IAAIqB,IAAI,CAAC,CAAC,EAAErB,IAAIL,IAAI,EAAE,CAAC"}
package/dist/rank.d.ts CHANGED
@@ -1,6 +1,17 @@
1
- import type { FuzzyOptions, GroupedResults, IndexedDoc, SearchField, SearchGroup } from './types.js';
1
+ import type { FuzzyOptions, GroupedResults, IndexedDoc, SearchField, SearchGroup, SearchResult } from './types.js';
2
2
  export declare const DEFAULT_FIELDS: SearchField[];
3
3
  export declare const DEFAULT_FUZZY: Required<FuzzyOptions>;
4
+ export type RankedDoc = {
5
+ doc: IndexedDoc;
6
+ highlights?: [number, number][];
7
+ score?: number;
8
+ };
9
+ export declare const toResult: ({ doc, highlights, score, }: RankedDoc) => SearchResult;
10
+ /** Fuse's inclusive title match indices as sorted, merged `[start, end)` ranges. */
11
+ export declare function titleHighlights(matches?: readonly {
12
+ indices: readonly (readonly [number, number])[];
13
+ key?: string;
14
+ }[]): [number, number][];
4
15
  /**
5
16
  * Rank documents against a query.
6
17
  *
@@ -18,17 +29,13 @@ export declare function rankDocs({ docs, fields, fuzzy, query, }: {
18
29
  fields?: SearchField[];
19
30
  fuzzy?: FuzzyOptions;
20
31
  query: string;
21
- }): {
22
- doc: IndexedDoc;
32
+ }): (RankedDoc & {
23
33
  score: number;
24
- }[];
34
+ })[];
25
35
  /** Bucket ranked documents into their groups, applying each group's cap. */
26
36
  export declare function groupResults({ groups, ranked, }: {
27
37
  groups: SearchGroup[];
28
- ranked: {
29
- doc: IndexedDoc;
30
- score?: number;
31
- }[];
38
+ ranked: RankedDoc[];
32
39
  }): GroupedResults;
33
40
  /**
34
41
  * The empty-query preset.
package/dist/rank.js CHANGED
@@ -21,15 +21,36 @@ export const DEFAULT_FUZZY = {
21
21
  minMatchCharLength: 3,
22
22
  threshold: 0.35
23
23
  };
24
- const toResult = (doc, score)=>({
24
+ export const toResult = ({ doc, highlights, score })=>({
25
25
  id: doc.id,
26
26
  collection: doc.collection,
27
+ description: doc.description,
28
+ docId: doc.docId,
27
29
  group: doc.group,
30
+ highlights,
28
31
  href: hrefFor(doc),
29
32
  icon: doc.icon,
30
33
  score,
31
34
  title: doc.title
32
35
  });
36
+ /** Fuse's inclusive title match indices as sorted, merged `[start, end)` ranges. */ export function titleHighlights(matches = []) {
37
+ const ranges = matches.filter((match)=>match.key === 'title').flatMap((match)=>match.indices.map(([a, b])=>[
38
+ a,
39
+ b + 1
40
+ ])).sort((a, b)=>a[0] - b[0]);
41
+ const merged = [];
42
+ for (const range of ranges){
43
+ const last = merged.at(-1);
44
+ if (last && range[0] <= last[1]) {
45
+ last[1] = Math.max(last[1], range[1]);
46
+ } else {
47
+ merged.push([
48
+ ...range
49
+ ]);
50
+ }
51
+ }
52
+ return merged;
53
+ }
33
54
  /**
34
55
  * Rank documents against a query.
35
56
  *
@@ -53,6 +74,7 @@ const toResult = (doc, score)=>({
53
74
  const search = (useTokenSearch)=>new Fuse(docs, {
54
75
  distance: options.distance,
55
76
  ignoreLocation: true,
77
+ includeMatches: true,
56
78
  includeScore: true,
57
79
  keys: fields.map((field)=>({
58
80
  name: field.name,
@@ -63,6 +85,7 @@ const toResult = (doc, score)=>({
63
85
  useTokenSearch
64
86
  }).search(trimmed).map((hit)=>({
65
87
  doc: hit.item,
88
+ highlights: titleHighlights(hit.matches),
66
89
  // Fuse scores are "lower is better", so dividing by weight promotes a heavier collection.
67
90
  score: (hit.score ?? 1) / (hit.item.weight || 1)
68
91
  })).sort((a, b)=>a.score - b.score);
@@ -85,8 +108,8 @@ const toResult = (doc, score)=>({
85
108
  for (const group of groups){
86
109
  grouped[group.slug] = [];
87
110
  }
88
- for (const { doc, score } of ranked){
89
- const group = bySlug.get(doc.group);
111
+ for (const hit of ranked){
112
+ const group = bySlug.get(hit.doc.group);
90
113
  if (!group) {
91
114
  continue;
92
115
  }
@@ -94,7 +117,7 @@ const toResult = (doc, score)=>({
94
117
  if (group.limit !== undefined && bucket.length >= group.limit) {
95
118
  continue;
96
119
  }
97
- bucket.push(toResult(doc, score));
120
+ bucket.push(toResult(hit));
98
121
  }
99
122
  return grouped;
100
123
  }
package/dist/rank.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/rank.ts"],"sourcesContent":["import Fuse from 'fuse.js';\nimport { hrefFor } from './project.js';\nimport type {\n FuzzyOptions,\n GroupedResults,\n IndexedDoc,\n SearchField,\n SearchGroup,\n SearchResult,\n} from './types.js';\n\nexport const DEFAULT_FIELDS: SearchField[] = [\n { name: 'title', weight: 1 },\n { name: 'slug', weight: 0.4 },\n { name: 'description', weight: 0.2 },\n];\n\nexport const DEFAULT_FUZZY: Required<FuzzyOptions> = {\n distance: 100,\n // Two-character queries match too much to be useful; this is what stops a query like \"tuni\"\n // pulling documents that merely contain those letters somewhere in a description.\n minMatchCharLength: 3,\n threshold: 0.35,\n};\n\nconst toResult = (doc: IndexedDoc, score?: number): SearchResult => ({\n id: doc.id,\n collection: doc.collection,\n group: doc.group,\n href: hrefFor(doc),\n icon: doc.icon,\n score,\n title: doc.title,\n});\n\n/**\n * Rank documents against a query.\n *\n * Fuse gives fuzzy tolerance for typos and plurals. Its score is then divided by the collection\n * weight so a configured priority can lift an otherwise equal match — cheaper and far more\n * predictable than trying to express priority through Fuse's own field weights.\n *\n * Fuse matches the query as one phrase, so a word the title lacks or a different word order\n * (\"royal palm mauritius\", \"seychelles hilton\") matches nothing. A multi-word query therefore also\n * matches word by word, and those hits follow every phrase hit: the phrase ranking stays as it was,\n * and the words only add what it missed.\n */\nexport function rankDocs({\n docs,\n fields = DEFAULT_FIELDS,\n fuzzy,\n query,\n}: {\n docs: IndexedDoc[];\n fields?: SearchField[];\n fuzzy?: FuzzyOptions;\n query: string;\n}): { doc: IndexedDoc; score: number }[] {\n const trimmed = query.trim();\n if (!trimmed) {\n return [];\n }\n\n const options = { ...DEFAULT_FUZZY, ...fuzzy };\n const search = (useTokenSearch: boolean) =>\n new Fuse(docs, {\n distance: options.distance,\n ignoreLocation: true,\n includeScore: true,\n keys: fields.map(field => ({\n name: field.name,\n weight: field.weight ?? 1,\n })),\n minMatchCharLength: options.minMatchCharLength,\n threshold: options.threshold,\n useTokenSearch,\n })\n .search(trimmed)\n .map(hit => ({\n doc: hit.item,\n // Fuse scores are \"lower is better\", so dividing by weight promotes a heavier collection.\n score: (hit.score ?? 1) / (hit.item.weight || 1),\n }))\n .sort((a, b) => a.score - b.score);\n\n const phrase = search(false);\n if (!/\\s/.test(trimmed)) {\n return phrase;\n }\n const found = new Set(phrase.map(hit => hit.doc));\n return [...phrase, ...search(true).filter(hit => !found.has(hit.doc))];\n}\n\n/** Bucket ranked documents into their groups, applying each group's cap. */\nexport function groupResults({\n groups,\n ranked,\n}: {\n groups: SearchGroup[];\n ranked: { doc: IndexedDoc; score?: number }[];\n}): GroupedResults {\n const bySlug = new Map(groups.map(group => [group.slug, group]));\n const grouped: GroupedResults = {};\n\n for (const group of groups) {\n grouped[group.slug] = [];\n }\n\n for (const { doc, score } of ranked) {\n const group = bySlug.get(doc.group);\n if (!group) {\n continue;\n }\n\n const bucket = grouped[group.slug];\n if (group.limit !== undefined && bucket.length >= group.limit) {\n continue;\n }\n\n bucket.push(toResult(doc, score));\n }\n\n return grouped;\n}\n\n/**\n * The empty-query preset.\n *\n * Ordered by collection weight and then alphabetically, and only for groups that opted in. Callers\n * that want a curated list should configure weights — this is explicitly not popularity-ranked,\n * and saying so here is cheaper than a client learning it later.\n */\nexport function presetResults({\n docs,\n groups,\n}: {\n docs: IndexedDoc[];\n groups: SearchGroup[];\n}): GroupedResults {\n const eligible = new Set(\n groups\n .filter(group => group.showWhenEmpty !== false)\n .map(group => group.slug)\n );\n\n const ordered = docs\n .filter(doc => eligible.has(doc.group))\n .sort((a, b) => b.weight - a.weight || a.title.localeCompare(b.title))\n .map(doc => ({ doc }));\n\n const grouped = groupResults({ groups, ranked: ordered });\n\n for (const group of groups) {\n if (!eligible.has(group.slug)) {\n grouped[group.slug] = [];\n }\n }\n\n return grouped;\n}\n"],"names":["Fuse","hrefFor","DEFAULT_FIELDS","name","weight","DEFAULT_FUZZY","distance","minMatchCharLength","threshold","toResult","doc","score","id","collection","group","href","icon","title","rankDocs","docs","fields","fuzzy","query","trimmed","trim","options","search","useTokenSearch","ignoreLocation","includeScore","keys","map","field","hit","item","sort","a","b","phrase","test","found","Set","filter","has","groupResults","groups","ranked","bySlug","Map","slug","grouped","get","bucket","limit","undefined","length","push","presetResults","eligible","showWhenEmpty","ordered","localeCompare"],"mappings":"AAAA,OAAOA,UAAU,UAAU;AAC3B,SAASC,OAAO,QAAQ,eAAe;AAUvC,OAAO,MAAMC,iBAAgC;IAC3C;QAAEC,MAAM;QAASC,QAAQ;IAAE;IAC3B;QAAED,MAAM;QAAQC,QAAQ;IAAI;IAC5B;QAAED,MAAM;QAAeC,QAAQ;IAAI;CACpC,CAAC;AAEF,OAAO,MAAMC,gBAAwC;IACnDC,UAAU;IACV,4FAA4F;IAC5F,kFAAkF;IAClFC,oBAAoB;IACpBC,WAAW;AACb,EAAE;AAEF,MAAMC,WAAW,CAACC,KAAiBC,QAAkC,CAAA;QACnEC,IAAIF,IAAIE,EAAE;QACVC,YAAYH,IAAIG,UAAU;QAC1BC,OAAOJ,IAAII,KAAK;QAChBC,MAAMd,QAAQS;QACdM,MAAMN,IAAIM,IAAI;QACdL;QACAM,OAAOP,IAAIO,KAAK;IAClB,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AC1B,IAAI,CAACa,SAASf,GAAG,CAAC7B,MAAMmC,IAAI,GAAG;YAC7BC,OAAO,CAACpC,MAAMmC,IAAI,CAAC,GAAG,EAAE;QAC1B;IACF;IAEA,OAAOC;AACT"}
1
+ {"version":3,"sources":["../src/rank.ts"],"sourcesContent":["import Fuse from 'fuse.js';\nimport { hrefFor } from './project.js';\nimport type {\n FuzzyOptions,\n GroupedResults,\n IndexedDoc,\n SearchField,\n SearchGroup,\n SearchResult,\n} from './types.js';\n\nexport const DEFAULT_FIELDS: SearchField[] = [\n { name: 'title', weight: 1 },\n { name: 'slug', weight: 0.4 },\n { name: 'description', weight: 0.2 },\n];\n\nexport const DEFAULT_FUZZY: Required<FuzzyOptions> = {\n distance: 100,\n // Two-character queries match too much to be useful; this is what stops a query like \"tuni\"\n // pulling documents that merely contain those letters somewhere in a description.\n minMatchCharLength: 3,\n threshold: 0.35,\n};\n\nexport type RankedDoc = {\n doc: IndexedDoc;\n highlights?: [number, number][];\n score?: number;\n};\n\nexport const toResult = ({\n doc,\n highlights,\n score,\n}: RankedDoc): SearchResult => ({\n id: doc.id,\n collection: doc.collection,\n description: doc.description,\n docId: doc.docId,\n group: doc.group,\n highlights,\n href: hrefFor(doc),\n icon: doc.icon,\n score,\n title: doc.title,\n});\n\n/** Fuse's inclusive title match indices as sorted, merged `[start, end)` ranges. */\nexport function titleHighlights(\n matches: readonly {\n indices: readonly (readonly [number, number])[];\n key?: string;\n }[] = []\n): [number, number][] {\n const ranges = matches\n .filter(match => match.key === 'title')\n .flatMap(match =>\n match.indices.map(([a, b]) => [a, b + 1] as [number, number])\n )\n .sort((a, b) => a[0] - b[0]);\n const merged: [number, number][] = [];\n for (const range of ranges) {\n const last = merged.at(-1);\n if (last && range[0] <= last[1]) {\n last[1] = Math.max(last[1], range[1]);\n } else {\n merged.push([...range]);\n }\n }\n return merged;\n}\n\n/**\n * Rank documents against a query.\n *\n * Fuse gives fuzzy tolerance for typos and plurals. Its score is then divided by the collection\n * weight so a configured priority can lift an otherwise equal match — cheaper and far more\n * predictable than trying to express priority through Fuse's own field weights.\n *\n * Fuse matches the query as one phrase, so a word the title lacks or a different word order\n * (\"royal palm mauritius\", \"seychelles hilton\") matches nothing. A multi-word query therefore also\n * matches word by word, and those hits follow every phrase hit: the phrase ranking stays as it was,\n * and the words only add what it missed.\n */\nexport function rankDocs({\n docs,\n fields = DEFAULT_FIELDS,\n fuzzy,\n query,\n}: {\n docs: IndexedDoc[];\n fields?: SearchField[];\n fuzzy?: FuzzyOptions;\n query: string;\n}): (RankedDoc & { score: number })[] {\n const trimmed = query.trim();\n if (!trimmed) {\n return [];\n }\n\n const options = { ...DEFAULT_FUZZY, ...fuzzy };\n const search = (useTokenSearch: boolean) =>\n new Fuse(docs, {\n distance: options.distance,\n ignoreLocation: true,\n includeMatches: true,\n includeScore: true,\n keys: fields.map(field => ({\n name: field.name,\n weight: field.weight ?? 1,\n })),\n minMatchCharLength: options.minMatchCharLength,\n threshold: options.threshold,\n useTokenSearch,\n })\n .search(trimmed)\n .map(hit => ({\n doc: hit.item,\n highlights: titleHighlights(hit.matches),\n // Fuse scores are \"lower is better\", so dividing by weight promotes a heavier collection.\n score: (hit.score ?? 1) / (hit.item.weight || 1),\n }))\n .sort((a, b) => a.score - b.score);\n\n const phrase = search(false);\n if (!/\\s/.test(trimmed)) {\n return phrase;\n }\n const found = new Set(phrase.map(hit => hit.doc));\n return [...phrase, ...search(true).filter(hit => !found.has(hit.doc))];\n}\n\n/** Bucket ranked documents into their groups, applying each group's cap. */\nexport function groupResults({\n groups,\n ranked,\n}: {\n groups: SearchGroup[];\n ranked: RankedDoc[];\n}): GroupedResults {\n const bySlug = new Map(groups.map(group => [group.slug, group]));\n const grouped: GroupedResults = {};\n\n for (const group of groups) {\n grouped[group.slug] = [];\n }\n\n for (const hit of ranked) {\n const group = bySlug.get(hit.doc.group);\n if (!group) {\n continue;\n }\n\n const bucket = grouped[group.slug];\n if (group.limit !== undefined && bucket.length >= group.limit) {\n continue;\n }\n\n bucket.push(toResult(hit));\n }\n\n return grouped;\n}\n\n/**\n * The empty-query preset.\n *\n * Ordered by collection weight and then alphabetically, and only for groups that opted in. Callers\n * that want a curated list should configure weights — this is explicitly not popularity-ranked,\n * and saying so here is cheaper than a client learning it later.\n */\nexport function presetResults({\n docs,\n groups,\n}: {\n docs: IndexedDoc[];\n groups: SearchGroup[];\n}): GroupedResults {\n const eligible = new Set(\n groups\n .filter(group => group.showWhenEmpty !== false)\n .map(group => group.slug)\n );\n\n const ordered = docs\n .filter(doc => eligible.has(doc.group))\n .sort((a, b) => b.weight - a.weight || a.title.localeCompare(b.title))\n .map(doc => ({ doc }));\n\n const grouped = groupResults({ groups, ranked: ordered });\n\n for (const group of groups) {\n if (!eligible.has(group.slug)) {\n grouped[group.slug] = [];\n }\n }\n\n return grouped;\n}\n"],"names":["Fuse","hrefFor","DEFAULT_FIELDS","name","weight","DEFAULT_FUZZY","distance","minMatchCharLength","threshold","toResult","doc","highlights","score","id","collection","description","docId","group","href","icon","title","titleHighlights","matches","ranges","filter","match","key","flatMap","indices","map","a","b","sort","merged","range","last","at","Math","max","push","rankDocs","docs","fields","fuzzy","query","trimmed","trim","options","search","useTokenSearch","ignoreLocation","includeMatches","includeScore","keys","field","hit","item","phrase","test","found","Set","has","groupResults","groups","ranked","bySlug","Map","slug","grouped","get","bucket","limit","undefined","length","presetResults","eligible","showWhenEmpty","ordered","localeCompare"],"mappings":"AAAA,OAAOA,UAAU,UAAU;AAC3B,SAASC,OAAO,QAAQ,eAAe;AAUvC,OAAO,MAAMC,iBAAgC;IAC3C;QAAEC,MAAM;QAASC,QAAQ;IAAE;IAC3B;QAAED,MAAM;QAAQC,QAAQ;IAAI;IAC5B;QAAED,MAAM;QAAeC,QAAQ;IAAI;CACpC,CAAC;AAEF,OAAO,MAAMC,gBAAwC;IACnDC,UAAU;IACV,4FAA4F;IAC5F,kFAAkF;IAClFC,oBAAoB;IACpBC,WAAW;AACb,EAAE;AAQF,OAAO,MA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
2
  import type { SearchIndexCache } from './cache.js';
3
- import type { GroupedResults, IndexReport, SearchPluginConfig } from './types.js';
3
+ import type { GroupedResults, IndexReport, PaginatedResults, SearchPluginConfig, SearchQuery } from './types.js';
4
+ /**
5
+ * The collection plugin-search maintains. Reading it rather than the source collections is the
6
+ * whole point: one query instead of one per collection, and sync is already solved by the hooks
7
+ * plugin-search installs.
8
+ */
9
+ export declare const DEFAULT_INDEX_COLLECTION = "search";
4
10
  export type SearchService = {
5
11
  inspect: () => Promise<IndexReport>;
12
+ /**
13
+ * Flat, ranked and paginated, ignoring group caps: for a results page, or for the ranked
14
+ * `docId`s a filtered archive narrows with its own `where`.
15
+ */
16
+ query: (query: SearchQuery) => Promise<PaginatedResults>;
6
17
  reindex: () => Promise<{
7
18
  indexed: number;
8
19
  skipped: number;
package/dist/resolve.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { projectDocs } from './project.js';
2
- import { groupResults, presetResults, rankDocs } from './rank.js';
2
+ import { groupResults, presetResults, rankDocs, toResult } from './rank.js';
3
3
  /**
4
4
  * The collection plugin-search maintains. Reading it rather than the source collections is the
5
5
  * whole point: one query instead of one per collection, and sync is already solved by the hooks
6
6
  * plugin-search installs.
7
- */ const SEARCH_COLLECTION = 'search';
7
+ */ export const DEFAULT_INDEX_COLLECTION = 'search';
8
8
  /**
9
9
  * Build the read path.
10
10
  *
@@ -15,16 +15,40 @@ import { groupResults, presetResults, rankDocs } from './rank.js';
15
15
  * editor rather than a developer.
16
16
  */ export function createSearchService({ cache, config, payload }) {
17
17
  const decode = config.decodeEntities ?? true;
18
+ /** `${collection}:${id}` for every document an `excludeField` checkbox hides. */ const hiddenDocs = async ()=>{
19
+ const keys = await Promise.all(config.collections.filter((entry)=>entry.excludeField).map(async (entry)=>{
20
+ const { docs } = await payload.find({
21
+ collection: entry.slug,
22
+ depth: 0,
23
+ limit: 0,
24
+ pagination: false,
25
+ select: {
26
+ [entry.excludeField]: true
27
+ },
28
+ where: {
29
+ [entry.excludeField]: {
30
+ equals: true
31
+ }
32
+ }
33
+ });
34
+ return docs.map((doc)=>`${entry.slug}:${doc.id}`);
35
+ }));
36
+ return new Set(keys.flat());
37
+ };
18
38
  const load = async ()=>{
19
- const response = await payload.find({
20
- collection: SEARCH_COLLECTION,
21
- depth: 0,
22
- limit: 0,
23
- pagination: false
24
- });
39
+ const [response, hidden] = await Promise.all([
40
+ payload.find({
41
+ collection: config.indexCollection ?? DEFAULT_INDEX_COLLECTION,
42
+ depth: 0,
43
+ limit: 0,
44
+ pagination: false
45
+ }),
46
+ hiddenDocs()
47
+ ]);
25
48
  return projectDocs({
26
49
  collections: config.collections,
27
50
  decode,
51
+ hidden,
28
52
  rows: response.docs
29
53
  });
30
54
  };
@@ -52,6 +76,25 @@ import { groupResults, presetResults, rankDocs } from './rank.js';
52
76
  total: fresh.length
53
77
  };
54
78
  },
79
+ async query ({ collections, limit = 10, page = 1, q }) {
80
+ const trimmed = q.trim();
81
+ const size = Math.min(Math.max(1, Math.floor(limit) || 10), 100);
82
+ const current = Math.max(1, Math.floor(page) || 1);
83
+ const wanted = collections?.length ? new Set(collections) : null;
84
+ const ranked = trimmed ? rankDocs({
85
+ docs: (await docs()).filter((doc)=>!wanted || wanted.has(doc.collection)),
86
+ fields: config.fields,
87
+ fuzzy: config.fuzzy,
88
+ query: trimmed
89
+ }) : [];
90
+ return {
91
+ docs: ranked.slice((current - 1) * size, current * size).map(toResult),
92
+ limit: size,
93
+ page: current,
94
+ totalDocs: ranked.length,
95
+ totalPages: Math.ceil(ranked.length / size)
96
+ };
97
+ },
55
98
  async reindex () {
56
99
  cache.invalidate();
57
100
  const { docs: fresh, skipped } = await load();
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/resolve.ts"],"sourcesContent":["import type { Payload } from 'payload';\n\nimport type { SearchIndexCache } from './cache.js';\nimport type { SearchDoc } from './project.js';\nimport { projectDocs } from './project.js';\nimport { groupResults, presetResults, rankDocs } from './rank.js';\nimport type {\n GroupedResults,\n IndexedDoc,\n IndexReport,\n SearchPluginConfig,\n} from './types.js';\n\n/**\n * The collection plugin-search maintains. Reading it rather than the source collections is the\n * whole point: one query instead of one per collection, and sync is already solved by the hooks\n * plugin-search installs.\n */\nconst SEARCH_COLLECTION = 'search';\n\nexport type SearchService = {\n inspect: () => Promise<IndexReport>;\n reindex: () => Promise<{ indexed: number; skipped: number }>;\n search: (query: string) => Promise<GroupedResults>;\n};\n\n/**\n * Build the read path.\n *\n * The projection is cached, so a burst of keystrokes costs one index read rather than one per\n * request per collection. `reindex` drops the snapshot and rebuilds immediately, which is what\n * makes the CMS button meaningful — hook-driven sync always desyncs eventually (a bulk migration\n * write, a restore from backup, a failed hook), and the recovery path has to be operable by an\n * editor rather than a developer.\n */\nexport function createSearchService({\n cache,\n config,\n payload,\n}: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n payload: Payload;\n}): SearchService {\n const decode = config.decodeEntities ?? true;\n\n const load = async (): Promise<{\n docs: IndexedDoc[];\n skipped: IndexReport['skipped'];\n }> => {\n const response = await payload.find({\n collection: SEARCH_COLLECTION as never,\n depth: 0,\n limit: 0,\n pagination: false,\n });\n\n return projectDocs({\n collections: config.collections,\n decode,\n rows: response.docs as SearchDoc[],\n });\n };\n\n const docs = async (): Promise<IndexedDoc[]> => {\n const cached = cache.get();\n if (cached) {\n return cached;\n }\n\n const { docs: fresh } = await load();\n cache.set(fresh);\n return fresh;\n };\n\n return {\n async inspect() {\n const { docs: fresh, skipped } = await load();\n cache.set(fresh);\n\n return {\n builtAt: cache.builtAt()\n ? new Date(cache.builtAt() as number).toISOString()\n : null,\n collections: config.collections.map(entry => ({\n slug: entry.slug,\n excluded: skipped.filter(row => row.slug === entry.slug).length,\n indexed: fresh.filter(doc => doc.collection === entry.slug).length,\n })),\n skipped,\n total: fresh.length,\n };\n },\n\n async reindex() {\n cache.invalidate();\n const { docs: fresh, skipped } = await load();\n cache.set(fresh);\n return { indexed: fresh.length, skipped: skipped.length };\n },\n\n async search(query: string) {\n const all = await docs();\n const trimmed = query.trim();\n\n if (!trimmed) {\n return presetResults({ docs: all, groups: config.groups });\n }\n\n return groupResults({\n groups: config.groups,\n ranked: rankDocs({\n docs: all,\n fields: config.fields,\n fuzzy: config.fuzzy,\n query: trimmed,\n }),\n });\n },\n };\n}\n"],"names":["projectDocs","groupResults","presetResults","rankDocs","SEARCH_COLLECTION","createSearchService","cache","config","payload","decode","decodeEntities","load","response","find","collection","depth","limit","pagination","collections","rows","docs","cached","get","fresh","set","inspect","skipped","builtAt","Date","toISOString","map","entry","slug","excluded","filter","row","length","indexed","doc","total","reindex","invalidate","search","query","all","trimmed","trim","groups","ranked","fields","fuzzy"],"mappings":"AAIA,SAASA,WAAW,QAAQ,eAAe;AAC3C,SAASC,YAAY,EAAEC,aAAa,EAAEC,QAAQ,QAAQ,YAAY;AAQlE;;;;CAIC,GACD,MAAMC,oBAAoB;AAQ1B;;;;;;;;CAQC,GACD,OAAO,SAASC,oBAAoB,EAClCC,KAAK,EACLC,MAAM,EACNC,OAAO,EAKR;IACC,MAAMC,SAASF,OAAOG,cAAc,IAAI;IAExC,MAAMC,OAAO;QAIX,MAAMC,WAAW,MAAMJ,QAAQK,IAAI,CAAC;YAClCC,YAAYV;YACZW,OAAO;YACPC,OAAO;YACPC,YAAY;QACd;QAEA,OAAOjB,YAAY;YACjBkB,aAAaX,OAAOW,WAAW;YAC/BT;YACAU,MAAMP,SAASQ,IAAI;QACrB;IACF;IAEA,MAAMA,OAAO;QACX,MAAMC,SAASf,MAAMgB,GAAG;QACxB,IAAID,QAAQ;YACV,OAAOA;QACT;QAEA,MAAM,EAAED,MAAMG,KAAK,EAAE,GAAG,MAAMZ;QAC9BL,MAAMkB,GAAG,CAACD;QACV,OAAOA;IACT;IAEA,OAAO;QACL,MAAME;YACJ,MAAM,EAAEL,MAAMG,KAAK,EAAEG,OAAO,EAAE,GAAG,MAAMf;YACvCL,MAAMkB,GAAG,CAACD;YAEV,OAAO;gBACLI,SAASrB,MAAMqB,OAAO,KAClB,IAAIC,KAAKtB,MAAMqB,OAAO,IAAcE,WAAW,KAC/C;gBACJX,aAAaX,OAAOW,WAAW,CAACY,GAAG,CAACC,CAAAA,QAAU,CAAA;wBAC5CC,MAAMD,MAAMC,IAAI;wBAChBC,UAAUP,QAAQQ,MAAM,CAACC,CAAAA,MAAOA,IAAIH,IAAI,KAAKD,MAAMC,IAAI,EAAEI,MAAM;wBAC/DC,SAASd,MAAMW,MAAM,CAACI,CAAAA,MAAOA,IAAIxB,UAAU,KAAKiB,MAAMC,IAAI,EAAEI,MAAM;oBACpE,CAAA;gBACAV;gBACAa,OAAOhB,MAAMa,MAAM;YACrB;QACF;QAEA,MAAMI;YACJlC,MAAMmC,UAAU;YAChB,MAAM,EAAErB,MAAMG,KAAK,EAAEG,OAAO,EAAE,GAAG,MAAMf;YACvCL,MAAMkB,GAAG,CAACD;YACV,OAAO;gBAAEc,SAASd,MAAMa,MAAM;gBAAEV,SAASA,QAAQU,MAAM;YAAC;QAC1D;QAEA,MAAMM,QAAOC,KAAa;YACxB,MAAMC,MAAM,MAAMxB;YAClB,MAAMyB,UAAUF,MAAMG,IAAI;YAE1B,IAAI,CAACD,SAAS;gBACZ,OAAO3C,cAAc;oBAAEkB,MAAMwB;oBAAKG,QAAQxC,OAAOwC,MAAM;gBAAC;YAC1D;YAEA,OAAO9C,aAAa;gBAClB8C,QAAQxC,OAAOwC,MAAM;gBACrBC,QAAQ7C,SAAS;oBACfiB,MAAMwB;oBACNK,QAAQ1C,OAAO0C,MAAM;oBACrBC,OAAO3C,OAAO2C,KAAK;oBACnBP,OAAOE;gBACT;YACF;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../src/resolve.ts"],"sourcesContent":["import type { Payload } from 'payload';\n\nimport type { SearchIndexCache } from './cache.js';\nimport { projectDocs } from './project.js';\nimport { groupResults, presetResults, rankDocs, toResult } from './rank.js';\nimport type {\n GroupedResults,\n IndexedDoc,\n IndexReport,\n PaginatedResults,\n SearchDoc,\n SearchPluginConfig,\n SearchQuery,\n} from './types.js';\n\n/**\n * The collection plugin-search maintains. Reading it rather than the source collections is the\n * whole point: one query instead of one per collection, and sync is already solved by the hooks\n * plugin-search installs.\n */\nexport const DEFAULT_INDEX_COLLECTION = 'search';\n\nexport type SearchService = {\n inspect: () => Promise<IndexReport>;\n /**\n * Flat, ranked and paginated, ignoring group caps: for a results page, or for the ranked\n * `docId`s a filtered archive narrows with its own `where`.\n */\n query: (query: SearchQuery) => Promise<PaginatedResults>;\n reindex: () => Promise<{ indexed: number; skipped: number }>;\n search: (query: string) => Promise<GroupedResults>;\n};\n\n/**\n * Build the read path.\n *\n * The projection is cached, so a burst of keystrokes costs one index read rather than one per\n * request per collection. `reindex` drops the snapshot and rebuilds immediately, which is what\n * makes the CMS button meaningful — hook-driven sync always desyncs eventually (a bulk migration\n * write, a restore from backup, a failed hook), and the recovery path has to be operable by an\n * editor rather than a developer.\n */\nexport function createSearchService({\n cache,\n config,\n payload,\n}: {\n cache: SearchIndexCache;\n config: SearchPluginConfig;\n payload: Payload;\n}): SearchService {\n const decode = config.decodeEntities ?? true;\n\n /** `${collection}:${id}` for every document an `excludeField` checkbox hides. */\n const hiddenDocs = async (): Promise<Set<string>> => {\n const keys = await Promise.all(\n config.collections\n .filter(entry => entry.excludeField)\n .map(async entry => {\n const { docs } = await payload.find({\n collection: entry.slug,\n depth: 0,\n limit: 0,\n pagination: false,\n select: { [entry.excludeField as string]: true },\n where: { [entry.excludeField as string]: { equals: true } },\n });\n return docs.map(doc => `${entry.slug}:${doc.id}`);\n })\n );\n return new Set(keys.flat());\n };\n\n const load = async (): Promise<{\n docs: IndexedDoc[];\n skipped: IndexReport['skipped'];\n }> => {\n const [response, hidden] = await Promise.all([\n payload.find({\n collection: (config.indexCollection ??\n DEFAULT_INDEX_COLLECTION) as never,\n depth: 0,\n limit: 0,\n pagination: false,\n }),\n hiddenDocs(),\n ]);\n\n return projectDocs({\n collections: config.collections,\n decode,\n hidden,\n rows: response.docs as SearchDoc[],\n });\n };\n\n const docs = async (): Promise<IndexedDoc[]> => {\n const cached = cache.get();\n if (cached) {\n return cached;\n }\n\n const { docs: fresh } = await load();\n cache.set(fresh);\n return fresh;\n };\n\n return {\n async inspect() {\n const { docs: fresh, skipped } = await load();\n cache.set(fresh);\n\n return {\n builtAt: cache.builtAt()\n ? new Date(cache.builtAt() as number).toISOString()\n : null,\n collections: config.collections.map(entry => ({\n slug: entry.slug,\n excluded: skipped.filter(row => row.slug === entry.slug).length,\n indexed: fresh.filter(doc => doc.collection === entry.slug).length,\n })),\n skipped,\n total: fresh.length,\n };\n },\n\n async query({ collections, limit = 10, page = 1, q }) {\n const trimmed = q.trim();\n const size = Math.min(Math.max(1, Math.floor(limit) || 10), 100);\n const current = Math.max(1, Math.floor(page) || 1);\n const wanted = collections?.length ? new Set(collections) : null;\n const ranked = trimmed\n ? rankDocs({\n docs: (await docs()).filter(\n doc => !wanted || wanted.has(doc.collection)\n ),\n fields: config.fields,\n fuzzy: config.fuzzy,\n query: trimmed,\n })\n : [];\n\n return {\n docs: ranked.slice((current - 1) * size, current * size).map(toResult),\n limit: size,\n page: current,\n totalDocs: ranked.length,\n totalPages: Math.ceil(ranked.length / size),\n };\n },\n\n async reindex() {\n cache.invalidate();\n const { docs: fresh, skipped } = await load();\n cache.set(fresh);\n return { indexed: fresh.length, skipped: skipped.length };\n },\n\n async search(query: string) {\n const all = await docs();\n const trimmed = query.trim();\n\n if (!trimmed) {\n return presetResults({ docs: all, groups: config.groups });\n }\n\n return groupResults({\n groups: config.groups,\n ranked: rankDocs({\n docs: all,\n fields: config.fields,\n fuzzy: config.fuzzy,\n query: trimmed,\n }),\n });\n },\n };\n}\n"],"names":["projectDocs","groupResults","presetResults","rankDocs","toResult","DEFAULT_INDEX_COLLECTION","createSearchService","cache","config","payload","decode","decodeEntities","hiddenDocs","keys","Promise","all","collections","filter","entry","excludeField","map","docs","find","collection","slug","depth","limit","pagination","select","where","equals","doc","id","Set","flat","load","response","hidden","indexCollection","rows","cached","get","fresh","set","inspect","skipped","builtAt","Date","toISOString","excluded","row","length","indexed","total","query","page","q","trimmed","trim","size","Math","min","max","floor","current","wanted","ranked","has","fields","fuzzy","slice","totalDocs","totalPages","ceil","reindex","invalidate","search","groups"],"mappings":"AAGA,SAASA,WAAW,QAAQ,eAAe;AAC3C,SAASC,YAAY,EAAEC,aAAa,EAAEC,QAAQ,EAAEC,QAAQ,QAAQ,YAAY;AAW5E;;;;CAIC,GACD,OAAO,MAAMC,2BAA2B,SAAS;AAajD;;;;;;;;CAQC,GACD,OAAO,SAASC,oBAAoB,EAClCC,KAAK,EACLC,MAAM,EACNC,OAAO,EAKR;IACC,MAAMC,SAASF,OAAOG,cAAc,IAAI;IAExC,+EAA+E,GAC/E,MAAMC,aAAa;QACjB,MAAMC,OAAO,MAAMC,QAAQC,GAAG,CAC5BP,OAAOQ,WAAW,CACfC,MAAM,CAACC,CAAAA,QAASA,MAAMC,YAAY,EAClCC,GAAG,CAAC,OAAMF;YACT,MAAM,EAAEG,IAAI,EAAE,GAAG,MAAMZ,QAAQa,IAAI,CAAC;gBAClCC,YAAYL,MAAMM,IAAI;gBACtBC,OAAO;gBACPC,OAAO;gBACPC,YAAY;gBACZC,QAAQ;oBAAE,CAACV,MAAMC,YAAY,CAAW,EAAE;gBAAK;gBAC/CU,OAAO;oBAAE,CAACX,MAAMC,YAAY,CAAW,EAAE;wBAAEW,QAAQ;oBAAK;gBAAE;YAC5D;YACA,OAAOT,KAAKD,GAAG,CAACW,CAAAA,MAAO,GAAGb,MAAMM,IAAI,CAAC,CAAC,EAAEO,IAAIC,EAAE,EAAE;QAClD;QAEJ,OAAO,IAAIC,IAAIpB,KAAKqB,IAAI;IAC1B;IAEA,MAAMC,OAAO;QAIX,MAAM,CAACC,UAAUC,OAAO,GAAG,MAAMvB,QAAQC,GAAG,CAAC;YAC3CN,QAAQa,IAAI,CAAC;gBACXC,YAAaf,OAAO8B,eAAe,IACjCjC;gBACFoB,OAAO;gBACPC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Ls are built, how strongly it ranks, and which documents are held back.
8
8
  */
9
9
  export type SearchableCollection = {
10
+ /**
11
+ * A checkbox on the source collection (e.g. `excludeFromSearch`) that hides a document from
12
+ * search. Resolved once per projection build, so it costs nothing per request.
13
+ */
14
+ excludeField?: string;
10
15
  /** Documents whose slug appears here are never returned. */
11
16
  excludeSlugs?: string[];
12
17
  /** Group key this collection's results are filed under. Must match a configured group. */
13
18
  group: string;
19
+ /**
20
+ * Build a result's URL from its raw index row, for URLs `path` + slug can't express (nested
21
+ * paths). Add the data it needs to the row with plugin-search's `beforeSync`. Return nothing to
22
+ * fall back to `path`.
23
+ */
24
+ href?: (row: SearchDoc) => null | string | undefined;
14
25
  /** Opaque icon token passed through to the consumer's own icon map. */
15
26
  icon?: string;
16
27
  /**
@@ -89,6 +100,8 @@ export type SearchPluginConfig = {
89
100
  fields?: SearchField[];
90
101
  fuzzy?: FuzzyOptions;
91
102
  groups: SearchGroup[];
103
+ /** Slug of the collection plugin-search maintains (its `searchOverrides.slug`). */
104
+ indexCollection?: string;
92
105
  /**
93
106
  * Rate-limit the public track endpoint per client IP, using Payload's KV store. Default
94
107
  * `{ limit: 30, window: 60 }`; `false` turns it off. Set `trustedProxies` (see
@@ -104,8 +117,13 @@ export type SearchPluginConfig = {
104
117
  export type IndexedDoc = {
105
118
  collection: string;
106
119
  description?: string;
120
+ /** The source document's ID. */
121
+ docId: string;
107
122
  group: string;
123
+ /** Set when the collection's `href` built one; otherwise `path` + slug. */
124
+ href?: string;
108
125
  icon?: string;
126
+ /** `${collection}-${docId}`, unique across collections. */
109
127
  id: string;
110
128
  path: string;
111
129
  slug: string;
@@ -114,7 +132,15 @@ export type IndexedDoc = {
114
132
  };
115
133
  export type SearchResult = {
116
134
  collection: string;
135
+ description?: string;
136
+ /** The source document's ID, for querying the source collection (e.g. `where: { id: { in } }`). */
137
+ docId: string;
117
138
  group: string;
139
+ /**
140
+ * Matched character ranges in `title`, as `[start, end)` pairs, for bolding the match. Absent on
141
+ * the empty-query preset.
142
+ */
143
+ highlights?: [number, number][];
118
144
  href: string;
119
145
  icon?: string;
120
146
  id: string;
@@ -123,6 +149,38 @@ export type SearchResult = {
123
149
  title: string;
124
150
  };
125
151
  export type GroupedResults = Record<string, SearchResult[]>;
152
+ /** Options for a flat, paginated query: a results page, or ranked IDs for a filtered archive. */
153
+ export type SearchQuery = {
154
+ /** Only these collections. Default: every configured collection. */
155
+ collections?: string[];
156
+ /** Results per page, capped at 100. Default 10. */
157
+ limit?: number;
158
+ /** 1-based. Default 1. */
159
+ page?: number;
160
+ q: string;
161
+ };
162
+ export type PaginatedResults = {
163
+ docs: SearchResult[];
164
+ limit: number;
165
+ page: number;
166
+ totalDocs: number;
167
+ totalPages: number;
168
+ };
169
+ /** A row as it comes back from the plugin-search index collection. */
170
+ export type SearchDoc = {
171
+ [key: string]: unknown;
172
+ doc?: {
173
+ relationTo?: string;
174
+ value?: number | string;
175
+ } | null;
176
+ id?: number | string;
177
+ meta?: {
178
+ description?: null | string;
179
+ title?: null | string;
180
+ } | null;
181
+ slug?: null | string;
182
+ title?: null | string;
183
+ };
126
184
  /** What the inspector reports, so "is this searchable" stops needing a code read. */
127
185
  export type IndexReport = {
128
186
  builtAt: null | string;
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { RateLimitOptions } from '@foundrykit/rate-limit';\nimport 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 \"&amp;\" 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 /**\n * Rate-limit the public track endpoint per client IP, using Payload's KV store. Default\n * `{ limit: 30, window: 60 }`; `false` turns it off. Set `trustedProxies` (see\n * `@foundrykit/rate-limit`) or every visitor shares one bucket.\n */\n rateLimit?:\n | false\n | Partial<Pick<RateLimitOptions, 'limit' | 'window' | 'trustedProxies'>>;\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":"AA2IA,mFAAmF,GACnF,WAaE"}
1
+ {"version":3,"sources":["../src/types.ts"],"sourcesContent":["import type { RateLimitOptions } from '@foundrykit/rate-limit';\nimport 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 /**\n * A checkbox on the source collection (e.g. `excludeFromSearch`) that hides a document from\n * search. Resolved once per projection build, so it costs nothing per request.\n */\n excludeField?: string;\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 /**\n * Build a result's URL from its raw index row, for URLs `path` + slug can't express (nested\n * paths). Add the data it needs to the row with plugin-search's `beforeSync`. Return nothing to\n * fall back to `path`.\n */\n href?: (row: SearchDoc) => null | string | undefined;\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 \"&amp;\" 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 /** Slug of the collection plugin-search maintains (its `searchOverrides.slug`). */\n indexCollection?: string;\n /**\n * Rate-limit the public track endpoint per client IP, using Payload's KV store. Default\n * `{ limit: 30, window: 60 }`; `false` turns it off. Set `trustedProxies` (see\n * `@foundrykit/rate-limit`) or every visitor shares one bucket.\n */\n rateLimit?:\n | false\n | Partial<Pick<RateLimitOptions, 'limit' | 'window' | 'trustedProxies'>>;\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 /** The source document's ID. */\n docId: string;\n group: string;\n /** Set when the collection's `href` built one; otherwise `path` + slug. */\n href?: string;\n icon?: string;\n /** `${collection}-${docId}`, unique across collections. */\n id: string;\n path: string;\n slug: string;\n title: string;\n weight: number;\n};\n\nexport type SearchResult = {\n collection: string;\n description?: string;\n /** The source document's ID, for querying the source collection (e.g. `where: { id: { in } }`). */\n docId: string;\n group: string;\n /**\n * Matched character ranges in `title`, as `[start, end)` pairs, for bolding the match. Absent on\n * the empty-query preset.\n */\n highlights?: [number, number][];\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/** Options for a flat, paginated query: a results page, or ranked IDs for a filtered archive. */\nexport type SearchQuery = {\n /** Only these collections. Default: every configured collection. */\n collections?: string[];\n /** Results per page, capped at 100. Default 10. */\n limit?: number;\n /** 1-based. Default 1. */\n page?: number;\n q: string;\n};\n\nexport type PaginatedResults = {\n docs: SearchResult[];\n limit: number;\n page: number;\n totalDocs: number;\n totalPages: number;\n};\n\n/** A row as it comes back from the plugin-search index collection. */\nexport type SearchDoc = {\n [key: string]: unknown;\n doc?: { relationTo?: string; value?: number | string } | null;\n id?: number | string;\n meta?: { description?: null | string; title?: null | string } | null;\n slug?: null | string;\n title?: null | string;\n};\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":"AAkMA,mFAAmF,GACnF,WAaE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foundrykit/search-plugin",
3
- "version": "0.3.0",
3
+ "version": "0.4.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",