@foundrykit/search-plugin 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +151 -0
  3. package/dist/analytics.d.ts +36 -0
  4. package/dist/analytics.js +71 -0
  5. package/dist/analytics.js.map +1 -0
  6. package/dist/cache.d.ts +21 -0
  7. package/dist/cache.js +42 -0
  8. package/dist/cache.js.map +1 -0
  9. package/dist/collections/SearchEvents.d.ts +15 -0
  10. package/dist/collections/SearchEvents.js +62 -0
  11. package/dist/collections/SearchEvents.js.map +1 -0
  12. package/dist/components/SearchDashboard.d.ts +13 -0
  13. package/dist/components/SearchDashboard.js +170 -0
  14. package/dist/components/SearchDashboard.js.map +1 -0
  15. package/dist/components/useSearchHotkey.d.ts +15 -0
  16. package/dist/components/useSearchHotkey.js +71 -0
  17. package/dist/components/useSearchHotkey.js.map +1 -0
  18. package/dist/decodeEntities.d.ts +12 -0
  19. package/dist/decodeEntities.js +13 -0
  20. package/dist/decodeEntities.js.map +1 -0
  21. package/dist/endpoints/handlers.d.ts +24 -0
  22. package/dist/endpoints/handlers.js +95 -0
  23. package/dist/endpoints/handlers.js.map +1 -0
  24. package/dist/exports/client.d.ts +1 -0
  25. package/dist/exports/client.js +3 -0
  26. package/dist/exports/client.js.map +1 -0
  27. package/dist/exports/rsc.d.ts +1 -0
  28. package/dist/exports/rsc.js +3 -0
  29. package/dist/exports/rsc.js.map +1 -0
  30. package/dist/index.d.ts +21 -0
  31. package/dist/index.js +79 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/options.d.ts +11 -0
  34. package/dist/options.js +42 -0
  35. package/dist/options.js.map +1 -0
  36. package/dist/project.d.ts +37 -0
  37. package/dist/project.js +82 -0
  38. package/dist/project.js.map +1 -0
  39. package/dist/rank.d.ts +38 -0
  40. package/dist/rank.js +110 -0
  41. package/dist/rank.js.map +1 -0
  42. package/dist/resolve.d.ts +25 -0
  43. package/dist/resolve.js +86 -0
  44. package/dist/resolve.js.map +1 -0
  45. package/dist/types.d.ts +125 -0
  46. package/dist/types.js +3 -0
  47. package/dist/types.js.map +1 -0
  48. package/package.json +96 -0
@@ -0,0 +1,15 @@
1
+ /**
2
+ * True when the event originated inside something the user is typing into.
3
+ *
4
+ * A search shortcut must not fire while the user is in an input, textarea or contenteditable. This
5
+ * matters specifically for Ctrl+K, which is Lexical's "insert link" binding — and Lexical is
6
+ * Payload's own editor, so a plugin that got this wrong would break the admin panel it ships with.
7
+ */
8
+ export declare function isEditableTarget(target: EventTarget | null): boolean;
9
+ /** Cmd+K (macOS) / Ctrl+K (Windows, Linux) to open search from anywhere on the page. */
10
+ export declare function useSearchHotkey(onOpen: () => void): void;
11
+ /**
12
+ * Whether to render the hint as "⌘" or "Ctrl". Resolved after mount so server and client markup
13
+ * match and React does not warn on hydration.
14
+ */
15
+ export declare function useIsAppleDevice(): boolean;
@@ -0,0 +1,71 @@
1
+ 'use client';
2
+ import { useEffect, useState } from 'react';
3
+ /**
4
+ * True when the event originated inside something the user is typing into.
5
+ *
6
+ * A search shortcut must not fire while the user is in an input, textarea or contenteditable. This
7
+ * matters specifically for Ctrl+K, which is Lexical's "insert link" binding — and Lexical is
8
+ * Payload's own editor, so a plugin that got this wrong would break the admin panel it ships with.
9
+ */ export function isEditableTarget(target) {
10
+ if (!(target instanceof HTMLElement)) {
11
+ return false;
12
+ }
13
+ if (target.isContentEditable) {
14
+ return true;
15
+ }
16
+ const tag = target.tagName;
17
+ if (tag === 'TEXTAREA' || tag === 'SELECT') {
18
+ return true;
19
+ }
20
+ if (tag === 'INPUT') {
21
+ // Checkboxes, radios and buttons are inputs but not text entry, so the shortcut is still
22
+ // welcome while they are focused.
23
+ const { type } = target;
24
+ return ![
25
+ 'button',
26
+ 'checkbox',
27
+ 'file',
28
+ 'radio',
29
+ 'range',
30
+ 'reset',
31
+ 'submit'
32
+ ].includes(type);
33
+ }
34
+ return false;
35
+ }
36
+ /** Cmd+K (macOS) / Ctrl+K (Windows, Linux) to open search from anywhere on the page. */ export function useSearchHotkey(onOpen) {
37
+ useEffect(()=>{
38
+ const onKeyDown = (event)=>{
39
+ if (event.key.toLowerCase() !== 'k') {
40
+ return;
41
+ }
42
+ if (!(event.metaKey || event.ctrlKey)) {
43
+ return;
44
+ }
45
+ if (event.altKey || event.shiftKey) {
46
+ return;
47
+ }
48
+ if (isEditableTarget(event.target)) {
49
+ return;
50
+ }
51
+ event.preventDefault();
52
+ onOpen();
53
+ };
54
+ document.addEventListener('keydown', onKeyDown);
55
+ return ()=>document.removeEventListener('keydown', onKeyDown);
56
+ }, [
57
+ onOpen
58
+ ]);
59
+ }
60
+ /**
61
+ * Whether to render the hint as "⌘" or "Ctrl". Resolved after mount so server and client markup
62
+ * match and React does not warn on hydration.
63
+ */ export function useIsAppleDevice() {
64
+ const [isApple, setIsApple] = useState(false);
65
+ useEffect(()=>{
66
+ setIsApple(/mac|iphone|ipad|ipod/i.test(navigator.platform));
67
+ }, []);
68
+ return isApple;
69
+ }
70
+
71
+ //# sourceMappingURL=useSearchHotkey.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/components/useSearchHotkey.ts"],"sourcesContent":["'use client'\n\nimport { useEffect, useState } from 'react'\n\n/**\n * True when the event originated inside something the user is typing into.\n *\n * A search shortcut must not fire while the user is in an input, textarea or contenteditable. This\n * matters specifically for Ctrl+K, which is Lexical's \"insert link\" binding — and Lexical is\n * Payload's own editor, so a plugin that got this wrong would break the admin panel it ships with.\n */\nexport function isEditableTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) {\n return false\n }\n if (target.isContentEditable) {\n return true\n }\n\n const tag = target.tagName\n if (tag === 'TEXTAREA' || tag === 'SELECT') {\n return true\n }\n\n if (tag === 'INPUT') {\n // Checkboxes, radios and buttons are inputs but not text entry, so the shortcut is still\n // welcome while they are focused.\n const { type } = target as HTMLInputElement\n return !['button', 'checkbox', 'file', 'radio', 'range', 'reset', 'submit'].includes(type)\n }\n\n return false\n}\n\n/** Cmd+K (macOS) / Ctrl+K (Windows, Linux) to open search from anywhere on the page. */\nexport function useSearchHotkey(onOpen: () => void): void {\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key.toLowerCase() !== 'k') {\n return\n }\n if (!(event.metaKey || event.ctrlKey)) {\n return\n }\n if (event.altKey || event.shiftKey) {\n return\n }\n if (isEditableTarget(event.target)) {\n return\n }\n\n event.preventDefault()\n onOpen()\n }\n\n document.addEventListener('keydown', onKeyDown)\n return () => document.removeEventListener('keydown', onKeyDown)\n }, [onOpen])\n}\n\n/**\n * Whether to render the hint as \"⌘\" or \"Ctrl\". Resolved after mount so server and client markup\n * match and React does not warn on hydration.\n */\nexport function useIsAppleDevice(): boolean {\n const [isApple, setIsApple] = useState(false)\n\n useEffect(() => {\n setIsApple(/mac|iphone|ipad|ipod/i.test(navigator.platform))\n }, [])\n\n return isApple\n}\n"],"names":["useEffect","useState","isEditableTarget","target","HTMLElement","isContentEditable","tag","tagName","type","includes","useSearchHotkey","onOpen","onKeyDown","event","key","toLowerCase","metaKey","ctrlKey","altKey","shiftKey","preventDefault","document","addEventListener","removeEventListener","useIsAppleDevice","isApple","setIsApple","test","navigator","platform"],"mappings":"AAAA;AAEA,SAASA,SAAS,EAAEC,QAAQ,QAAQ,QAAO;AAE3C;;;;;;CAMC,GACD,OAAO,SAASC,iBAAiBC,MAA0B;IACzD,IAAI,CAAEA,CAAAA,kBAAkBC,WAAU,GAAI;QACpC,OAAO;IACT;IACA,IAAID,OAAOE,iBAAiB,EAAE;QAC5B,OAAO;IACT;IAEA,MAAMC,MAAMH,OAAOI,OAAO;IAC1B,IAAID,QAAQ,cAAcA,QAAQ,UAAU;QAC1C,OAAO;IACT;IAEA,IAAIA,QAAQ,SAAS;QACnB,yFAAyF;QACzF,kCAAkC;QAClC,MAAM,EAAEE,IAAI,EAAE,GAAGL;QACjB,OAAO,CAAC;YAAC;YAAU;YAAY;YAAQ;YAAS;YAAS;YAAS;SAAS,CAACM,QAAQ,CAACD;IACvF;IAEA,OAAO;AACT;AAEA,sFAAsF,GACtF,OAAO,SAASE,gBAAgBC,MAAkB;IAChDX,UAAU;QACR,MAAMY,YAAY,CAACC;YACjB,IAAIA,MAAMC,GAAG,CAACC,WAAW,OAAO,KAAK;gBACnC;YACF;YACA,IAAI,CAAEF,CAAAA,MAAMG,OAAO,IAAIH,MAAMI,OAAO,AAAD,GAAI;gBACrC;YACF;YACA,IAAIJ,MAAMK,MAAM,IAAIL,MAAMM,QAAQ,EAAE;gBAClC;YACF;YACA,IAAIjB,iBAAiBW,MAAMV,MAAM,GAAG;gBAClC;YACF;YAEAU,MAAMO,cAAc;YACpBT;QACF;QAEAU,SAASC,gBAAgB,CAAC,WAAWV;QACrC,OAAO,IAAMS,SAASE,mBAAmB,CAAC,WAAWX;IACvD,GAAG;QAACD;KAAO;AACb;AAEA;;;CAGC,GACD,OAAO,SAASa;IACd,MAAM,CAACC,SAASC,WAAW,GAAGzB,SAAS;IAEvCD,UAAU;QACR0B,WAAW,wBAAwBC,IAAI,CAACC,UAAUC,QAAQ;IAC5D,GAAG,EAAE;IAEL,OAAOJ;AACT"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Decode the HTML entities that survive in titles and labels migrated out of a CMS which stored
3
+ * them encoded.
4
+ *
5
+ * Rich-text renderers decode on the way out, so a body reads correctly while a plain-text surface
6
+ * — a search result, a filter label, a map pin — shows the literal "&". This is why the same
7
+ * stored string can look right on a page and wrong in search.
8
+ *
9
+ * Server-safe: no DOM dependency. `&` is decoded LAST, deliberately — decoding it first would
10
+ * feed the output of one replacement into the next and turn a literal "£" into "£".
11
+ */
12
+ export declare const decodeEntities: (value?: null | string) => string;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Decode the HTML entities that survive in titles and labels migrated out of a CMS which stored
3
+ * them encoded.
4
+ *
5
+ * Rich-text renderers decode on the way out, so a body reads correctly while a plain-text surface
6
+ * — a search result, a filter label, a map pin — shows the literal "&". This is why the same
7
+ * stored string can look right on a page and wrong in search.
8
+ *
9
+ * Server-safe: no DOM dependency. `&` is decoded LAST, deliberately — decoding it first would
10
+ * feed the output of one replacement into the next and turn a literal "£" into "£".
11
+ */ export const decodeEntities = (value)=>(value || '').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#0?39;|&apos;|&rsquo;|&#8217;/g, "'").replace(/&lsquo;|&#8216;/g, "'").replace(/&ldquo;|&#8220;/g, '"').replace(/&rdquo;|&#8221;/g, '"').replace(/&ndash;|&#8211;/g, '–').replace(/&mdash;|&#8212;/g, '—').replace(/&hellip;|&#8230;/g, '…').replace(/&pound;|&#163;/g, '£').replace(/&euro;|&#8364;/g, '€').replace(/&nbsp;|&#160;/g, ' ').replace(/&amp;/g, '&');
12
+
13
+ //# sourceMappingURL=decodeEntities.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/decodeEntities.ts"],"sourcesContent":["/**\n * Decode the HTML entities that survive in titles and labels migrated out of a CMS which stored\n * them encoded.\n *\n * Rich-text renderers decode on the way out, so a body reads correctly while a plain-text surface\n * — a search result, a filter label, a map pin — shows the literal \"&amp;\". This is why the same\n * stored string can look right on a page and wrong in search.\n *\n * Server-safe: no DOM dependency. `&amp;` is decoded LAST, deliberately — decoding it first would\n * feed the output of one replacement into the next and turn a literal \"&amp;pound;\" into \"£\".\n */\nexport const decodeEntities = (value?: null | string): string =>\n (value || '')\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&quot;/g, '\"')\n .replace(/&#0?39;|&apos;|&rsquo;|&#8217;/g, \"'\")\n .replace(/&lsquo;|&#8216;/g, \"'\")\n .replace(/&ldquo;|&#8220;/g, '\"')\n .replace(/&rdquo;|&#8221;/g, '\"')\n .replace(/&ndash;|&#8211;/g, '–')\n .replace(/&mdash;|&#8212;/g, '—')\n .replace(/&hellip;|&#8230;/g, '…')\n .replace(/&pound;|&#163;/g, '£')\n .replace(/&euro;|&#8364;/g, '€')\n .replace(/&nbsp;|&#160;/g, ' ')\n .replace(/&amp;/g, '&')\n"],"names":["decodeEntities","value","replace"],"mappings":"AAAA;;;;;;;;;;CAUC,GACD,OAAO,MAAMA,iBAAiB,CAACC,QAC7B,AAACA,CAAAA,SAAS,EAAC,EACRC,OAAO,CAAC,SAAS,KACjBA,OAAO,CAAC,SAAS,KACjBA,OAAO,CAAC,WAAW,KACnBA,OAAO,CAAC,mCAAmC,KAC3CA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,oBAAoB,KAC5BA,OAAO,CAAC,qBAAqB,KAC7BA,OAAO,CAAC,mBAAmB,KAC3BA,OAAO,CAAC,mBAAmB,KAC3BA,OAAO,CAAC,kBAAkB,KAC1BA,OAAO,CAAC,UAAU,KAAI"}
@@ -0,0 +1,24 @@
1
+ import type { PayloadHandler } from 'payload';
2
+ import type { SearchIndexCache } from '../cache.js';
3
+ import type { SearchPluginConfig } from '../types.js';
4
+ /** GET — grouped, ranked results for `?q=`. Records the search when analytics are enabled. */
5
+ export declare const createSearchHandler: ({ cache, config, }: {
6
+ cache: SearchIndexCache;
7
+ config: SearchPluginConfig;
8
+ }) => PayloadHandler;
9
+ /** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */
10
+ export declare const createReindexHandler: ({ cache, config, requireAdmin, }: {
11
+ cache: SearchIndexCache;
12
+ config: SearchPluginConfig;
13
+ requireAdmin: boolean;
14
+ }) => PayloadHandler;
15
+ /** GET — what is searchable, and why anything missing was left out. */
16
+ export declare const createInspectHandler: ({ cache, config, requireAdmin, }: {
17
+ cache: SearchIndexCache;
18
+ config: SearchPluginConfig;
19
+ requireAdmin: boolean;
20
+ }) => PayloadHandler;
21
+ /** POST — attribute a click to a query, so click-through is measurable. */
22
+ export declare const createTrackHandler: ({ config }: {
23
+ config: SearchPluginConfig;
24
+ }) => PayloadHandler;
@@ -0,0 +1,95 @@
1
+ import { recordSearch } from '../analytics.js';
2
+ import { resolveAnalytics } from '../options.js';
3
+ import { createSearchService } from '../resolve.js';
4
+ const json = (body, status = 200)=>new Response(JSON.stringify(body), {
5
+ headers: {
6
+ 'Content-Type': 'application/json'
7
+ },
8
+ status
9
+ });
10
+ const forbidden = ()=>json({
11
+ error: 'Not permitted'
12
+ }, 403);
13
+ const service = (req, cache, config)=>createSearchService({
14
+ cache,
15
+ config,
16
+ payload: req.payload
17
+ });
18
+ /** GET — grouped, ranked results for `?q=`. Records the search when analytics are enabled. */ export const createSearchHandler = ({ cache, config })=>async (req)=>{
19
+ const query = new URL(req.url ?? '', 'http://localhost').searchParams.get('q') ?? '';
20
+ const results = await service(req, cache, config).search(query);
21
+ const analytics = resolveAnalytics(config.analytics);
22
+ if (analytics.enabled && query.trim()) {
23
+ const resultCount = Object.values(results).reduce((sum, group)=>sum + group.length, 0);
24
+ // Never let a failed write break the search response — analytics are diagnostic, not
25
+ // load-bearing.
26
+ try {
27
+ await recordSearch({
28
+ collectionSlug: analytics.collectionSlug,
29
+ payload: req.payload,
30
+ query,
31
+ resultCount,
32
+ retentionDays: analytics.retentionDays
33
+ });
34
+ } catch (error) {
35
+ req.payload.logger.error({
36
+ err: error,
37
+ msg: 'search-plugin: failed to record search'
38
+ });
39
+ }
40
+ }
41
+ return json(results);
42
+ };
43
+ /** POST — rebuild the projection now. This is the editor-facing recovery path for a desync. */ export const createReindexHandler = ({ cache, config, requireAdmin })=>async (req)=>{
44
+ if (requireAdmin && !req.user) {
45
+ return forbidden();
46
+ }
47
+ const stats = await service(req, cache, config).reindex();
48
+ // Reported rather than silently succeeding: the point is for a non-developer to be able to
49
+ // tell whether it worked.
50
+ return json({
51
+ message: `Reindexed ${stats.indexed} documents, ${stats.skipped} skipped.`,
52
+ ...stats
53
+ });
54
+ };
55
+ /** GET — what is searchable, and why anything missing was left out. */ export const createInspectHandler = ({ cache, config, requireAdmin })=>async (req)=>{
56
+ if (requireAdmin && !req.user) {
57
+ return forbidden();
58
+ }
59
+ return json(await service(req, cache, config).inspect());
60
+ };
61
+ /** POST — attribute a click to a query, so click-through is measurable. */ export const createTrackHandler = ({ config })=>async (req)=>{
62
+ const analytics = resolveAnalytics(config.analytics);
63
+ if (!analytics.enabled) {
64
+ return json({
65
+ tracked: false
66
+ });
67
+ }
68
+ const body = await req.json?.();
69
+ if (!body?.query) {
70
+ return json({
71
+ error: 'query is required'
72
+ }, 400);
73
+ }
74
+ try {
75
+ await recordSearch({
76
+ clickedHref: body.href,
77
+ collectionSlug: analytics.collectionSlug,
78
+ payload: req.payload,
79
+ query: body.query,
80
+ // A click implies the result set was not empty; recorded separately from the search itself.
81
+ resultCount: 1,
82
+ retentionDays: analytics.retentionDays
83
+ });
84
+ } catch (error) {
85
+ req.payload.logger.error({
86
+ err: error,
87
+ msg: 'search-plugin: failed to record click'
88
+ });
89
+ }
90
+ return json({
91
+ tracked: true
92
+ });
93
+ };
94
+
95
+ //# sourceMappingURL=handlers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/endpoints/handlers.ts"],"sourcesContent":["import type { PayloadHandler, PayloadRequest } from 'payload'\n\nimport type { SearchIndexCache } from '../cache.js'\nimport type { SearchPluginConfig } from '../types.js'\n\nimport { recordSearch } from '../analytics.js'\nimport { resolveAnalytics } from '../options.js'\nimport { createSearchService } from '../resolve.js'\n\nconst json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n headers: { 'Content-Type': 'application/json' },\n status,\n })\n\nconst forbidden = () => json({ error: 'Not permitted' }, 403)\n\nconst service = (req: PayloadRequest, cache: SearchIndexCache, config: SearchPluginConfig) =>\n createSearchService({ cache, config, payload: req.payload })\n\n/** GET — grouped, ranked results for `?q=`. Records the search when analytics are enabled. */\nexport const createSearchHandler =\n ({\n cache,\n config,\n }: {\n cache: SearchIndexCache\n config: SearchPluginConfig\n }): PayloadHandler =>\n async (req) => {\n const query = new URL(req.url ?? '', 'http://localhost').searchParams.get('q') ?? ''\n const results = await service(req, cache, config).search(query)\n\n const analytics = resolveAnalytics(config.analytics)\n if (analytics.enabled && query.trim()) {\n const resultCount = Object.values(results).reduce((sum, group) => sum + group.length, 0)\n\n // Never let a failed write break the search response — analytics are diagnostic, not\n // load-bearing.\n try {\n await recordSearch({\n collectionSlug: analytics.collectionSlug,\n payload: req.payload,\n query,\n resultCount,\n retentionDays: analytics.retentionDays,\n })\n } catch (error) {\n req.payload.logger.error({ err: error, msg: 'search-plugin: failed to record search' })\n }\n }\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) {\n return json({ tracked: false })\n }\n\n const body = (await req.json?.()) as { href?: string; query?: string } | undefined\n if (!body?.query) {\n return json({ error: 'query is required' }, 400)\n }\n\n try {\n await recordSearch({\n clickedHref: body.href,\n collectionSlug: analytics.collectionSlug,\n payload: req.payload,\n query: body.query,\n // A click implies the result set was not empty; recorded separately from the search itself.\n resultCount: 1,\n retentionDays: analytics.retentionDays,\n })\n } catch (error) {\n req.payload.logger.error({ err: error, msg: 'search-plugin: failed to record click' })\n }\n\n return json({ tracked: true })\n }\n"],"names":["recordSearch","resolveAnalytics","createSearchService","json","body","status","Response","JSON","stringify","headers","forbidden","error","service","req","cache","config","payload","createSearchHandler","query","URL","url","searchParams","get","results","search","analytics","enabled","trim","resultCount","Object","values","reduce","sum","group","length","collectionSlug","retentionDays","logger","err","msg","createReindexHandler","requireAdmin","user","stats","reindex","message","indexed","skipped","createInspectHandler","inspect","createTrackHandler","tracked","clickedHref","href"],"mappings":"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"}
@@ -0,0 +1 @@
1
+ export { isEditableTarget, useIsAppleDevice, useSearchHotkey } from '../components/useSearchHotkey.js';
@@ -0,0 +1,3 @@
1
+ export { isEditableTarget, useIsAppleDevice, useSearchHotkey } from '../components/useSearchHotkey.js';
2
+
3
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export { isEditableTarget, useIsAppleDevice, useSearchHotkey } from '../components/useSearchHotkey.js'\n"],"names":["isEditableTarget","useIsAppleDevice","useSearchHotkey"],"mappings":"AAAA,SAASA,gBAAgB,EAAEC,gBAAgB,EAAEC,eAAe,QAAQ,mCAAkC"}
@@ -0,0 +1 @@
1
+ export { SearchDashboard } from '../components/SearchDashboard.js';
@@ -0,0 +1,3 @@
1
+ export { SearchDashboard } from '../components/SearchDashboard.js';
2
+
3
+ //# sourceMappingURL=rsc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["export { SearchDashboard } from '../components/SearchDashboard.js'\n"],"names":["SearchDashboard"],"mappings":"AAAA,SAASA,eAAe,QAAQ,mCAAkC"}
@@ -0,0 +1,21 @@
1
+ import type { Config } from 'payload';
2
+ import type { SearchPluginConfig } from './types.js';
3
+ export { aggregateEvents, normalizeQuery, recordSearch } from './analytics.js';
4
+ export { SearchIndexCache, searchIndexCache } from './cache.js';
5
+ export { decodeEntities } from './decodeEntities.js';
6
+ export { hrefFor, projectDocs } from './project.js';
7
+ export { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs } from './rank.js';
8
+ export { createSearchService } from './resolve.js';
9
+ export type * from './types.js';
10
+ /**
11
+ * Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.
12
+ *
13
+ * Layered on top of plugin-search rather than replacing it: that plugin already keeps a `search`
14
+ * collection in sync through afterChange/afterDelete hooks, and sync is the part of an index
15
+ * implementation that rots. This owns the read side — projection, caching, fuzzy ranking,
16
+ * grouping — plus the operational surface an editor needs.
17
+ *
18
+ * Install it AFTER searchPlugin in the plugins array, since it reads the collection that one
19
+ * creates.
20
+ */
21
+ export declare const searchPlugin: (pluginOptions: SearchPluginConfig) => (config: Config) => Config;
package/dist/index.js ADDED
@@ -0,0 +1,79 @@
1
+ import { searchIndexCache } from './cache.js';
2
+ import { createSearchEventsCollection } from './collections/SearchEvents.js';
3
+ import { createInspectHandler, createReindexHandler, createSearchHandler, createTrackHandler } from './endpoints/handlers.js';
4
+ import { assertConfig, resolveAnalytics } from './options.js';
5
+ export { aggregateEvents, normalizeQuery, recordSearch } from './analytics.js';
6
+ export { SearchIndexCache, searchIndexCache } from './cache.js';
7
+ export { decodeEntities } from './decodeEntities.js';
8
+ export { hrefFor, projectDocs } from './project.js';
9
+ export { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs } from './rank.js';
10
+ export { createSearchService } from './resolve.js';
11
+ /**
12
+ * Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.
13
+ *
14
+ * Layered on top of plugin-search rather than replacing it: that plugin already keeps a `search`
15
+ * collection in sync through afterChange/afterDelete hooks, and sync is the part of an index
16
+ * implementation that rots. This owns the read side — projection, caching, fuzzy ranking,
17
+ * grouping — plus the operational surface an editor needs.
18
+ *
19
+ * Install it AFTER searchPlugin in the plugins array, since it reads the collection that one
20
+ * creates.
21
+ */ export const searchPlugin = (pluginOptions)=>(config)=>{
22
+ if (pluginOptions.disabled) {
23
+ return config;
24
+ }
25
+ assertConfig(pluginOptions);
26
+ const analytics = resolveAnalytics(pluginOptions.analytics);
27
+ const prefix = pluginOptions.routePrefix ?? '/site-search';
28
+ const requireAdmin = pluginOptions.requireAdminForOperations ?? true;
29
+ searchIndexCache.configure(pluginOptions.cacheTTL ?? 60_000);
30
+ if (analytics.enabled) {
31
+ config.collections = [
32
+ ...config.collections || [],
33
+ createSearchEventsCollection({
34
+ slug: analytics.collectionSlug
35
+ })
36
+ ];
37
+ }
38
+ config.endpoints = [
39
+ ...config.endpoints || [],
40
+ {
41
+ handler: createSearchHandler({
42
+ cache: searchIndexCache,
43
+ config: pluginOptions
44
+ }),
45
+ method: 'get',
46
+ path: prefix
47
+ },
48
+ {
49
+ handler: createReindexHandler({
50
+ cache: searchIndexCache,
51
+ config: pluginOptions,
52
+ requireAdmin
53
+ }),
54
+ method: 'post',
55
+ path: `${prefix}/reindex`
56
+ },
57
+ {
58
+ handler: createInspectHandler({
59
+ cache: searchIndexCache,
60
+ config: pluginOptions,
61
+ requireAdmin
62
+ }),
63
+ method: 'get',
64
+ path: `${prefix}/inspect`
65
+ },
66
+ ...analytics.enabled ? [
67
+ {
68
+ handler: createTrackHandler({
69
+ config: pluginOptions
70
+ }),
71
+ method: 'post',
72
+ path: `${prefix}/track`
73
+ }
74
+ ] : []
75
+ ];
76
+ return config;
77
+ };
78
+
79
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type { Config } from 'payload'\n\nimport type { SearchPluginConfig } from './types.js'\n\nimport { searchIndexCache } from './cache.js'\nimport { createSearchEventsCollection } from './collections/SearchEvents.js'\nimport {\n createInspectHandler,\n createReindexHandler,\n createSearchHandler,\n createTrackHandler,\n} from './endpoints/handlers.js'\nimport { assertConfig, resolveAnalytics } from './options.js'\n\nexport { aggregateEvents, normalizeQuery, recordSearch } from './analytics.js'\nexport { SearchIndexCache, searchIndexCache } from './cache.js'\nexport { decodeEntities } from './decodeEntities.js'\nexport { hrefFor, projectDocs } from './project.js'\nexport { DEFAULT_FIELDS, DEFAULT_FUZZY, groupResults, presetResults, rankDocs } from './rank.js'\nexport { createSearchService } from './resolve.js'\nexport type * from './types.js'\n\n/**\n * Cached, grouped and ranked site search over the `@payloadcms/plugin-search` index.\n *\n * Layered on top of plugin-search rather than replacing it: that plugin already keeps a `search`\n * collection in sync through afterChange/afterDelete hooks, and sync is the part of an index\n * implementation that rots. This owns the read side — projection, caching, fuzzy ranking,\n * grouping — plus the operational surface an editor needs.\n *\n * Install it AFTER searchPlugin in the plugins array, since it reads the collection that one\n * creates.\n */\nexport const searchPlugin =\n (pluginOptions: SearchPluginConfig) =>\n (config: Config): Config => {\n if (pluginOptions.disabled) {\n return config\n }\n\n assertConfig(pluginOptions)\n\n const analytics = resolveAnalytics(pluginOptions.analytics)\n const prefix = pluginOptions.routePrefix ?? '/site-search'\n const requireAdmin = pluginOptions.requireAdminForOperations ?? true\n\n searchIndexCache.configure(pluginOptions.cacheTTL ?? 60_000)\n\n if (analytics.enabled) {\n config.collections = [\n ...(config.collections || []),\n createSearchEventsCollection({ slug: analytics.collectionSlug }),\n ]\n }\n\n config.endpoints = [\n ...(config.endpoints || []),\n {\n handler: createSearchHandler({ cache: searchIndexCache, config: pluginOptions }),\n method: 'get',\n path: prefix,\n },\n {\n handler: createReindexHandler({\n cache: searchIndexCache,\n config: pluginOptions,\n requireAdmin,\n }),\n method: 'post',\n path: `${prefix}/reindex`,\n },\n {\n handler: createInspectHandler({\n cache: searchIndexCache,\n config: pluginOptions,\n requireAdmin,\n }),\n method: 'get',\n path: `${prefix}/inspect`,\n },\n ...(analytics.enabled\n ? [\n {\n handler: createTrackHandler({ config: pluginOptions }),\n method: 'post' as const,\n path: `${prefix}/track`,\n },\n ]\n : []),\n ]\n\n return config\n }\n"],"names":["searchIndexCache","createSearchEventsCollection","createInspectHandler","createReindexHandler","createSearchHandler","createTrackHandler","assertConfig","resolveAnalytics","aggregateEvents","normalizeQuery","recordSearch","SearchIndexCache","decodeEntities","hrefFor","projectDocs","DEFAULT_FIELDS","DEFAULT_FUZZY","groupResults","presetResults","rankDocs","createSearchService","searchPlugin","pluginOptions","config","disabled","analytics","prefix","routePrefix","requireAdmin","requireAdminForOperations","configure","cacheTTL","enabled","collections","slug","collectionSlug","endpoints","handler","cache","method","path"],"mappings":"AAIA,SAASA,gBAAgB,QAAQ,aAAY;AAC7C,SAASC,4BAA4B,QAAQ,gCAA+B;AAC5E,SACEC,oBAAoB,EACpBC,oBAAoB,EACpBC,mBAAmB,EACnBC,kBAAkB,QACb,0BAAyB;AAChC,SAASC,YAAY,EAAEC,gBAAgB,QAAQ,eAAc;AAE7D,SAASC,eAAe,EAAEC,cAAc,EAAEC,YAAY,QAAQ,iBAAgB;AAC9E,SAASC,gBAAgB,EAAEX,gBAAgB,QAAQ,aAAY;AAC/D,SAASY,cAAc,QAAQ,sBAAqB;AACpD,SAASC,OAAO,EAAEC,WAAW,QAAQ,eAAc;AACnD,SAASC,cAAc,EAAEC,aAAa,EAAEC,YAAY,EAAEC,aAAa,EAAEC,QAAQ,QAAQ,YAAW;AAChG,SAASC,mBAAmB,QAAQ,eAAc;AAGlD;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,eACX,CAACC,gBACD,CAACC;QACC,IAAID,cAAcE,QAAQ,EAAE;YAC1B,OAAOD;QACT;QAEAjB,aAAagB;QAEb,MAAMG,YAAYlB,iBAAiBe,cAAcG,SAAS;QAC1D,MAAMC,SAASJ,cAAcK,WAAW,IAAI;QAC5C,MAAMC,eAAeN,cAAcO,yBAAyB,IAAI;QAEhE7B,iBAAiB8B,SAAS,CAACR,cAAcS,QAAQ,IAAI;QAErD,IAAIN,UAAUO,OAAO,EAAE;YACrBT,OAAOU,WAAW,GAAG;mBACfV,OAAOU,WAAW,IAAI,EAAE;gBAC5BhC,6BAA6B;oBAAEiC,MAAMT,UAAUU,cAAc;gBAAC;aAC/D;QACH;QAEAZ,OAAOa,SAAS,GAAG;eACbb,OAAOa,SAAS,IAAI,EAAE;YAC1B;gBACEC,SAASjC,oBAAoB;oBAAEkC,OAAOtC;oBAAkBuB,QAAQD;gBAAc;gBAC9EiB,QAAQ;gBACRC,MAAMd;YACR;YACA;gBACEW,SAASlC,qBAAqB;oBAC5BmC,OAAOtC;oBACPuB,QAAQD;oBACRM;gBACF;gBACAW,QAAQ;gBACRC,MAAM,GAAGd,OAAO,QAAQ,CAAC;YAC3B;YACA;gBACEW,SAASnC,qBAAqB;oBAC5BoC,OAAOtC;oBACPuB,QAAQD;oBACRM;gBACF;gBACAW,QAAQ;gBACRC,MAAM,GAAGd,OAAO,QAAQ,CAAC;YAC3B;eACID,UAAUO,OAAO,GACjB;gBACE;oBACEK,SAAShC,mBAAmB;wBAAEkB,QAAQD;oBAAc;oBACpDiB,QAAQ;oBACRC,MAAM,GAAGd,OAAO,MAAM,CAAC;gBACzB;aACD,GACD,EAAE;SACP;QAED,OAAOH;IACT,EAAC"}
@@ -0,0 +1,11 @@
1
+ import type { AnalyticsOptions, SearchPluginConfig } from './types.js';
2
+ export declare const DEFAULT_ANALYTICS: Required<AnalyticsOptions>;
3
+ /** Normalise the `analytics` option, which accepts a boolean shorthand. */
4
+ export declare const resolveAnalytics: (analytics: SearchPluginConfig["analytics"]) => Required<AnalyticsOptions>;
5
+ /**
6
+ * Fail loudly on a misconfiguration rather than silently returning nothing.
7
+ *
8
+ * A collection pointing at a group that does not exist is the most likely mistake, and its symptom
9
+ * — results vanishing — is indistinguishable from an empty index.
10
+ */
11
+ export declare function assertConfig(config: SearchPluginConfig): void;
@@ -0,0 +1,42 @@
1
+ export const DEFAULT_ANALYTICS = {
2
+ collectionSlug: 'search-events',
3
+ enabled: false,
4
+ // Long enough to spot a trend, short enough that the log stays bounded and the retention
5
+ // question is answered up front rather than by accumulation.
6
+ retentionDays: 90
7
+ };
8
+ /** Normalise the `analytics` option, which accepts a boolean shorthand. */ export const resolveAnalytics = (analytics)=>{
9
+ if (analytics === undefined) {
10
+ return DEFAULT_ANALYTICS;
11
+ }
12
+ if (typeof analytics === 'boolean') {
13
+ return {
14
+ ...DEFAULT_ANALYTICS,
15
+ enabled: analytics
16
+ };
17
+ }
18
+ return {
19
+ collectionSlug: analytics.collectionSlug ?? DEFAULT_ANALYTICS.collectionSlug,
20
+ enabled: analytics.enabled ?? true,
21
+ retentionDays: analytics.retentionDays ?? DEFAULT_ANALYTICS.retentionDays
22
+ };
23
+ };
24
+ /**
25
+ * Fail loudly on a misconfiguration rather than silently returning nothing.
26
+ *
27
+ * A collection pointing at a group that does not exist is the most likely mistake, and its symptom
28
+ * — results vanishing — is indistinguishable from an empty index.
29
+ */ export function assertConfig(config) {
30
+ const groups = new Set(config.groups.map((group)=>group.slug));
31
+ for (const entry of config.collections){
32
+ if (!groups.has(entry.group)) {
33
+ throw new Error(`search-plugin: collection "${String(entry.slug)}" is assigned to group "${entry.group}", which is not configured.`);
34
+ }
35
+ }
36
+ const duplicateGroup = config.groups.find((group, index)=>config.groups.findIndex((other)=>other.slug === group.slug) !== index);
37
+ if (duplicateGroup) {
38
+ throw new Error(`search-plugin: duplicate group "${duplicateGroup.slug}".`);
39
+ }
40
+ }
41
+
42
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/options.ts"],"sourcesContent":["import type { AnalyticsOptions, SearchPluginConfig } from './types.js'\n\nexport const DEFAULT_ANALYTICS: Required<AnalyticsOptions> = {\n collectionSlug: 'search-events',\n enabled: false,\n // Long enough to spot a trend, short enough that the log stays bounded and the retention\n // question is answered up front rather than by accumulation.\n retentionDays: 90,\n}\n\n/** Normalise the `analytics` option, which accepts a boolean shorthand. */\nexport const resolveAnalytics = (\n analytics: SearchPluginConfig['analytics'],\n): Required<AnalyticsOptions> => {\n if (analytics === undefined) {\n return DEFAULT_ANALYTICS\n }\n if (typeof analytics === 'boolean') {\n return { ...DEFAULT_ANALYTICS, enabled: analytics }\n }\n return {\n collectionSlug: analytics.collectionSlug ?? DEFAULT_ANALYTICS.collectionSlug,\n enabled: analytics.enabled ?? true,\n retentionDays: analytics.retentionDays ?? DEFAULT_ANALYTICS.retentionDays,\n }\n}\n\n/**\n * Fail loudly on a misconfiguration rather than silently returning nothing.\n *\n * A collection pointing at a group that does not exist is the most likely mistake, and its symptom\n * — results vanishing — is indistinguishable from an empty index.\n */\nexport function assertConfig(config: SearchPluginConfig): void {\n const groups = new Set(config.groups.map((group) => group.slug))\n\n for (const entry of config.collections) {\n if (!groups.has(entry.group)) {\n throw new Error(\n `search-plugin: collection \"${String(entry.slug)}\" is assigned to group \"${entry.group}\", which is not configured.`,\n )\n }\n }\n\n const duplicateGroup = config.groups.find(\n (group, index) => config.groups.findIndex((other) => other.slug === group.slug) !== index,\n )\n if (duplicateGroup) {\n throw new Error(`search-plugin: duplicate group \"${duplicateGroup.slug}\".`)\n }\n}\n"],"names":["DEFAULT_ANALYTICS","collectionSlug","enabled","retentionDays","resolveAnalytics","analytics","undefined","assertConfig","config","groups","Set","map","group","slug","entry","collections","has","Error","String","duplicateGroup","find","index","findIndex","other"],"mappings":"AAEA,OAAO,MAAMA,oBAAgD;IAC3DC,gBAAgB;IAChBC,SAAS;IACT,yFAAyF;IACzF,6DAA6D;IAC7DC,eAAe;AACjB,EAAC;AAED,yEAAyE,GACzE,OAAO,MAAMC,mBAAmB,CAC9BC;IAEA,IAAIA,cAAcC,WAAW;QAC3B,OAAON;IACT;IACA,IAAI,OAAOK,cAAc,WAAW;QAClC,OAAO;YAAE,GAAGL,iBAAiB;YAAEE,SAASG;QAAU;IACpD;IACA,OAAO;QACLJ,gBAAgBI,UAAUJ,cAAc,IAAID,kBAAkBC,cAAc;QAC5EC,SAASG,UAAUH,OAAO,IAAI;QAC9BC,eAAeE,UAAUF,aAAa,IAAIH,kBAAkBG,aAAa;IAC3E;AACF,EAAC;AAED;;;;;CAKC,GACD,OAAO,SAASI,aAAaC,MAA0B;IACrD,MAAMC,SAAS,IAAIC,IAAIF,OAAOC,MAAM,CAACE,GAAG,CAAC,CAACC,QAAUA,MAAMC,IAAI;IAE9D,KAAK,MAAMC,SAASN,OAAOO,WAAW,CAAE;QACtC,IAAI,CAACN,OAAOO,GAAG,CAACF,MAAMF,KAAK,GAAG;YAC5B,MAAM,IAAIK,MACR,CAAC,2BAA2B,EAAEC,OAAOJ,MAAMD,IAAI,EAAE,wBAAwB,EAAEC,MAAMF,KAAK,CAAC,2BAA2B,CAAC;QAEvH;IACF;IAEA,MAAMO,iBAAiBX,OAAOC,MAAM,CAACW,IAAI,CACvC,CAACR,OAAOS,QAAUb,OAAOC,MAAM,CAACa,SAAS,CAAC,CAACC,QAAUA,MAAMV,IAAI,KAAKD,MAAMC,IAAI,MAAMQ;IAEtF,IAAIF,gBAAgB;QAClB,MAAM,IAAIF,MAAM,CAAC,gCAAgC,EAAEE,eAAeN,IAAI,CAAC,EAAE,CAAC;IAC5E;AACF"}
@@ -0,0 +1,37 @@
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
+ };
16
+ export type ProjectionResult = {
17
+ docs: IndexedDoc[];
18
+ skipped: {
19
+ id: string;
20
+ reason: string;
21
+ slug: string;
22
+ }[];
23
+ };
24
+ /**
25
+ * Turn plugin-search rows into the flat projection the read path searches.
26
+ *
27
+ * Rows are dropped rather than half-rendered when they cannot produce a working result, and every
28
+ * drop is recorded with a reason — an inventory count tells you nothing when the document you care
29
+ * about is the one that is missing.
30
+ */
31
+ export declare function projectDocs({ collections, decode, rows, }: {
32
+ collections: SearchableCollection[];
33
+ decode?: boolean;
34
+ rows: SearchDoc[];
35
+ }): ProjectionResult;
36
+ /** Build the href for a projected document. */
37
+ export declare const hrefFor: (doc: IndexedDoc) => string;
@@ -0,0 +1,82 @@
1
+ import { decodeEntities } from './decodeEntities.js';
2
+ /**
3
+ * Turn plugin-search rows into the flat projection the read path searches.
4
+ *
5
+ * Rows are dropped rather than half-rendered when they cannot produce a working result, and every
6
+ * drop is recorded with a reason — an inventory count tells you nothing when the document you care
7
+ * about is the one that is missing.
8
+ */ export function projectDocs({ collections, decode = true, rows }) {
9
+ const byslug = new Map(collections.map((entry)=>[
10
+ entry.slug,
11
+ entry
12
+ ]));
13
+ const docs = [];
14
+ const skipped = [];
15
+ for (const row of rows){
16
+ const collection = row.doc?.relationTo;
17
+ const id = String(row.doc?.value ?? row.id ?? '');
18
+ if (!collection) {
19
+ skipped.push({
20
+ id,
21
+ slug: '',
22
+ reason: 'no source collection on the index row'
23
+ });
24
+ continue;
25
+ }
26
+ const config = byslug.get(collection);
27
+ if (!config) {
28
+ skipped.push({
29
+ id,
30
+ slug: collection,
31
+ reason: `collection "${collection}" is not configured`
32
+ });
33
+ continue;
34
+ }
35
+ const slug = row.slug;
36
+ const title = row.title || row.meta?.title;
37
+ if (!slug) {
38
+ skipped.push({
39
+ id,
40
+ slug: collection,
41
+ reason: 'no slug, so no URL can be built'
42
+ });
43
+ continue;
44
+ }
45
+ if (!title) {
46
+ skipped.push({
47
+ id,
48
+ slug: collection,
49
+ reason: 'no title to display'
50
+ });
51
+ continue;
52
+ }
53
+ if (config.excludeSlugs?.includes(slug)) {
54
+ skipped.push({
55
+ id,
56
+ slug: collection,
57
+ reason: 'excluded by config'
58
+ });
59
+ continue;
60
+ }
61
+ docs.push({
62
+ id: `${collection}-${id}`,
63
+ collection,
64
+ description: decode ? decodeEntities(row.meta?.description) : row.meta?.description ?? undefined,
65
+ group: config.group,
66
+ icon: config.icon,
67
+ // An empty prefix is meaningful: it marks a collection served at the site root. Compared
68
+ // against undefined rather than truthiness so those documents are not silently dropped.
69
+ slug,
70
+ path: config.path,
71
+ title: decode ? decodeEntities(title) : title,
72
+ weight: config.weight ?? 1
73
+ });
74
+ }
75
+ return {
76
+ docs,
77
+ skipped
78
+ };
79
+ }
80
+ /** Build the href for a projected document. */ export const hrefFor = (doc)=>`${doc.path}/${doc.slug}`;
81
+
82
+ //# sourceMappingURL=project.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/project.ts"],"sourcesContent":["import type { IndexedDoc, SearchableCollection } from './types.js'\n\nimport { decodeEntities } from './decodeEntities.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({ id, slug: '', reason: 'no source collection on the index row' })\n continue\n }\n\n const config = byslug.get(collection)\n if (!config) {\n skipped.push({ id, slug: collection, reason: `collection \"${collection}\" is not configured` })\n continue\n }\n\n const slug = row.slug\n const title = row.title || row.meta?.title\n\n if (!slug) {\n skipped.push({ id, slug: collection, reason: 'no slug, so no URL can be built' })\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":"AAEA,SAASA,cAAc,QAAQ,sBAAqB;AAgBpD;;;;;;CAMC,GACD,OAAO,SAASC,YAAY,EAC1BC,WAAW,EACXC,SAAS,IAAI,EACbC,IAAI,EAKL;IACC,MAAMC,SAAS,IAAIC,IAAIJ,YAAYK,GAAG,CAAC,CAACC,QAAU;YAACA,MAAMC,IAAI;YAAED;SAAM;IACrE,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;gBAAEH;gBAAIP,MAAM;gBAAIW,QAAQ;YAAwC;YAC7E;QACF;QAEA,MAAMC,SAAShB,OAAOiB,GAAG,CAACT;QAC1B,IAAI,CAACQ,QAAQ;YACXV,QAAQQ,IAAI,CAAC;gBAAEH;gBAAIP,MAAMI;gBAAYO,QAAQ,CAAC,YAAY,EAAEP,WAAW,mBAAmB,CAAC;YAAC;YAC5F;QACF;QAEA,MAAMJ,OAAOG,IAAIH,IAAI;QACrB,MAAMc,QAAQX,IAAIW,KAAK,IAAIX,IAAIY,IAAI,EAAED;QAErC,IAAI,CAACd,MAAM;YACTE,QAAQQ,IAAI,CAAC;gBAAEH;gBAAIP,MAAMI;gBAAYO,QAAQ;YAAkC;YAC/E;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,CAAA"}