@rubixstudios/payload-typesense 1.6.13 → 1.8.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 (186) hide show
  1. package/README.md +109 -114
  2. package/dist/components/ThemeProvider.d.ts +4 -3
  3. package/dist/components/ThemeProvider.d.ts.map +1 -1
  4. package/dist/components/ThemeProvider.js +15 -5
  5. package/dist/components/icons/clockIcon.d.ts +2 -0
  6. package/dist/components/icons/clockIcon.d.ts.map +1 -0
  7. package/dist/components/icons/clockIcon.js +16 -0
  8. package/dist/components/icons/collectionIcon.d.ts +2 -0
  9. package/dist/components/icons/collectionIcon.d.ts.map +1 -0
  10. package/dist/components/icons/collectionIcon.js +16 -0
  11. package/dist/components/icons/errorIcon.d.ts +2 -0
  12. package/dist/components/icons/errorIcon.d.ts.map +1 -0
  13. package/dist/components/icons/errorIcon.js +16 -0
  14. package/dist/components/icons/index.d.ts +7 -0
  15. package/dist/components/icons/index.d.ts.map +1 -0
  16. package/dist/components/icons/index.js +6 -0
  17. package/dist/components/icons/noResultsIcon.d.ts +4 -0
  18. package/dist/components/icons/noResultsIcon.d.ts.map +1 -0
  19. package/dist/components/icons/noResultsIcon.js +19 -0
  20. package/dist/components/icons/searchIcon.d.ts +4 -0
  21. package/dist/components/icons/searchIcon.d.ts.map +1 -0
  22. package/dist/components/icons/searchIcon.js +16 -0
  23. package/dist/components/icons/xIcon.d.ts +2 -0
  24. package/dist/components/icons/xIcon.d.ts.map +1 -0
  25. package/dist/components/icons/xIcon.js +17 -0
  26. package/dist/components/index.d.ts +10 -5
  27. package/dist/components/index.d.ts.map +1 -1
  28. package/dist/components/index.js +6 -3
  29. package/dist/components/render/Content.d.ts +26 -0
  30. package/dist/components/render/Content.d.ts.map +1 -0
  31. package/dist/components/render/Content.js +144 -0
  32. package/dist/components/render/Dialog.d.ts +20 -0
  33. package/dist/components/render/Dialog.d.ts.map +1 -0
  34. package/dist/components/render/Dialog.js +43 -0
  35. package/dist/components/render/Header.d.ts +4 -4
  36. package/dist/components/render/Header.d.ts.map +1 -1
  37. package/dist/components/render/Header.js +20 -39
  38. package/dist/components/render/Highlight.d.ts +3 -0
  39. package/dist/components/render/Highlight.d.ts.map +1 -0
  40. package/dist/components/render/Highlight.js +22 -0
  41. package/dist/components/render/NoResults.d.ts +4 -4
  42. package/dist/components/render/NoResults.d.ts.map +1 -1
  43. package/dist/components/render/NoResults.js +21 -45
  44. package/dist/components/render/ResultError.d.ts +4 -4
  45. package/dist/components/render/ResultError.d.ts.map +1 -1
  46. package/dist/components/render/ResultError.js +14 -38
  47. package/dist/components/render/Results.d.ts +7 -6
  48. package/dist/components/render/Results.d.ts.map +1 -1
  49. package/dist/components/render/Results.js +70 -141
  50. package/dist/components/render/index.d.ts +7 -4
  51. package/dist/components/render/index.d.ts.map +1 -1
  52. package/dist/components/render/index.js +7 -4
  53. package/dist/components/search/HeadlessDialog.d.ts +5 -0
  54. package/dist/components/search/HeadlessDialog.d.ts.map +1 -0
  55. package/dist/components/search/HeadlessDialog.js +254 -0
  56. package/dist/components/search/HeadlessInput.d.ts +5 -0
  57. package/dist/components/search/HeadlessInput.d.ts.map +1 -0
  58. package/dist/components/search/HeadlessInput.js +193 -0
  59. package/dist/components/search/SearchStyles.d.ts +8 -0
  60. package/dist/components/search/SearchStyles.d.ts.map +1 -0
  61. package/dist/components/search/SearchStyles.js +9 -0
  62. package/dist/components/themes/constant.d.ts +3 -0
  63. package/dist/components/themes/constant.d.ts.map +1 -0
  64. package/dist/components/themes/constant.js +75 -0
  65. package/dist/components/themes/hooks.d.ts +4 -42
  66. package/dist/components/themes/hooks.d.ts.map +1 -1
  67. package/dist/components/themes/hooks.js +35 -95
  68. package/dist/components/themes/index.d.ts +1 -0
  69. package/dist/components/themes/index.d.ts.map +1 -1
  70. package/dist/components/themes/index.js +1 -0
  71. package/dist/components/themes/themes.d.ts.map +1 -1
  72. package/dist/components/themes/themes.js +66 -27
  73. package/dist/components/themes/types.d.ts +62 -2
  74. package/dist/components/themes/types.d.ts.map +1 -1
  75. package/dist/components/themes/utils.d.ts +13 -18
  76. package/dist/components/themes/utils.d.ts.map +1 -1
  77. package/dist/components/themes/utils.js +466 -344
  78. package/dist/components/utils/decodeEntities.d.ts +2 -0
  79. package/dist/components/utils/decodeEntities.d.ts.map +1 -0
  80. package/dist/components/utils/decodeEntities.js +23 -0
  81. package/dist/components/utils/index.d.ts +4 -0
  82. package/dist/components/utils/index.d.ts.map +1 -0
  83. package/dist/components/utils/index.js +3 -0
  84. package/dist/components/utils/toKebab.d.ts +2 -0
  85. package/dist/components/utils/toKebab.d.ts.map +1 -0
  86. package/dist/components/utils/toKebab.js +3 -0
  87. package/dist/components/utils/toText.d.ts +2 -0
  88. package/dist/components/utils/toText.d.ts.map +1 -0
  89. package/dist/components/utils/toText.js +3 -0
  90. package/dist/endpoints/handler/createAdvancedSearch.d.ts +1 -1
  91. package/dist/endpoints/handler/createAdvancedSearch.d.ts.map +1 -1
  92. package/dist/endpoints/handler/createAdvancedSearch.js +133 -11
  93. package/dist/endpoints/handler/createCollections.d.ts +1 -1
  94. package/dist/endpoints/handler/createCollections.d.ts.map +1 -1
  95. package/dist/endpoints/handler/createCollections.js +8 -8
  96. package/dist/endpoints/handler/createSearch.d.ts +1 -1
  97. package/dist/endpoints/handler/createSearch.d.ts.map +1 -1
  98. package/dist/endpoints/handler/createSearch.js +85 -110
  99. package/dist/endpoints/handler/createSuggest.d.ts +1 -1
  100. package/dist/endpoints/handler/createSuggest.d.ts.map +1 -1
  101. package/dist/endpoints/handler/createSuggest.js +39 -22
  102. package/dist/endpoints/health.d.ts +2 -2
  103. package/dist/endpoints/health.d.ts.map +1 -1
  104. package/dist/endpoints/health.js +58 -52
  105. package/dist/endpoints/search.d.ts +2 -9
  106. package/dist/endpoints/search.d.ts.map +1 -1
  107. package/dist/endpoints/search.js +17 -16
  108. package/dist/{utils → hooks}/useDebounce.d.ts.map +1 -1
  109. package/dist/{utils → hooks}/useDebounce.js +2 -2
  110. package/dist/hooks/useSearch.d.ts +21 -0
  111. package/dist/hooks/useSearch.d.ts.map +1 -0
  112. package/dist/hooks/useSearch.js +126 -0
  113. package/dist/index.d.ts.map +1 -1
  114. package/dist/index.js +45 -34
  115. package/dist/lib/cache.d.ts.map +1 -1
  116. package/dist/lib/cache.js +54 -25
  117. package/dist/lib/client.d.ts +1 -1
  118. package/dist/lib/client.d.ts.map +1 -1
  119. package/dist/lib/client.js +35 -31
  120. package/dist/lib/hooks.d.ts +3 -11
  121. package/dist/lib/hooks.d.ts.map +1 -1
  122. package/dist/lib/hooks.js +15 -45
  123. package/dist/lib/initialization.d.ts +1 -1
  124. package/dist/lib/initialization.d.ts.map +1 -1
  125. package/dist/lib/initialization.js +54 -52
  126. package/dist/lib/schema-mapper.d.ts +3 -6
  127. package/dist/lib/schema-mapper.d.ts.map +1 -1
  128. package/dist/lib/schema-mapper.js +90 -84
  129. package/dist/lib/search-dialog.d.ts +169 -0
  130. package/dist/lib/search-dialog.d.ts.map +1 -0
  131. package/dist/lib/search-dialog.js +4 -0
  132. package/dist/lib/search-input.d.ts +93 -0
  133. package/dist/lib/search-input.d.ts.map +1 -0
  134. package/dist/lib/search-pagination.d.ts +38 -0
  135. package/dist/lib/search-pagination.d.ts.map +1 -0
  136. package/dist/lib/search-pagination.js +4 -0
  137. package/dist/lib/search.d.ts +25 -0
  138. package/dist/lib/search.d.ts.map +1 -0
  139. package/dist/lib/search.js +59 -0
  140. package/dist/lib/validation.d.ts +57 -39
  141. package/dist/lib/validation.d.ts.map +1 -1
  142. package/dist/lib/validation.js +92 -66
  143. package/dist/types.d.ts +193 -127
  144. package/dist/types.d.ts.map +1 -1
  145. package/dist/types.js +1 -1
  146. package/dist/utils/buildError.d.ts +1 -1
  147. package/dist/utils/buildError.d.ts.map +1 -1
  148. package/dist/utils/buildError.js +2 -2
  149. package/dist/utils/ensureCollection.d.ts +2 -2
  150. package/dist/utils/ensureCollection.d.ts.map +1 -1
  151. package/dist/utils/ensureCollection.js +138 -22
  152. package/dist/utils/extractText.d.ts.map +1 -1
  153. package/dist/utils/extractText.js +11 -8
  154. package/dist/utils/getCacheStats.d.ts.map +1 -1
  155. package/dist/utils/getCacheStats.js +1 -8
  156. package/dist/utils/getCollectionInfo.d.ts.map +1 -1
  157. package/dist/utils/getCollectionInfo.js +1 -1
  158. package/dist/utils/getCollections.d.ts +11 -0
  159. package/dist/utils/getCollections.d.ts.map +1 -0
  160. package/dist/utils/getCollections.js +152 -0
  161. package/dist/utils/keyboard.d.ts +4 -4
  162. package/dist/utils/keyboard.d.ts.map +1 -1
  163. package/dist/utils/keyboard.js +21 -23
  164. package/dist/utils/sortResults.d.ts +3 -0
  165. package/dist/utils/sortResults.d.ts.map +1 -0
  166. package/dist/utils/sortResults.js +103 -0
  167. package/dist/utils/testConnection.d.ts +1 -1
  168. package/dist/utils/testConnection.d.ts.map +1 -1
  169. package/dist/utils/testConnection.js +2 -2
  170. package/dist/utils/vectorSearch.d.ts +2 -5
  171. package/dist/utils/vectorSearch.d.ts.map +1 -1
  172. package/dist/utils/vectorSearch.js +24 -12
  173. package/package.json +16 -15
  174. package/dist/components/HeadlessSearchInput.d.ts +0 -5
  175. package/dist/components/HeadlessSearchInput.d.ts.map +0 -1
  176. package/dist/components/HeadlessSearchInput.js +0 -204
  177. package/dist/lib/headlessSearch.d.ts +0 -86
  178. package/dist/lib/headlessSearch.d.ts.map +0 -1
  179. package/dist/utils/getAllCollections.d.ts +0 -11
  180. package/dist/utils/getAllCollections.d.ts.map +0 -1
  181. package/dist/utils/getAllCollections.js +0 -103
  182. package/dist/utils/useSearch.d.ts +0 -18
  183. package/dist/utils/useSearch.d.ts.map +0 -1
  184. package/dist/utils/useSearch.js +0 -66
  185. /package/dist/{utils → hooks}/useDebounce.d.ts +0 -0
  186. /package/dist/lib/{headlessSearch.js → search-input.js} +0 -0
@@ -3,107 +3,113 @@ import { buildError } from '../utils/buildError.js';
3
3
  import { getCacheStats } from '../utils/getCacheStats.js';
4
4
  import { getCollectionInfo } from '../utils/getCollectionInfo.js';
5
5
  import { testConnection } from '../utils/testConnection.js';
6
- export const createHealthCheck = (typesenseClient, _pluginOptions, lastSyncTime)=>{
6
+ export const createHealthCheck = (client, _config, lastSyncTime)=>{
7
7
  return async ()=>{
8
8
  const start = Date.now();
9
9
  try {
10
- const isTypesenseHealthy = await testConnection(typesenseClient);
11
- const collections = isTypesenseHealthy ? await getCollectionInfo(typesenseClient) : [];
12
- const cacheStats = getCacheStats();
13
- const isHealthy = isTypesenseHealthy && collections.length > 0;
14
- const base = {
15
- cache: cacheStats,
10
+ const health = await testConnection(client);
11
+ const collections = health ? await getCollectionInfo(client) : [];
12
+ const isHealthy = health && collections.length > 0;
13
+ const error = buildError(health, collections.length > 0);
14
+ const response = {
15
+ cache: getCacheStats(),
16
16
  collections,
17
17
  status: isHealthy ? 'healthy' : 'unhealthy',
18
18
  typesense: {
19
- ok: isTypesenseHealthy,
19
+ ok: health,
20
20
  version: 'unknown'
21
21
  },
22
22
  ...lastSyncTime !== undefined && {
23
23
  lastSync: lastSyncTime
24
+ },
25
+ ...error && {
26
+ error
24
27
  }
25
28
  };
26
- const error = buildError(isTypesenseHealthy, collections.length > 0);
27
- const responseTime = Date.now() - start;
28
29
  return Response.json({
29
- ...base,
30
- ...error && {
31
- error
32
- },
33
- responseTime,
30
+ ...response,
31
+ responseTime: Date.now() - start,
34
32
  timestamp: new Date().toISOString(),
35
33
  version: pkg.version
34
+ }, {
35
+ status: isHealthy ? 200 : 503
36
36
  });
37
- } catch (err) {
38
- const errorResponse = {
37
+ } catch (error) {
38
+ return Response.json({
39
39
  cache: getCacheStats(),
40
- error: err instanceof Error ? err.message : 'Unknown error',
41
- status: 'unhealthy'
42
- };
43
- return Response.json(errorResponse, {
40
+ error: error instanceof Error ? error.message : 'Unknown error',
41
+ responseTime: Date.now() - start,
42
+ status: 'unhealthy',
43
+ timestamp: new Date().toISOString(),
44
+ version: pkg.version
45
+ }, {
44
46
  status: 500
45
47
  });
46
48
  }
47
49
  };
48
50
  };
49
- export const createDetailedHealthCheck = (typesenseClient, pluginOptions, lastSyncTime)=>{
51
+ export const createDetailedHealthCheck = (client, config, lastSyncTime)=>{
50
52
  return async ()=>{
51
53
  const start = Date.now();
52
54
  try {
53
- const isTypesenseHealthy = await testConnection(typesenseClient);
55
+ const health = await testConnection(client);
54
56
  let collectionDetails = [];
55
- if (isTypesenseHealthy) {
57
+ let collectionError;
58
+ if (health) {
56
59
  try {
57
- const collectionsData = await typesenseClient.collections().retrieve();
58
- collectionDetails = collectionsData.map((col)=>({
59
- name: col.name,
60
- createdAt: col.created_at,
61
- fields: col.fields?.length || 0,
62
- numDocuments: col.num_documents
60
+ const collectionsData = await client.collections().retrieve();
61
+ collectionDetails = collectionsData.map((collection)=>({
62
+ createdAt: collection.created_at,
63
+ fields: collection.fields?.length || 0,
64
+ name: collection.name,
65
+ numDocuments: collection.num_documents
63
66
  }));
64
67
  } catch {
65
- // ignore detailed retrieval error
68
+ collectionError = 'Failed to retrieve collection details';
66
69
  }
67
70
  }
68
- const collections = collectionDetails.map((c)=>c.name);
69
- const cacheStats = getCacheStats();
71
+ const collections = collectionDetails.map((collection)=>collection.name);
72
+ const isHealthy = health && !collectionError && collections.length > 0;
73
+ const error = collectionError || buildError(health, collections.length > 0);
70
74
  const configInfo = {
71
- enabledCollections: Object.entries(pluginOptions.collections || {}).filter(([_, config])=>config?.enabled).map(([name, config])=>({
75
+ enabledCollections: Object.entries(config.collections || {}).filter(([, collection])=>collection?.enabled).map(([name, collection])=>({
72
76
  name,
73
- displayName: config?.displayName,
74
- facetFields: config?.facetFields || [],
75
- searchFields: config?.searchFields || []
77
+ displayName: collection?.displayName,
78
+ facetFields: collection?.facetFields || [],
79
+ searchFields: collection?.searchFields || []
76
80
  })),
77
- settings: pluginOptions.settings,
78
- totalCollections: Object.keys(pluginOptions.collections || {}).length
81
+ totalCollections: Object.keys(config.collections || {}).length
79
82
  };
80
- const isHealthy = isTypesenseHealthy && collectionDetails.length > 0;
81
83
  const response = {
82
- cache: cacheStats,
84
+ cache: getCacheStats(),
83
85
  collectionDetails,
84
86
  collections,
85
87
  config: configInfo,
86
- lastSync: lastSyncTime,
87
- responseTime: Date.now() - start,
88
88
  status: isHealthy ? 'healthy' : 'unhealthy',
89
- timestamp: new Date().toISOString(),
90
89
  typesense: {
91
- ok: isTypesenseHealthy,
90
+ ok: health,
92
91
  version: 'unknown'
93
92
  },
94
- version: pkg.version,
95
- ...isHealthy ? {} : {
96
- error: [
97
- !isTypesenseHealthy && 'Typesense connection failed',
98
- collectionDetails.length === 0 && 'No collections available'
99
- ].filter(Boolean).join(', ')
93
+ ...lastSyncTime !== undefined && {
94
+ lastSync: lastSyncTime
95
+ },
96
+ ...error && {
97
+ error
100
98
  }
101
99
  };
102
- return Response.json(response);
100
+ return Response.json({
101
+ ...response,
102
+ responseTime: Date.now() - start,
103
+ timestamp: new Date().toISOString(),
104
+ version: pkg.version
105
+ }, {
106
+ status: isHealthy ? 200 : 503
107
+ });
103
108
  } catch (error) {
104
109
  return Response.json({
105
110
  cache: getCacheStats(),
106
111
  error: error instanceof Error ? error.message : 'Unknown error',
112
+ responseTime: Date.now() - start,
107
113
  status: 'unhealthy',
108
114
  timestamp: new Date().toISOString(),
109
115
  version: pkg.version
@@ -1,12 +1,5 @@
1
+ import { type Endpoint } from 'payload';
1
2
  import type Typesense from 'typesense';
2
3
  import { type TypesenseConfig } from '../types.js';
3
- export declare const createSearchEndpoints: (typesenseClient: Typesense.Client, pluginOptions: TypesenseConfig, lastSyncTime?: number) => ({
4
- handler: import("payload").PayloadHandler;
5
- method: 'get';
6
- path: string;
7
- } | {
8
- handler: import("payload").PayloadHandler;
9
- method: 'post';
10
- path: string;
11
- })[];
4
+ export declare const createEndpoints: (client: Typesense.Client, config: TypesenseConfig) => Endpoint[];
12
5
  //# sourceMappingURL=search.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/endpoints/search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,SAAS,MAAM,WAAW,CAAA;AAEtC,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAA;AAOlD,eAAO,MAAM,qBAAqB,oBACf,SAAS,CAAC,MAAM,iBAClB,eAAe,iBACf,MAAM;;YAKT,KAAK;;;;YAeL,MAAM;;IAmBnB,CAAA"}
1
+ {"version":3,"file":"search.d.ts","sourceRoot":"","sources":["../../src/endpoints/search.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,SAAS,CAAA;AACvC,OAAO,KAAK,SAAS,MAAM,WAAW,CAAA;AAEtC,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAA;AAOlD,eAAO,MAAM,eAAe,WAAY,SAAS,CAAC,MAAM,UAAU,eAAe,KAAG,QAAQ,EAwC3F,CAAA"}
@@ -3,42 +3,43 @@ import { createCollections } from './handler/createCollections.js';
3
3
  import { createSearch } from './handler/createSearch.js';
4
4
  import { createSuggest } from './handler/createSuggest.js';
5
5
  import { createDetailedHealthCheck, createHealthCheck } from './health.js';
6
- export const createSearchEndpoints = (typesenseClient, pluginOptions, lastSyncTime)=>{
6
+ export const createEndpoints = (client, config)=>{
7
+ const search = createSearch(client, config);
7
8
  return [
8
9
  {
9
- handler: createCollections(pluginOptions),
10
+ handler: createCollections(config),
10
11
  method: 'get',
11
12
  path: '/search/collections'
12
13
  },
13
14
  {
14
- handler: createSuggest(typesenseClient, pluginOptions),
15
+ handler: createHealthCheck(client, config),
15
16
  method: 'get',
16
- path: '/search/:collectionName/suggest'
17
+ path: '/search/health'
17
18
  },
18
19
  {
19
- handler: createSearch(typesenseClient, pluginOptions),
20
+ handler: createDetailedHealthCheck(client, config),
20
21
  method: 'get',
21
- path: '/search/:collectionName'
22
+ path: '/search/health/detailed'
22
23
  },
23
24
  {
24
- handler: createAdvancedSearch(typesenseClient, pluginOptions),
25
- method: 'post',
26
- path: '/search/:collectionName'
25
+ handler: createSuggest(client, config),
26
+ method: 'get',
27
+ path: '/search/:collectionName/suggest'
27
28
  },
28
29
  {
29
- handler: createSearch(typesenseClient, pluginOptions),
30
+ handler: search,
30
31
  method: 'get',
31
- path: '/search'
32
+ path: '/search/:collectionName'
32
33
  },
33
34
  {
34
- handler: createHealthCheck(typesenseClient, pluginOptions, lastSyncTime),
35
- method: 'get',
36
- path: '/search/health'
35
+ handler: createAdvancedSearch(client, config),
36
+ method: 'post',
37
+ path: '/search/:collectionName'
37
38
  },
38
39
  {
39
- handler: createDetailedHealthCheck(typesenseClient, pluginOptions, lastSyncTime),
40
+ handler: search,
40
41
  method: 'get',
41
- path: '/search/health/detailed'
42
+ path: '/search'
42
43
  }
43
44
  ];
44
45
  };
@@ -1 +1 @@
1
- {"version":3,"file":"useDebounce.d.ts","sourceRoot":"","sources":["../../src/utils/useDebounce.ts"],"names":[],"mappings":"AAIA,wBAAgB,WAAW,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,CAAC,CAWzD"}
1
+ {"version":3,"file":"useDebounce.d.ts","sourceRoot":"","sources":["../../src/hooks/useDebounce.ts"],"names":[],"mappings":"AAIA,wBAAgB,WAAW,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,CAAC,CAYzD"}
@@ -3,9 +3,9 @@ import { useEffect, useState } from 'react';
3
3
  export function useDebounce(value, delay) {
4
4
  const [debounced, setDebounced] = useState(value);
5
5
  useEffect(()=>{
6
- const handle = setTimeout(()=>setDebounced(value), delay);
6
+ const timeout = setTimeout(()=>setDebounced(value), delay);
7
7
  return ()=>{
8
- clearTimeout(handle);
8
+ clearTimeout(timeout);
9
9
  };
10
10
  }, [
11
11
  value,
@@ -0,0 +1,21 @@
1
+ import { type SearchMode, type SearchResponse } from '../types.js';
2
+ export type UseSearchOptions<T> = {
3
+ baseUrl: string;
4
+ collections?: string | string[];
5
+ enabled?: boolean;
6
+ minQueryLength: number;
7
+ onResults?: (results: SearchResponse<T>) => void;
8
+ onSearch?: (query: string, results: SearchResponse<T>) => void;
9
+ perPage: number;
10
+ searchMode?: SearchMode;
11
+ numTypos?: 0 | 1 | 2;
12
+ vector?: boolean;
13
+ };
14
+ export declare function useSearch<T = Record<string, unknown>>({ baseUrl, collections, enabled, minQueryLength, onResults, onSearch, perPage, searchMode, numTypos, vector, }: UseSearchOptions<T>): {
15
+ error: string | null;
16
+ isLoading: boolean;
17
+ results: SearchResponse<T> | null;
18
+ search: (searchQuery: string, page?: number) => Promise<void>;
19
+ reset: () => void;
20
+ };
21
+ //# sourceMappingURL=useSearch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useSearch.d.ts","sourceRoot":"","sources":["../../src/hooks/useSearch.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,KAAK,UAAU,EAAE,KAAK,cAAc,EAAE,MAAM,aAAa,CAAA;AAElE,MAAM,MAAM,gBAAgB,CAAC,CAAC,IAAI;IAChC,OAAO,EAAE,MAAM,CAAA;IACf,WAAW,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IAC/B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,cAAc,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,KAAK,IAAI,CAAA;IAChD,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,KAAK,IAAI,CAAA;IAC9D,OAAO,EAAE,MAAM,CAAA;IACf,UAAU,CAAC,EAAE,UAAU,CAAA;IACvB,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IACpB,MAAM,CAAC,EAAE,OAAO,CAAA;CACjB,CAAA;AAED,wBAAgB,SAAS,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,EACrD,OAAO,EACP,WAAW,EACX,OAAc,EACd,cAAc,EACd,SAAS,EACT,QAAQ,EACR,OAAO,EACP,UAAU,EACV,QAAQ,EACR,MAAc,GACf,EAAE,gBAAgB,CAAC,CAAC,CAAC;;;;0BA4CE,MAAM;;EAyG7B"}
@@ -0,0 +1,126 @@
1
+ 'use client';
2
+ import { useCallback, useEffect, useRef, useState } from 'react';
3
+ export function useSearch({ baseUrl, collections, enabled = true, minQueryLength, onResults, onSearch, perPage, searchMode, numTypos, vector = false }) {
4
+ const [results, setResults] = useState(null);
5
+ const [isLoading, setIsLoading] = useState(false);
6
+ const [error, setError] = useState(null);
7
+ const requestRef = useRef(null);
8
+ const onResultsRef = useRef(onResults);
9
+ const onSearchRef = useRef(onSearch);
10
+ const collection = typeof collections === 'string' ? collections : collections?.length === 1 ? collections[0] : undefined;
11
+ const collectionList = Array.isArray(collections) && collections.length > 1 ? collections.join(',') : undefined;
12
+ useEffect(()=>{
13
+ onResultsRef.current = onResults;
14
+ onSearchRef.current = onSearch;
15
+ }, [
16
+ onResults,
17
+ onSearch
18
+ ]);
19
+ const reset = useCallback(()=>{
20
+ requestRef.current?.abort();
21
+ requestRef.current = null;
22
+ setResults(null);
23
+ setIsLoading(false);
24
+ setError(null);
25
+ }, []);
26
+ useEffect(()=>{
27
+ if (!enabled) reset();
28
+ }, [
29
+ enabled,
30
+ reset
31
+ ]);
32
+ useEffect(()=>()=>{
33
+ requestRef.current?.abort();
34
+ requestRef.current = null;
35
+ }, []);
36
+ const search = useCallback(async (searchQuery, page = 1)=>{
37
+ requestRef.current?.abort();
38
+ requestRef.current = null;
39
+ const query = searchQuery.trim();
40
+ if (!enabled || query.length < minQueryLength) {
41
+ reset();
42
+ return;
43
+ }
44
+ const controller = new AbortController();
45
+ requestRef.current = controller;
46
+ setIsLoading(true);
47
+ setError(null);
48
+ try {
49
+ const params = new URLSearchParams({
50
+ per_page: String(perPage),
51
+ page: String(page),
52
+ q: query
53
+ });
54
+ if (searchMode) {
55
+ params.set('search_mode', searchMode);
56
+ } else if (vector) {
57
+ params.set('vector', 'true');
58
+ }
59
+ if (numTypos !== undefined) {
60
+ params.set('num_typos', String(numTypos));
61
+ }
62
+ if (collectionList) {
63
+ params.set('collections', collectionList);
64
+ }
65
+ let end = baseUrl.length;
66
+ while(end > 0 && baseUrl[end - 1] === '/'){
67
+ end--;
68
+ }
69
+ const url = baseUrl.slice(0, end);
70
+ const path = collection ? `/api/search/${encodeURIComponent(collection)}` : '/api/search';
71
+ const response = await fetch(`${url}${path}?${params}`, {
72
+ signal: controller.signal
73
+ });
74
+ if (!response.ok) {
75
+ let message = `Search failed (${response.status})`;
76
+ try {
77
+ const body = await response.json();
78
+ if (typeof body.error === 'string') {
79
+ message = body.error;
80
+ }
81
+ if (typeof body.details === 'string') {
82
+ message += ` (${body.details})`;
83
+ }
84
+ } catch {
85
+ /* Keep the HTTP status when the response is not JSON. */ }
86
+ throw new Error(message);
87
+ }
88
+ const data = await response.json();
89
+ if (requestRef.current !== controller || controller.signal.aborted) {
90
+ return;
91
+ }
92
+ setResults(data);
93
+ onResultsRef.current?.(data);
94
+ onSearchRef.current?.(query, data);
95
+ } catch (err) {
96
+ if (controller.signal.aborted || requestRef.current !== controller) {
97
+ return;
98
+ }
99
+ setError(err instanceof Error ? err.message : 'Search failed');
100
+ setResults(null);
101
+ } finally{
102
+ if (requestRef.current === controller) {
103
+ requestRef.current = null;
104
+ setIsLoading(false);
105
+ }
106
+ }
107
+ }, [
108
+ baseUrl,
109
+ collection,
110
+ collectionList,
111
+ enabled,
112
+ minQueryLength,
113
+ perPage,
114
+ searchMode,
115
+ numTypos,
116
+ vector,
117
+ reset
118
+ ]);
119
+ return {
120
+ error,
121
+ isLoading,
122
+ results,
123
+ search,
124
+ reset
125
+ };
126
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,SAAS,CAAA;AAMrC,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAA;AAEjD,cAAc,uBAAuB,CAAA;AACrC,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAEjD,eAAO,MAAM,eAAe,iBACX,eAAe,sBACb,MAAM,KAAG,MA8CzB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,SAAS,CAAA;AAOrC,OAAO,EAAE,KAAK,eAAe,EAAE,MAAM,YAAY,CAAA;AAEjD,cAAc,uBAAuB,CAAA;AACrC,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAA;AAEjD,eAAO,MAAM,eAAe,iBACX,eAAe,sBACb,MAAM,KAAG,MAsDzB,CAAA"}
package/dist/index.js CHANGED
@@ -1,43 +1,54 @@
1
- import { createSearchEndpoints } from './endpoints/search.js';
1
+ import { createEndpoints } from './endpoints/search.js';
2
2
  import { createClient } from './lib/client.js';
3
- import { deleteDocumentFromTypesense, syncDocumentToTypesense } from './lib/hooks.js';
3
+ import { deleteDoc, syncDoc } from './lib/hooks.js';
4
4
  import { initializeTypesense } from './lib/initialization.js';
5
+ import { getErrors, validateConfig } from './lib/validation.js';
5
6
  export * from './components/index.js';
6
7
  export const typesenseSearch = (pluginConfig)=>(incomingConfig)=>{
7
8
  if (pluginConfig.disabled) return incomingConfig;
8
- const client = createClient(pluginConfig.typesense);
9
- incomingConfig.endpoints = [
10
- ...incomingConfig.endpoints || [],
11
- ...createSearchEndpoints(client, pluginConfig, Date.now())
12
- ];
13
- const shouldAutoSync = pluginConfig.settings?.autoSync !== false;
14
- const hasCollections = !!pluginConfig.collections;
15
- if (shouldAutoSync && hasCollections) {
16
- incomingConfig.collections = (incomingConfig.collections || []).map((collection)=>{
17
- const colConfig = pluginConfig.collections?.[collection.slug];
18
- if (!colConfig?.enabled) return collection;
19
- return {
20
- ...collection,
21
- hooks: {
22
- ...collection.hooks,
23
- afterChange: [
24
- ...collection.hooks?.afterChange || [],
25
- async ({ doc, operation })=>syncDocumentToTypesense(client, collection.slug, doc, operation, colConfig)
26
- ],
27
- afterDelete: [
28
- ...collection.hooks?.afterDelete || [],
29
- async ({ doc })=>deleteDocumentFromTypesense(client, collection.slug, doc.id)
30
- ]
31
- }
32
- };
33
- });
9
+ const validate = validateConfig(pluginConfig);
10
+ if (!validate.success) {
11
+ throw new Error(`Invalid configuration\n${getErrors(validate.errors ?? [])}`);
34
12
  }
35
- const existingOnInit = incomingConfig.onInit;
36
- incomingConfig.onInit = async (payload)=>{
37
- if (existingOnInit) {
38
- await existingOnInit(payload);
13
+ const client = createClient(pluginConfig.typesense);
14
+ const sync = pluginConfig.settings?.autoSync !== false;
15
+ const collections = incomingConfig.collections?.map((collection)=>{
16
+ const config = pluginConfig.collections?.[collection.slug];
17
+ if (!sync || !config?.enabled) {
18
+ return collection;
19
+ }
20
+ return {
21
+ ...collection,
22
+ hooks: {
23
+ ...collection.hooks,
24
+ afterChange: [
25
+ ...collection.hooks?.afterChange || [],
26
+ async ({ doc })=>syncDoc(client, collection.slug, doc, config, pluginConfig.vectorSearch)
27
+ ],
28
+ afterDelete: [
29
+ ...collection.hooks?.afterDelete || [],
30
+ async ({ doc })=>{
31
+ if (typeof doc.id === 'string' || typeof doc.id === 'number') {
32
+ await deleteDoc(client, collection.slug, String(doc.id));
33
+ }
34
+ }
35
+ ]
36
+ }
37
+ };
38
+ });
39
+ const existing = incomingConfig.onInit;
40
+ return {
41
+ ...incomingConfig,
42
+ collections,
43
+ endpoints: [
44
+ ...incomingConfig.endpoints || [],
45
+ ...createEndpoints(client, pluginConfig)
46
+ ],
47
+ onInit: async (payload)=>{
48
+ if (existing) {
49
+ await existing(payload);
50
+ }
51
+ await initializeTypesense(payload, client, pluginConfig);
39
52
  }
40
- await initializeTypesense(payload, client, pluginConfig);
41
53
  };
42
- return incomingConfig;
43
54
  };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AO,CAAC,EAChC,GAAG,CAAC,EAAE,MAAM,GACX,IAAI,CAyBN;CACF;AAED,eAAO,MAAM,WAAW,sBAGtB,CAAA"}
package/dist/lib/cache.js CHANGED
@@ -9,22 +9,34 @@ export class SearchCache {
9
9
  constructor(options = {}){
10
10
  this.defaultTTL = options.ttl ?? 5 * 60 * 1000;
11
11
  this.maxSize = options.maxSize ?? 1000;
12
+ if (!Number.isFinite(this.defaultTTL) || this.defaultTTL < 0) {
13
+ throw new RangeError('Cache TTL must be a non-negative number');
14
+ }
15
+ if (!Number.isSafeInteger(this.maxSize) || this.maxSize < 0) {
16
+ throw new RangeError('Cache maxSize must be a non-negative integer');
17
+ }
12
18
  }
13
19
  evict() {
20
+ if (this.cache.size < this.maxSize) {
21
+ return;
22
+ }
14
23
  this.cleanup();
15
- if (this.cache.size < this.maxSize) return;
16
- const oldestKey = this.cache.keys().next().value;
17
- if (oldestKey) {
18
- this.cache.delete(oldestKey);
24
+ if (this.cache.size < this.maxSize) {
25
+ return;
26
+ }
27
+ const oldest = this.cache.keys().next();
28
+ if (!oldest.done) {
29
+ this.cache.delete(oldest.value);
19
30
  }
20
31
  }
21
32
  generateKey(query, collection, params) {
22
- const base = `${this.normalize(collection)}:${query}`;
23
- const serializedParams = this.serialize(params);
24
- return serializedParams ? `${base}:${serializedParams}` : base;
33
+ return `${this.normalize(collection)}:${JSON.stringify([
34
+ query,
35
+ this.serialize(params)
36
+ ])}`;
25
37
  }
26
38
  isExpired(entry) {
27
- return Date.now() - entry.timestamp > entry.ttl;
39
+ return Date.now() - entry.timestamp >= entry.ttl;
28
40
  }
29
41
  lookup(query, collection, params) {
30
42
  const key = this.generateKey(query, collection, params);
@@ -43,9 +55,15 @@ export class SearchCache {
43
55
  return collection ?? 'universal';
44
56
  }
45
57
  serialize(params) {
46
- if (!params || Object.keys(params).length === 0) return '';
47
- const sorted = Object.keys(params).sort().map((key)=>`${key}=${JSON.stringify(params[key])}`).join('&');
48
- return sorted;
58
+ if (!params || Object.keys(params).length === 0) {
59
+ return '';
60
+ }
61
+ return JSON.stringify(params, (_key, value)=>{
62
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
63
+ return Object.fromEntries(Object.entries(value).sort(([a], [b])=>a.localeCompare(b)));
64
+ }
65
+ return value;
66
+ });
49
67
  }
50
68
  cleanup() {
51
69
  for (const [key, entry] of this.cache.entries()){
@@ -55,13 +73,19 @@ export class SearchCache {
55
73
  }
56
74
  }
57
75
  clear(pattern) {
58
- if (!pattern) {
76
+ if (pattern === undefined) {
59
77
  this.cache.clear();
60
78
  return;
61
79
  }
62
- const matcher = typeof pattern === 'string' ? (key)=>key.includes(pattern) : (key)=>pattern.test(key);
63
80
  for (const key of this.cache.keys()){
64
- if (matcher(key)) {
81
+ let matches;
82
+ if (typeof pattern === 'string') {
83
+ matches = key.includes(pattern);
84
+ } else {
85
+ pattern.lastIndex = 0;
86
+ matches = pattern.test(key);
87
+ }
88
+ if (matches) {
65
89
  this.cache.delete(key);
66
90
  }
67
91
  }
@@ -76,6 +100,7 @@ export class SearchCache {
76
100
  return entry.data;
77
101
  }
78
102
  getStats() {
103
+ this.cleanup();
79
104
  const total = this.stats.hits + this.stats.misses;
80
105
  return {
81
106
  hitRate: total === 0 ? 0 : this.stats.hits / total,
@@ -84,23 +109,27 @@ export class SearchCache {
84
109
  };
85
110
  }
86
111
  has(query, collection, params) {
87
- const key = this.generateKey(query, collection, params);
88
- const entry = this.cache.get(key);
89
- if (!entry || this.isExpired(entry)) {
90
- if (entry) {
91
- this.cache.delete(key);
92
- }
93
- return false;
94
- }
95
- return true;
112
+ return this.lookup(query, collection, params) !== null;
96
113
  }
97
114
  set(query, data, collection, params, ttl) {
115
+ const duration = ttl ?? this.defaultTTL;
116
+ if (!Number.isFinite(duration) || duration < 0) {
117
+ throw new RangeError('Cache TTL must be a non-negative number');
118
+ }
98
119
  const key = this.generateKey(query, collection, params);
99
- this.evict();
120
+ if (this.maxSize === 0 || duration === 0) {
121
+ this.cache.delete(key);
122
+ return;
123
+ }
124
+ if (this.cache.has(key)) {
125
+ this.cache.delete(key);
126
+ } else {
127
+ this.evict();
128
+ }
100
129
  this.cache.set(key, {
101
130
  data,
102
131
  timestamp: Date.now(),
103
- ttl: ttl ?? this.defaultTTL
132
+ ttl: duration
104
133
  });
105
134
  }
106
135
  }